Skip to content

Conversation

@mostlygeek
Copy link
Owner

@mostlygeek mostlygeek commented May 13, 2025

Sometimes upstreams can accept HTTP but never respond causing requests to build up waiting for a response. This can block Process.Stop() as that waits for inflight requests to finish. This change refactors the code to not wait when attempting to shutdown the process.

Summary by CodeRabbit

  • New Features
    • Introduced configurable process stopping strategies, allowing processes to either stop immediately or wait for ongoing requests to complete before stopping.
  • Bug Fixes
    • Improved process shutdown behavior to ensure active requests are handled appropriately during configuration reloads and shutdowns.
  • Tests
    • Added and updated tests to verify both immediate and graceful process stopping behaviors.
  • Documentation
    • Clarified process state transitions and shutdown behavior in comments.

Sometimes upstreams can accept HTTP but never respond causing requests
to build up waiting for a response. This can block Process.Stop() as
that waits for inflight requests to finish. This change refactors the
code to not wait when attempting to shutdown the process.
@mostlygeek mostlygeek self-assigned this May 13, 2025
@mostlygeek mostlygeek added the enhancement New feature or request label May 13, 2025
@coderabbitai
Copy link

coderabbitai bot commented May 13, 2025

Walkthrough

The changes introduce a StopStrategy type to control how processes are stopped, allowing either immediate termination or waiting for in-flight requests to finish. Method signatures for stopping processes are updated across multiple components to accept this strategy. Tests are updated to use the new strategy, and new logic is added to handle immediate stopping and waiting behaviors.

Changes

File(s) Change Summary
llama-swap.go Modified the configuration reload to call StopProcesses with StopWaitForInflightRequest, ensuring in-flight requests complete before stopping processes.
proxy/process.go Introduced StopStrategy type and constants. Split stopping logic into Stop() (waits for inflight requests) and StopImmediately(). Updated comments and state transitions.
proxy/process_test.go Added TestProcess_StopImmediately to verify immediate process stopping interrupts ongoing requests and updates state.
proxy/processgroup.go Updated StopProcesses to accept a StopStrategy parameter and merged helper logic. Calls either Stop() or StopImmediately() on each process based on strategy.
proxy/processgroup_test.go Updated tests to call StopProcesses(StopWaitForInflightRequest), ensuring shutdown waits for inflight requests.
proxy/proxymanager.go Updated StopProcesses to accept a StopStrategy and propagate it to ProcessGroup. Updated all internal calls to use the new argument.
proxy/proxymanager_test.go Modified all test calls to StopProcesses to use StopWaitForInflightRequest for consistent shutdown behavior in tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ProxyManager
    participant ProcessGroup
    participant Process

    Client->>ProxyManager: Request to reload config / unload models
    ProxyManager->>ProcessGroup: StopProcesses(strategy)
    alt StopWaitForInflightRequest
        ProcessGroup->>Process: Stop()
        Process->>Process: Wait for inflight requests
        Process->>Process: StopImmediately()
    else StopImmediately
        ProcessGroup->>Process: StopImmediately()
    end
    Process->>ProcessGroup: Stopped
    ProcessGroup->>ProxyManager: All stopped
    ProxyManager->>Client: Reload/unload complete
Loading

Possibly related PRs

  • mostlygeek/llama-swap#106: Modifies llama-swap.go to improve configuration reload behavior and graceful process stopping, directly related to the enhancements in stop process calls and hot-reload logic introduced in this PR.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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.

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

@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

🧹 Nitpick comments (2)
proxy/process.go (2)

33-38: New stop strategy enumeration.

A new StopStrategy type is introduced with two constants to represent different stopping behaviors:

  • StopImmediately: Stop the process immediately without waiting for in-flight requests
  • StopWaitForInflightRequest: Wait for in-flight requests to complete before stopping

Consider adding more detailed documentation for the StopStrategy type to explain the semantics of each strategy:

// StopStrategy defines the strategy to stop processes.
+// It controls whether a process should be stopped immediately or wait for in-flight
+// requests to complete first.
type StopStrategy int

const (
+    // StopImmediately terminates the process without waiting for in-flight requests
    StopImmediately StopStrategy = iota
+    // StopWaitForInflightRequest waits for all in-flight requests to complete before terminating
    StopWaitForInflightRequest
)

335-356: New StopImmediately() method for immediate process termination.

This new method implements the actual process stopping logic without waiting for in-flight requests, allowing the /unload endpoint to stop processes without being blocked by hanging requests.

The logging is slightly inconsistent. The debug message uses "Stopping process" while the info message refers to "Stop()". Consider updating the info messages to be clearer about which method is being called:

-       p.proxyLogger.Infof("<%s> Stop() Ready -> StateStopping err: %v, current state: %v", p.ID, err, curState)
+       p.proxyLogger.Infof("<%s> StopImmediately() Ready -> StateStopping err: %v, current state: %v", p.ID, err, curState)

Similarly for the second info message:

-       p.proxyLogger.Infof("<%s> Stop() StateStopping -> StateStopped err: %v, current state: %v", p.ID, err, curState)
+       p.proxyLogger.Infof("<%s> StopImmediately() StateStopping -> StateStopped err: %v, current state: %v", p.ID, err, curState)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9dc4bcb and 237b07f.

