Skip to content

Conversation

@mvlipka
Copy link
Contributor

@mvlipka mvlipka commented Aug 20, 2025

A bug was found when resetting connections due to improperly storing the tokenid and token of the BHE client
This also adds an additional information log when the client resets a connection with the BHE server

Tested locally by setting the maxreqsperconn settings to a low number (50) to replicate the issue and ensured AzureHound could re-connect to the test instance after the connection was reset

Summary by CodeRabbit

  • Bug Fixes
    • Authentication credentials are now correctly applied during client initialization, reducing auth failures.
  • Chores
    • Adds an informational log when a connection is reset after reaching the max requests per connection to improve observability.
  • Tests
    • Adds synchronization to retry tests to reliably verify retry behavior and exact request counts.

@coderabbitai
Copy link

coderabbitai bot commented Aug 20, 2025

Walkthrough

BHE client now stores provided token and tokenId; resetConnection logs at V(1) when per-connection request limit is reached; request-count check extracted to a local variable. Tests add synchronization (WaitGroup) to assert exact retry behavior. No public API signature changes.

Changes

Cohort / File(s) Summary
BHE client init & connection reset
client/bloodhound/client.go
Wire token and tokenId into BHEClient in NewBHEClient; add a V(1) log in resetConnection when max requests-per-connection is reached; refactor request-count check to use a local needsReset variable. No exported signature changes.
BHE client tests (retry synchronization)
client/bloodhound/client_test.go
Add sync import and a WaitGroup to coordinate retries in tests; add defer testServer.Close() in subtests; wait for all retry attempts and assert the exact retry count and error flag. Test-only changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant BHEClient
  note over Caller,BHEClient: Initialization

  Caller->>BHEClient: NewBHEClient(host, token, tokenId, ...)
  activate BHEClient
  BHEClient->>BHEClient: Assign token, tokenId fields
  BHEClient-->>Caller: Return configured client
  deactivate BHEClient
Loading
sequenceDiagram
  autonumber
  participant BHEClient
  participant HTTPClient as HTTP Client/Transport

  note over BHEClient: Connection reset path

  BHEClient->>BHEClient: Compute needsReset = currentRequestCount >= requestLimit
  alt needsReset true
    Note right of BHEClient #D6F5D6: V(1) log emitted ("Max requests per connection limit reached...")
    BHEClient->>HTTPClient: CloseIdleConnections()
    BHEClient->>BHEClient: Replace HTTP client instance
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nibble tokens, tuck them safe inside,
I tap a log when weary links subside.
Hop-reset, hop-new, the transports skip and run,
Retries counted till the echo's done.
A rabbit cheers the tests — small hops, big fun. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 50d2351 and 4dc17b2.

📒 Files selected for processing (1)
  • client/bloodhound/client_test.go (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/bloodhound/client_test.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch BED-5717/Fix-AzureHound-Connection-Reset

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 0

Caution

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

⚠️ Outside diff range comments (1)
client/bloodhound/client.go (1)

419-432: Data race on currentRequestCount; move threshold check under the lock

currentRequestCount is incremented under s.mu but read outside the lock, which is a data race and can trigger multiple concurrent resets. Move the check under the lock and compute a local needReset flag. Call resetConnection() after unlocking to avoid deadlock (it locks internally).

Apply this diff:

 func (s *BHEClient) incrementRequest() error {
-  s.mu.Lock()
-  s.currentRequestCount += 1
-  s.mu.Unlock()
-
-  if s.currentRequestCount >= s.requestLimit {
+  s.mu.Lock()
+  s.currentRequestCount++
+  needReset := s.currentRequestCount >= s.requestLimit
+  s.mu.Unlock()
+
+  if needReset {
     if err := s.resetConnection(); err != nil {
       s.log.Error(err, "error resetting BHE http client connection")
       return err
     }
   }
 
   return nil
 }
🧹 Nitpick comments (2)
client/bloodhound/client.go (2)

406-407: Enhance the new reset log with actionable context (limit value)

Including the limit in the log helps correlate resets with configured thresholds during debugging.

Apply this diff:

- s.log.V(1).Info("Max requests per connection limit reached, resetting connection with BHE server")
+ s.log.V(1).Info(
+   "Max requests per connection limit reached, resetting connection with BHE server",
+   "requestLimit", s.requestLimit,
+)

111-113: Minor log typo: “from from”

Duplicate word in the GOAWAY error logs.

Apply this diff:

- s.log.Error(err, fmt.Sprintf("received GOAWAY from from AWS load balancer while requesting %s; attempt %d/%d; trying again", req.URL, currentAttempt+1, s.maxRetries))
+ s.log.Error(err, fmt.Sprintf("received GOAWAY from AWS load balancer while requesting %s; attempt %d/%d; trying again", req.URL, currentAttempt+1, s.maxRetries))

Repeat the same change for the identical message in Ingest.

Also applies to: 207-209

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3f9b012 and 04b33cb.

📒 Files selected for processing (1)
  • client/bloodhound/client.go (2 hunks)
🔇 Additional comments (1)
client/bloodhound/client.go (1)

82-84: Good fix: persist token and tokenId on the client

Storing token and tokenId in the BHEClient ensures resetConnection() can rebuild a correctly signed transport. This addresses the bug where reconnections lost auth context.

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: 0

🧹 Nitpick comments (6)
client/bloodhound/client_test.go (6)

87-88: Derive the WaitGroup count from maxRetries instead of hardcoding 2.

Future-proof the test so it tracks changes to retry policy without silently under/over-counting.

Apply this diff:

-        wg := sync.WaitGroup{}
-        wg.Add(2)
+        wg := sync.WaitGroup{}
+        // initial attempt + retries
+        wg.Add(maxRetries + 1)

90-94: Guarantee wg.Done is always called in the handler.

Use defer to avoid hangs if the handler ever early-returns or panics in future edits.

-        testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-            requestCount++
-            w.WriteHeader(http.StatusGatewayTimeout)
-            wg.Done()
-        }))
+        testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+            defer wg.Done()
+            requestCount++
+            w.WriteHeader(http.StatusGatewayTimeout)
+        }))

110-110: Avoid indefinite waits by guarding wg.Wait with a timeout.

If the retry loop behavior changes or a Done is missed, this test could hang. Add a timeout wrapper.

Apply this diff and add a time import if you adopt it:

-        wg.Wait()
+        done := make(chan struct{})
+        go func() { defer close(done); wg.Wait() }()
+        select {
+        case <-done:
+        case <-time.After(2 * time.Second):
+            t.Fatal("timed out waiting for retries to complete")
+        }

If you adopt the above, add to the imports:

  • time

66-71: Close the httptest server to prevent resource leaks.

Add a defer to ensure proper cleanup in all paths.

         testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
             w.WriteHeader(http.StatusAccepted)
         }))
+        defer testServer.Close()

90-98: Close the httptest server in the failure/retry case as well.

Same rationale—avoid leaking listeners between subtests.

-        testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+        testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
             defer wg.Done()
             requestCount++
             w.WriteHeader(http.StatusGatewayTimeout)
         }))
+        defer testServer.Close()

43-47: Also close the server in TestBHEClient_SendRequest retry test.

Consistent cleanup across tests keeps CI stable and avoids port exhaustion on flaky runs.

         testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
             requestCount++
             w.WriteHeader(http.StatusInternalServerError)
         }))
+        defer testServer.Close()
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3a511c2 and 50d2351.

📒 Files selected for processing (1)
  • client/bloodhound/client_test.go (3 hunks)
🔇 Additional comments (1)
client/bloodhound/client_test.go (1)

8-8: Importing sync for WaitGroup is appropriate.

This aligns with the added synchronization in the "retry after failures" ingest test.

@mvlipka mvlipka merged commit 3beec51 into main Aug 21, 2025
11 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Aug 21, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants