Skip to content

test: improve memory management in engine check functions#2323

Merged
tolgaozen merged 1 commit intomasterfrom
feat/check-goroutine-leak-test
Jul 17, 2025
Merged

test: improve memory management in engine check functions#2323
tolgaozen merged 1 commit intomasterfrom
feat/check-goroutine-leak-test

Conversation

@tolgaozen
Copy link
Copy Markdown
Member

@tolgaozen tolgaozen commented Jul 17, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of errors during permission checks to prevent unwanted error propagation.
    • Enhanced concurrency management to reduce the risk of goroutine leaks.
  • Tests

    • Added comprehensive tests to verify the absence of goroutine leaks, correct handling of context cancellation, and robust high-concurrency behavior in the permission checking engine.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 17, 2025

Walkthrough

The changes optimize internal slice allocations and update error handling in the permission check engine. They also introduce a comprehensive test suite to detect goroutine leaks, verify context cancellation handling, and ensure proper concurrency management during permission checks, using behavior-driven tests with Ginkgo and Gomega.

Changes

File(s) Change Summary
internal/engines/check.go Optimized slice preallocation, updated error handling in CEL evaluation, changed map type, and refactored concurrency loop style. No public API changes.
internal/engines/check_goroutine_leak_test.go Added new test suite for goroutine leak detection, context cancellation, and high concurrency handling using Ginkgo and Gomega.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite
    participant DB as InMemoryDB
    participant Engine as PermissionCheckEngine
    participant Invoker as DirectInvoker
    participant GoRuntime

    TestSuite->>DB: Setup schema and test data
    TestSuite->>GoRuntime: Record initial goroutine count
    loop Concurrent Checks
        TestSuite->>Invoker: Invoke permission check (concurrent)
        Invoker->>Engine: Check permission
        Engine-->>Invoker: Permission result
        Invoker-->>TestSuite: Result
    end
    TestSuite->>GoRuntime: Wait for goroutine cleanup
    TestSuite->>GoRuntime: Record final goroutine count
    TestSuite->>TestSuite: Assert no significant goroutine leaks
Loading

Poem

In the engine’s warren, slices now pre-grow,
While errors are tamed, denied with a gentle “no.”
New tests hop in, counting goroutines with care,
Ensuring no leaks linger, just clean, crisp air.
With concurrency checked and context in hand,
The rabbits rejoice—robustness is grand! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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

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
Copy Markdown

@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

🔭 Outside diff range comments (1)
internal/engines/check.go (1)

613-629: Critical: CEL evaluation errors should not be silently converted to denials.

The change at line 629 suppresses the error from CEL evaluation and returns a denial instead. This is problematic because:

  1. It hides actual evaluation errors (syntax errors, type mismatches, runtime errors)
  2. It makes debugging difficult as administrators won't know why the evaluation failed
  3. It conflates "permission denied" with "evaluation error"

The error handling at line 615 was more appropriate as it provided context about the failure.

Consider reverting this change to maintain proper error propagation:

-		return denied(emptyResponseMetadata()), nil
+		return denied(emptyResponseMetadata()), err
🧹 Nitpick comments (3)
internal/engines/check.go (2)

289-289: Consider documenting the rationale for the fixed capacity of 4.

While preallocating capacity is a good optimization, the magic number 4 seems arbitrary. Consider either:

  1. Adding a comment explaining why 4 was chosen (e.g., based on profiling data)
  2. Using a named constant for better maintainability
  3. Making it configurable if this is a tuning parameter
-		checkFunctions := make([]CheckFunction, 0, 4)
+		// Preallocate with capacity 4 based on typical relationship count
+		const initialCheckFunctionsCap = 4
+		checkFunctions := make([]CheckFunction, 0, initialCheckFunctionsCap)

369-369: Apply the same capacity constant here for consistency.

This uses the same magic number 4 as in checkDirectRelation. If you implement a named constant as suggested above, apply it here as well for consistency.

internal/engines/check_goroutine_leak_test.go (1)

258-385: Consider strengthening the test assertions.

While the test validates concurrency limits and goroutine management well, the assertions could be more comprehensive:

  1. The test collects errorCount but doesn't validate it
  2. Only checking that successCount > 0 is weak - all requests should complete
 			Expect(successCount).Should(BeNumerically(">", 0))
+			// Ensure all requests completed (either success or error)
+			Expect(successCount + errorCount).Should(Equal(numRequests))
+			// If there are errors, they should be context-related (timeout/cancellation)
+			if errorCount > 0 {
+				GinkgoWriter.Printf("Completed with %d successes and %d errors\n", successCount, errorCount)
+			}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f06f31 and 69bac60.

📒 Files selected for processing (2)
  • internal/engines/check.go (8 hunks)
  • internal/engines/check_goroutine_leak_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Test with Coverage
  • GitHub Check: Analyze (go)
  • GitHub Check: Test with Coverage
🔇 Additional comments (5)
internal/engines/check.go (3)

226-226: Good performance optimization!

Preallocating the slice capacity to match len(children) avoids unnecessary reallocations during the append operations in the loop below.


544-545: Good modernization to Go 1.18+ conventions.

Using any instead of interface{} improves readability while maintaining the same functionality.


663-663: Go 1.22+ Syntax Supported
The project’s go.mod specifies Go 1.24, so the for range len(functions) syntax is fully supported. No changes needed.

internal/engines/check_goroutine_leak_test.go (2)

24-167: Well-structured goroutine leak test with appropriate stabilization.

The test effectively validates that concurrent permission checks don't leak goroutines. The use of runtime.GC() and sleep intervals helps ensure accurate goroutine counts.

Consider making the tolerance configurable or environment-aware, as different test environments might have varying baseline goroutine counts.


169-256: Good test coverage for context cancellation.

The test correctly validates that the engine respects context cancellation and returns an error when the context is cancelled.

@tolgaozen tolgaozen merged commit 3a5c2b3 into master Jul 17, 2025
13 checks passed
@tolgaozen tolgaozen deleted the feat/check-goroutine-leak-test branch July 17, 2025 14:08
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.

1 participant