📒 Files selected for processing (7)
  • llama-swap.go (1 hunks)
  • proxy/process.go (3 hunks)
  • proxy/process_test.go (1 hunks)
  • proxy/processgroup.go (2 hunks)
  • proxy/processgroup_test.go (2 hunks)
  • proxy/proxymanager.go (4 hunks)
  • proxy/proxymanager_test.go (10 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
llama-swap.go (1)
proxy/process.go (1)
  • StopWaitForInflightRequest (37-37)
proxy/process_test.go (1)
proxy/process.go (4)
  • NewProcess (72-96)
  • StateReady (23-23)
  • StopImmediately (36-36)
  • StateStopped (21-21)
proxy/processgroup.go (1)
proxy/process.go (2)
  • StopStrategy (33-33)
  • StopImmediately (36-36)
proxy/proxymanager.go (1)
proxy/process.go (3)
  • StopStrategy (33-33)
  • StopWaitForInflightRequest (37-37)
  • StopImmediately (36-36)
🔇 Additional comments (13)
proxy/processgroup_test.go (2)

49-49: Updated to use explicit stop strategy parameter.

The code has been correctly modified to pass StopWaitForInflightRequest to the updated StopProcesses method, ensuring that test teardown maintains the expected behavior of waiting for in-flight requests to complete.


77-77: Updated to use explicit stop strategy parameter.

This change correctly passes StopWaitForInflightRequest to the StopProcesses method in the second test, maintaining consistent test teardown behavior.

llama-swap.go (1)

87-87: Updated configuration reload to wait for in-flight requests.

The code has been correctly modified to explicitly pass proxy.StopWaitForInflightRequest when stopping processes during configuration reload. This ensures that the server waits for any in-progress requests to complete before updating the configuration, maintaining a smooth user experience during reloads.

proxy/process_test.go (1)

376-395: Added test for immediate process termination.

The new test correctly validates that StopImmediately() can terminate a process with in-flight requests without waiting for them to complete. The test correctly:

  1. Starts a process and verifies it reaches StateReady
  2. Launches a slow request in a separate goroutine
  3. Calls StopImmediately() and verifies the process transitions to StateStopped immediately

This test is crucial for validating the core functionality of this PR, which is to allow immediate termination without waiting for in-flight requests.

proxy/processgroup.go (2)

79-79: Updated method signature to support different stop strategies.

The StopProcesses method signature has been correctly modified to accept a StopStrategy parameter, allowing callers to control whether processes should be stopped immediately or should wait for in-flight requests to complete.


93-98: Added strategy-based process stopping logic.

The implementation correctly handles different stop strategies:

  • StopImmediately: Calls process.StopImmediately() to terminate the process without waiting
  • Default (including StopWaitForInflightRequest): Calls process.Stop() to gracefully wait for requests

This implementation maintains backward compatibility by defaulting to the waiting behavior while adding support for immediate termination when needed.

proxy/proxymanager_test.go (2)

30-30: Parameter added to match new signature.

The StopWaitForInflightRequest parameter is now required when calling StopProcesses() and will ensure the test cleanup waits for in-flight requests to complete before stopping processes.


66-66: Test cleanup now uses explicit stop strategy.

The test cleanup consistently uses the StopWaitForInflightRequest strategy across all test functions, which is appropriate for tests as we want to ensure all test-initiated requests complete before stopping the processes.

Also applies to: 108-108, 144-144, 355-355, 410-410, 464-464, 560-560, 589-589, 607-607

proxy/proxymanager.go (3)

221-221: Strategy propagated to process groups.

The stop strategy is now properly propagated to each process group, ensuring consistent stopping behavior.


507-507: /unload endpoint now stops processes immediately.

This is the key change in the PR - the /unload endpoint now uses StopImmediately so it will no longer block waiting for in-flight requests that might be hanging, addressing the issue with unresponsive upstream servers.


263-263:

❓ Verification inconclusive

Exclusive mode uses wait strategy when stopping other groups.

When a process group is running in exclusive mode, other process groups are stopped using the StopWaitForInflightRequest strategy. This ensures that in-flight requests to other groups complete before stopping them.

Is this behavior intentional? It means that even if the caller wants to stop everything immediately, groups stopped due to exclusivity will still wait for in-flight requests. Run this script to check if there are any other places in the codebase where process groups are stopped:


🏁 Script executed:

#!/bin/bash
# Find all calls to StopProcesses to verify the strategy usage
rg -A 2 -B 2 'StopProcesses' --glob '*.go'

Length of output: 5596


Confirm hardcoded wait strategy on non-target process groups

In ProxyManager.StopProcesses (proxy/proxymanager.go:263), any “other” group is always stopped with StopWaitForInflightRequest, regardless of the strategy passed in. Concretely:

  • In unloadAllModelsHandler (proxy/proxymanager.go), we call pm.StopProcesses(StopImmediately), but all other groups still use StopWaitForInflightRequest.
  • In llama-swap.go, upgrades also unconditionally use StopWaitForInflightRequest.
  • No existing test covers the StopImmediately path for non-target groups.

Is it intentional to always drain in-flight requests on secondary groups? If you want to respect the caller’s strategy, update the code to:

-   otherGroup.StopProcesses(StopWaitForInflightRequest)
+   otherGroup.StopProcesses(strategy)
proxy/process.go (2)

323-333: Stop() now waits for in-flight requests before stopping.

The Stop() method has been refactored to explicitly wait for in-flight requests to complete before delegating to StopImmediately(). This improves separation of concerns and makes the code more maintainable.


360-361: Enhanced docstring clarification.

The docstring now clearly states that once a process reaches the StateShutdown state, it cannot be restarted, which is an important detail for maintainers to understand.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants