Skip to content

fix: avoid data race when watching request cancellation#2219

Merged
luispater merged 1 commit intorouter-for-me:devfrom
beck-8:fix/context-done-race
Mar 23, 2026
Merged

fix: avoid data race when watching request cancellation#2219
luispater merged 1 commit intorouter-for-me:devfrom
beck-8:fix/context-done-race

Conversation

@beck-8
Copy link
Copy Markdown
Contributor

@beck-8 beck-8 commented Mar 18, 2026

[2026-03-18 23:43:57] [08a61818] [info ] [gin_logger.go:93] 200 |       11.694s |       127.0.0.1 | POST    "/v1/responses"
[2026-03-18 23:44:02] [2b7669ad] [info ] [gin_logger.go:93] 200 |        4.712s |       127.0.0.1 | POST    "/v1/responses"
panic: interface conversion: interface {} is , not chan struct {}

goroutine 2426 [running]:
context.(*cancelCtx).Done(0x0?)
        /opt/hostedtoolcache/go/1.26.1/x64/src/context/context.go:451 +0x1a5
github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers.(*BaseAPIHandler).GetContextWithCancel.func1()
        /home/runner/work/CLIProxyAPI/CLIProxyAPI/sdk/api/handlers/handlers.go:347 +0x49
created by github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers.(*BaseAPIHandler).GetContextWithCancel in goroutine 2594
        /home/runner/work/CLIProxyAPI/CLIProxyAPI/sdk/api/handlers/handlers.go:343 +0x290

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a critical data race within the context cancellation mechanism, which previously caused a panic during concurrent request processing. The fix ensures that the context used for cancellation monitoring is correctly captured, thereby preventing unexpected runtime errors and improving the stability of API request handling.

Highlights

  • Data Race Fix: Addressed a data race condition that could lead to a panic during request cancellation by capturing the context.Context in a local variable before launching a goroutine.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request fixes a data race that occurs when watching for request cancellation. The race happens because the newCtx variable was being modified after being captured by a goroutine. The fix introduces a new variable cancelCtx to be used by the goroutine, which resolves the issue. I've added a suggestion to use a more idiomatic Go pattern for passing variables to goroutines, which can further improve code clarity and safety.

Comment on lines +342 to 351
cancelCtx := newCtx
if requestCtx != nil && requestCtx != parentCtx {
go func() {
select {
case <-requestCtx.Done():
cancel()
case <-newCtx.Done():
case <-cancelCtx.Done():
}
}()
}
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.

medium

While this change correctly fixes the data race, a more idiomatic Go approach is to pass newCtx as an argument to the goroutine. This makes the variable capture explicit and is a safer pattern for concurrent code, as it avoids potential confusion with closure variable capturing.

	if requestCtx != nil && requestCtx != parentCtx {
		go func(ctxToWatch context.Context) {
			select {
			case <-requestCtx.Done():
				cancel()
			case <-ctxToWatch.Done():
			}
		}(newCtx)
	}
References
  1. To prevent data races when using variables inside a goroutine, it's a best practice to pass them as arguments to the goroutine's function. This creates a copy of the variable for the goroutine, ensuring it doesn't get affected by modifications in the parent goroutine.

Copy link
Copy Markdown
Collaborator

@luispater luispater left a comment

Choose a reason for hiding this comment

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

Summary:
This PR fixes a real concurrency bug in GetContextWithCancel by avoiding closure capture of a context interface variable that is later reassigned. The change is minimal, scoped, and matches the reported panic stack.

Key findings:

  • Blocking: none.
  • Non-blocking: add a focused regression test to lock in the race fix over time.

Why this looks correct:

  • Before: the goroutine selected on newCtx.Done() while newCtx was subsequently reassigned via context.WithValue(...), which can race on the captured interface variable.
  • After: the goroutine selects on cancelCtx.Done() where cancelCtx is a stable snapshot of the cancelable context returned by context.WithCancel, removing the variable-capture race hazard.

Test plan:

  • CI build check is passing.
  • I did not run local tests in this review pass.
  • Suggested follow-up: add a targeted stress/race test around this function (go test -race).

Overall:
The fix is appropriate and low risk. I recommend approve.

This is an automated Codex review result and still requires manual verification by a human reviewer.

@luispater luispater changed the base branch from main to dev March 23, 2026 14:57
@luispater luispater merged commit 7b04530 into router-for-me:dev Mar 23, 2026
2 checks passed
Adamcf123 pushed a commit to Adamcf123/CLIProxyAPI that referenced this pull request Mar 24, 2026
fix: avoid data race when watching request cancellation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants