Skip to content

Conversation

Pratham-Mishra04
Copy link
Collaborator

Allow plugins to short-circuit request processing

This PR enhances the plugin system by allowing plugins to short-circuit the request processing flow. The PreHook method signature has been updated to return an optional response in addition to the modified request.

When a plugin returns a non-nil response from its PreHook method, Bifrost will skip the provider call and immediately run all remaining plugins' PostHook methods in reverse order before returning the response to the client.

This change enables plugins to:

  • Serve cached responses
  • Implement custom routing logic
  • Handle certain requests entirely within the plugin

The implementation maintains the existing error handling pattern while adding the new short-circuit capability.

Copy link
Contributor

coderabbitai bot commented Jun 10, 2025

Caution

Review failed

The pull request is closed.

Summary by CodeRabbit

  • New Features
    • Plugins can now perform cleanup actions during shutdown.
    • Plugins have the ability to return a response early in the request lifecycle, bypassing further processing.
  • Documentation
    • Updated plugin documentation to reflect new interface changes, including examples for the updated methods.
  • Refactor
    • Improved error handling and logging for plugin operations and cleanup processes.

Summary by CodeRabbit

  • New Features
    • Enhanced plugin system to allow plugins to provide immediate responses during the pre-processing phase, potentially bypassing the normal request flow.
    • Added a Cleanup() method to the plugin interface for resource release on shutdown.
  • Bug Fixes
    • Improved error handling when processing plugin post-hooks during early exits.

Walkthrough

The changes update the Bifrost plugin system by extending the PreHook method to optionally return a response that short-circuits normal processing. The tryTextCompletion and tryChatCompletion methods now handle this early exit by running PostHook methods of executed plugins in reverse order before returning. A Cleanup() method was added to plugins and invoked on shutdown.

Changes

File(s) Change Summary
core/schemas/plugin.go Updated Plugin interface: PreHook returns (*BifrostRequest, *BifrostResponse, error); added Cleanup() error method.
core/bifrost.go Refactored error handling with helper functions; modified tryTextCompletion and tryChatCompletion to support early exit on PreHook response; added Cleanup() method invoking plugins' cleanup.
core/utils.go Added helper functions newBifrostError and newBifrostErrorFromMsg for consistent error wrapping.
docs/plugins.md Updated plugin interface and examples to reflect new PreHook signature and added Cleanup() method; enhanced documentation on plugin lifecycle and short-circuiting behavior.

Poem

A plugin’s wish, a shortcut path,
Now PreHook answers—skip the aftermath!
If response is ready, we’ll quickly comply,
PostHooks in reverse, then wave goodbye.
Cleanup calls tidy, when shutdown’s in sight,
Bifrost hops smarter, with code so bright!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4aee9d and f69a51c.

📒 Files selected for processing (4)
  • core/bifrost.go (11 hunks)
  • core/schemas/plugin.go (1 hunks)
  • core/utils.go (1 hunks)
  • docs/plugins.md (5 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch 06-11-chore_plugin_support_extensions
  • Post Copyable Unit Tests in Comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator Author

Pratham-Mishra04 commented Jun 10, 2025

Copy link
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: 2

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

525-551: ⚠️ Potential issue

Post-hook is executed for plugins whose Pre-hook never ran

When a plugin short-circuits (resp != nil) you run PostHook for all
plugins:

for i := len(bifrost.plugins) - 1; i >= 0; i-- { … }

Plugins located after the short-circuiting one never had their PreHook
executed, yet their PostHook is invoked, breaking the documented “reverse
order of executed PreHooks”
contract and risking panics due to missing
state.

Minimal fix – track executed plugins:

-var resp *schemas.BifrostResponse
+var (
+    resp              *schemas.BifrostResponse
+    executedPlugins   []schemas.Plugin
+)

 for _, plugin := range bifrost.plugins {
-    req, resp, err = plugin.PreHook(&ctx, req)
+    req, resp, err = plugin.PreHook(&ctx, req)-    if resp != nil {
-        for i := len(bifrost.plugins) - 1; i >= 0; i-- {
-            resp, err = bifrost.plugins[i].PostHook(&ctx, resp)
+    executedPlugins = append(executedPlugins, plugin)
+    if resp != nil {
+        for i := len(executedPlugins) - 1; i >= 0; i-- {
+            resp, err = executedPlugins[i].PostHook(&ctx, resp)
             …
         }
         return resp, nil
     }
 }

Apply the same fix in tryChatCompletion.

♻️ Duplicate comments (1)
core/bifrost.go (1)

528-528: 🛠️ Refactor suggestion

Pass context.Context, not *context.Context

Continuing the pattern from the interface, plugin.PreHook(&ctx, req) leaks the
non-idiomatic pointer usage into every call-site. Switching the interface to
plain context.Context (see previous comment) removes the need for the &
operator here and simplifies code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc74f7d and 8b88c85.

📒 Files selected for processing (2)
  • core/bifrost.go (4 hunks)
  • core/schemas/plugin.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
core/bifrost.go (1)
core/schemas/bifrost.go (3)
  • BifrostResponse (191-201)
  • BifrostError (319-325)
  • ErrorField (328-335)
core/schemas/plugin.go (1)
core/schemas/bifrost.go (2)
  • BifrostRequest (54-64)
  • BifrostResponse (191-201)

@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-chore_plugin_support_extensions branch from 8b88c85 to 58dfdd3 Compare June 11, 2025 08:36
@Pratham-Mishra04 Pratham-Mishra04 changed the title feat: allow plugins to return responses directly from PreHook feat: enhance plugin system with short-circuit capability and cleanup method Jun 11, 2025
Copy link
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

♻️ Duplicate comments (2)
core/schemas/plugin.go (1)

25-33: 🛠️ Refactor suggestion

Avoid *context.Context – pass context.Context by value

context.Context is already reference-like and designed to be passed by value.
Using a pointer is non-idiomatic, invites nil-dereference foot-guns, and complicates cancellation / deadline propagation.

-PreHook(ctx *context.Context, req *BifrostRequest) (*BifrostRequest, *BifrostResponse, error)
+PreHook(ctx context.Context,  req *BifrostRequest) (*BifrostRequest, *BifrostResponse, error)

-PostHook(ctx *context.Context, result *BifrostResponse) (*BifrostResponse, error)
+PostHook(ctx context.Context,  result *BifrostResponse) (*BifrostResponse, error)

If a plugin truly needs to mutate the context, let it return a new context (or embed values) rather than taking a pointer.

This change ripples to every implementation & call-site (core/bifrost.go, examples in docs, plugins), but keeps the public interface idiomatic and safer.

docs/plugins.md (1)

28-34: 🧹 Nitpick (assertive)

Docs drift: update signatures to match idiomatic interface

Once *context.Context is removed from the Plugin interface, the documentation and all code snippets here must be updated accordingly:

-PreHook(ctx *context.Context, req *BifrostRequest) (*BifrostRequest, *BifrostResponse, error)
+PreHook(ctx context.Context,  req *BifrostRequest) (*BifrostRequest, *BifrostResponse, error)-PostHook(ctx *context.Context, result *BifrostResponse) (*BifrostResponse, error)
+PostHook(ctx context.Context,  result *BifrostResponse) (*BifrostResponse, error)

Keeping docs in lock-step with the exported API prevents consumer confusion.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b88c85 and 58dfdd3.

📒 Files selected for processing (4)
  • core/bifrost.go (11 hunks)
  • core/schemas/plugin.go (1 hunks)
  • core/utils.go (1 hunks)
  • docs/plugins.md (5 hunks)
🧰 Additional context used
🧠 Learnings (1)
core/bifrost.go (1)
Learnt from: Pratham-Mishra04
PR: maximhq/bifrost#65
File: transports/bifrost-http/integrations/utils.go:169-173
Timestamp: 2025-06-09T17:33:52.234Z
Learning: The ChatCompletionRequest method in the Bifrost client follows a contract where the result parameter will never be nil if the error parameter is nil. This means when error checking passes (err == nil), the result is guaranteed to be valid and can be safely used without additional nil checks.
🧬 Code Graph Analysis (2)
core/utils.go (1)
core/schemas/bifrost.go (2)
  • BifrostError (319-325)
  • ErrorField (328-335)
core/schemas/plugin.go (1)
core/schemas/bifrost.go (2)
  • BifrostRequest (54-64)
  • BifrostResponse (191-201)
🔇 Additional comments (1)
core/bifrost.go (1)

520-537:

❌ Incorrect review comment

Propagate the context-pointer fix to hook invocations

After switching the interface to take context.Context by value, adjust the calls:

-req, resp, err = plugin.PreHook(&ctx, req)
+req, resp, err = plugin.PreHook(ctx, req)-resp, err = bifrost.plugins[j].PostHook(&ctx, resp)
+resp, err = bifrost.plugins[j].PostHook(ctx, resp)

(The same substitution is required in tryChatCompletion and the post-provider hook loop.)

Without this, the code will no longer compile once the interface is corrected.


Let’s confirm the current signatures of PreHook/PostHook and where the plugin interface is defined:


🏁 Script executed:

#!/bin/bash
# List all interface blocks (to locate the plugin interface)
rg -n "interface" -n .

# Find all PreHook signatures and references
rg -n -C2 "PreHook(" -n .

# Find all PostHook signatures and references
rg -n -C2 "PostHook(" -n .

Length of output: 26310


Let’s confirm the Plugin interface signatures and how ctx is declared before these calls:


🏁 Script executed:

#!/bin/bash
# Show the Plugin interface definition around PreHook/PostHook
rg -A5 -n "type Plugin interface" core/schemas/plugin.go

# Show PreHook signature in Plugin interface
rg -A3 -n "PreHook" core/schemas/plugin.go

# Show PostHook signature in Plugin interface
rg -A3 -n "PostHook" core/schemas/plugin.go

# Inspect ctx declaration and hook invocations in core/bifrost.go around line 520
sed -n '480,550p' core/bifrost.go

Length of output: 5214


Ignore context-pointer invocation suggestion

The Plugin interface still expects *context.Context (see core/schemas/plugin.go), and all current calls in core/bifrost.go correctly pass &ctx to both PreHook and PostHook. No changes are required until the interface itself is updated.

Likely an incorrect or invalid review comment.

@Pratham-Mishra04 Pratham-Mishra04 marked this pull request as ready for review June 11, 2025 14:06
@Pratham-Mishra04 Pratham-Mishra04 changed the base branch from main to graphite-base/69 June 11, 2025 14:17
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-chore_plugin_support_extensions branch from 58dfdd3 to 9150fa1 Compare June 11, 2025 14:17
@Pratham-Mishra04 Pratham-Mishra04 changed the base branch from graphite-base/69 to 06-11-refactor_changed_content_schema_to_follow_openai June 11, 2025 14:17
Copy link
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 58dfdd3 and 9150fa1.

📒 Files selected for processing (4)
  • core/bifrost.go (11 hunks)
  • core/schemas/plugin.go (1 hunks)
  • core/utils.go (1 hunks)
  • docs/plugins.md (5 hunks)
🧰 Additional context used
🧠 Learnings (1)
core/bifrost.go (1)
Learnt from: Pratham-Mishra04
PR: maximhq/bifrost#65
File: transports/bifrost-http/integrations/utils.go:169-173
Timestamp: 2025-06-09T17:33:52.234Z
Learning: The ChatCompletionRequest method in the Bifrost client follows a contract where the result parameter will never be nil if the error parameter is nil. This means when error checking passes (err == nil), the result is guaranteed to be valid and can be safely used without additional nil checks.
🧬 Code Graph Analysis (2)
core/utils.go (1)
core/schemas/bifrost.go (2)
  • BifrostError (365-371)
  • ErrorField (374-381)
core/schemas/plugin.go (1)
core/schemas/bifrost.go (2)
  • BifrostRequest (59-69)
  • BifrostResponse (237-247)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Graphite / mergeability_check
🔇 Additional comments (10)
core/schemas/plugin.go (3)

19-20: Good documentation addition.

This comment clearly states the error handling behavior for plugins, which is important for developers to understand.


25-27: Well-documented API enhancement.

The PreHook signature change is clearly documented with the short-circuit behavior explained. The implementation aligns with the PR objectives.


34-38: Excellent addition for resource management.

The Cleanup method provides a proper lifecycle hook for plugins to release resources during shutdown. The documentation clearly states the error handling behavior.

core/utils.go (1)

9-30: Clean helper functions for consistent error handling.

These helpers effectively reduce code duplication when creating BifrostError instances. The implementation correctly sets IsBifrostError to false for non-Bifrost errors.

core/bifrost.go (3)

520-538: Correct implementation of short-circuit behavior.

The logic properly tracks which plugins had their PreHook executed and ensures only their PostHooks are called in reverse order when short-circuiting. This maintains the documented symmetry between PreHook and PostHook calls.


750-757: Proper plugin cleanup implementation.

The code correctly iterates through all plugins to call their Cleanup methods and logs any errors as warnings, consistent with the documented plugin error handling behavior.


604-613: Consistent error handling refactoring.

Good use of the newBifrostErrorFromMsg helper for static error messages, maintaining consistency throughout the codebase.

docs/plugins.md (3)

22-23: Important clarification for plugin developers.

This note clearly explains the PostHook execution behavior during short-circuiting, which is crucial for understanding the plugin lifecycle.


27-44: Accurate interface documentation.

The plugin interface documentation correctly reflects the changes to PreHook and the addition of the Cleanup method, matching the actual interface definition.


56-70: Well-updated examples demonstrating the new API.

All example plugins correctly implement the new PreHook signature (returning nil for the response to continue normal processing) and include appropriate Cleanup methods. These examples provide clear guidance for plugin developers.

Also applies to: 86-101, 114-127, 263-277

@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-refactor_changed_content_schema_to_follow_openai branch from ead45eb to fc217ab Compare June 11, 2025 14:28
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-chore_plugin_support_extensions branch from 9150fa1 to bd7a68a Compare June 11, 2025 14:28
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-chore_plugin_support_extensions branch from bd7a68a to a0b4c6d Compare June 11, 2025 14:40
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-refactor_changed_content_schema_to_follow_openai branch from fc217ab to 05c93c4 Compare June 11, 2025 14:40
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-chore_plugin_support_extensions branch from a0b4c6d to a58b1c6 Compare June 11, 2025 14:54
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-refactor_changed_content_schema_to_follow_openai branch 2 times, most recently from 72a4006 to e437920 Compare June 11, 2025 15:13
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-11-chore_plugin_support_extensions branch from a58b1c6 to c4aee9d Compare June 11, 2025 15:13
Copy link
Contributor

akshaydeo commented Jun 11, 2025

Merge activity

  • Jun 11, 4:27 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jun 11, 4:28 PM UTC: Graphite rebased this pull request as part of a merge.
  • Jun 11, 4:30 PM UTC: @akshaydeo merged this pull request with Graphite.

@akshaydeo akshaydeo changed the base branch from 06-11-refactor_changed_content_schema_to_follow_openai to graphite-base/69 June 11, 2025 16:27
@akshaydeo akshaydeo changed the base branch from graphite-base/69 to main June 11, 2025 16:27
@akshaydeo akshaydeo force-pushed the 06-11-chore_plugin_support_extensions branch from c4aee9d to f69a51c Compare June 11, 2025 16:28
@akshaydeo akshaydeo merged commit 8b814ca into main Jun 11, 2025
1 of 2 checks passed
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

✅ BugBot reviewed your changes and found no bugs!


BugBot free trial expires on June 17, 2025
You have used $0.00 of your $50.00 spend limit so far. Manage your spend limit in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

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