Skip to content

[management] Fix data race on ctx in HTTP metrics middleware - #8627

Merged
mlsmaycon merged 1 commit into
mainfrom
work/affectionate-pasteur-mqmnyj
Nov 14, 2026
Merged

mlsmaycon merged 1 commit into
mainfrom
work/affectionate-pasteur-mqmnyj

Conversation

@mlsmaycon

@mlsmaycon mlsmaycon commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes

The HTTP metrics middleware registers a context.AfterFunc whose callback reads the local ctx (for context.Cause), while the handler reassigns ctx = req.Context() after ServeHTTP. If the request context is cancelled as the handler finishes, the callback goroutine reads ctx concurrently with that write.

go test -race -tags devcert -count=8 -run TestBrokerLimitsCallbacksPerClient ./management/internals/modules/mcpapi/ reports WARNING: DATA RACE at http_api_metrics.go:207 (write) vs :198 (read) on main.

The callback now captures the request context in its own variable, the post-ServeHTTP context uses a separate respCtx, and the AfterFunc stop function is called once the handler returns. Logging and metrics behaviour is unchanged.

Verified: the reproduction above at -count=50 shows no race, and go test -race -tags devcert ./management/server/telemetry/... ./management/internals/modules/mcpapi/... passes.

Issue ticket number and link

None, trivial race fix.

Stack

Checklist

  • Is it a bug fix
  • Is a typo/documentation fix
  • Is a feature enhancement
  • It is a refactor
  • Created tests that fail without the change (if possible)
  • I ran and tested this change locally — I did not rely on CI to find out whether it works
  • This PR has a single purpose (not a fix + refactor + feature in one)
  • This change is a trivial fix, OR it links an issue the NetBird team agreed on beforehand. Changes to the public API, gRPC protocols, functionality behavior, CLI / service flags, or new features always need that agreement first. See CONTRIBUTING.md.

By submitting this pull request, you confirm that you have read and agree to the terms of the Contributor License Agreement.

Documentation

Select exactly one:

  • I added/updated documentation for this change
  • Documentation is not needed for this change (explain why)

Internal race fix with no user-facing change.

Docs PR URL (required if "docs added" is checked)

Paste the PR link from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__


Generated by Claude Code

View guided diff Turn on auto-fix

Summary by CodeRabbit

  • Bug Fixes
    • Improved the accuracy of HTTP request telemetry when request context changes during handling. Cancellation details and response timing are now recorded using the appropriate context.

The context.AfterFunc callback read the local ctx while the handler
reassigned it after ServeHTTP, so a request context cancelled as the
handler finished raced with that write.

Capture the request context in its own variable for the callback, use a
separate variable for the post-ServeHTTP context, and stop the AfterFunc
once the handler returns.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The HTTP middleware retains the original request context for cancellation monitoring. It uses the request’s current context for response and duration logs.

Changes: HTTP telemetry context handling

Layer / File(s) Summary
Request and response context logging
management/server/telemetry/http_api_metrics.go
The cancellation callback observes the retained request context and stops after the handler returns. Response and duration logs use the request’s current context.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: pascal-fischer, bcmmbaga

Merge Risk: Minimal · up to 6461d

This change fixes a data race in the HTTP metrics middleware, and logging and metrics behavior is unchanged. No remaining merge-blocking risk was found.

Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
No Attribution Trailers Inconclusive Pull request inputs changed after this check was assessed; its verdict is no longer current. Re-run the check against the current pull request inputs.
Passed Passed checks: 4 passed

Check name Status Explanation
Title check Passed The title names the main change: a fix for a data race on ctx in the HTTP metrics middleware. The raw summary confirms the middleware now keeps the request context for the cancellation callback and us…
Description check Passed The description follows the template. It has a clear change description with the race cause, the fix, and verification commands. The checklist is filled in with the bug fix, local testing, single-purp…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: a fix for a data race on ctx in the HTTP metrics middleware. The raw summary confirms the middleware now keeps the request context for the cancellation callback and uses a separate context after ServeHTTP. The title is specific and accurate, and it does not need to list every detail.

Full details: Description check

Explanation

The description follows the template. It has a clear change description with the race cause, the fix, and verification commands. The checklist is filled in with the bug fix, local testing, single-purpose, and trivial-fix boxes checked. The documentation section selects 'not needed' and gives a reason. Two gaps remain: the 'Issue ticket number and link' section says 'None, trivial race fix' rather than linking an agreed issue, and the Docs PR URL line still contains the unfilled placeholder '__'. The 'Created tests that fail without the change' box is unchecked and no test is added for the race. Because the bug fix is labelled trivial, the missing issue link is acceptable under the template, but the author should confirm that. The placeholder line should be removed or completed.

Resolution

Remove or fill in the placeholder docs URL line (https://github.com/netbirdio/docs/pull/__). Confirm that the 'trivial fix' label is accepted for the missing issue link, or link an agreed issue. Optionally add a regression test or state why one is not possible.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between c4a6e4c and 6461d2e.

Files selected for processing: 1

  • management/server/telemetry/http_api_metrics.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@sonarqubecloud

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

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.

No issues found across 1 file

View guided diff | Turn on auto-fix | Re-trigger cubic

@mlsmaycon
mlsmaycon merged commit 1bb2fd3 into main Nov 14, 2026
58 checks passed
@mlsmaycon
mlsmaycon deleted the work/affectionate-pasteur-mqmnyj branch November 14, 2026 17:13
@github-actions

Copy link
Copy Markdown

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