Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a MaxVariables limits #6

Merged
merged 5 commits into from
Jul 23, 2024
Merged

Add a MaxVariables limits #6

merged 5 commits into from
Jul 23, 2024

Conversation

bdeneux
Copy link

@bdeneux bdeneux commented Jul 23, 2024

📝 Description

This PR introduces a new global variable to define the maximum number of variables that can be created in the interpreter. This is used to prevent memory overflow or latency issues in predicates that loop on NewVariable() calls.

Due to the current design of NewVariable(), which uses a global variable counter, I also had to use a global variable to handle the maxVariables limit. To avoid changing the signature of NewVariable(), which is used extensively throughout the interpreter, the only feasible way to throw an error when the limit is reached is to trigger a panic. This panic is caught by the interpreter and returns a Prolog error without stopping the interpreter.

By default, no limit is set (0 means no limit).

If you have any idea to do in a better way 😇

Used to fix : axone-protocol/axoned#618

Copy link

coderabbitai bot commented Jul 23, 2024

Warning

Rate limit exceeded

@bdeneux has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 25 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 0358f8f and 5392a0f.

Walkthrough

The changes introduce a more structured approach to variable management within the codebase, shifting from simple integer counters to encapsulated objects that maintain state. This enhances thread safety, improves test reliability by reducing global state usage, and enforces constraints on variable creation. New tests have been added to validate the system's behavior under maximum variable limits, further strengthening robustness and maintainability.

Changes

Files Change Summary
engine/builtin_test.go, engine/text_test.go Updated varCounter initialization from an integer to a struct with a count field, enhancing encapsulation and mitigating global state issues in tests.
engine/variable.go, engine/variable_test.go Replaced atomic counter with a mutex-protected struct for varCounter, introduced maxVariables limit, added error handling, and validated behavior with new tests.
engine/vm.go, engine/vm_test.go Added maxVariables field to the VM struct and a method for setting it, modified reset logic accordingly, and enhanced tests to validate these features.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant VM
    participant VariableManager
    
    User->>VM: SetMaxVariables(10)
    VM->>VariableManager: Update maxVariables
    VariableManager-->>VM: Acknowledge update
    VM->>User: Confirmation of max variable limit set
    
    User->>VM: ResetEnv()
    VM->>VariableManager: Reset with current maxVariables
    VariableManager-->>VM: Environment reset
    VM->>User: Confirmation of environment reset
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @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.

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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

codecov bot commented Jul 23, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Impacted file tree graph

@@           Coverage Diff           @@
##             main       #6   +/-   ##
=======================================
  Coverage   98.33%   98.34%           
=======================================
  Files          23       23           
  Lines        6503     6513   +10     
=======================================
+ Hits         6395     6405   +10     
  Misses         79       79           
  Partials       29       29           
Files Coverage Δ
engine/variable.go 97.14% <100.00%> (+0.26%) ⬆️
engine/vm.go 94.44% <100.00%> (+0.09%) ⬆️

@bdeneux bdeneux marked this pull request as ready for review July 23, 2024 09:18
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ff37990 and e8d9489.

Files selected for processing (6)
  • engine/builtin_test.go (1 hunks)
  • engine/text_test.go (2 hunks)
  • engine/variable.go (1 hunks)
  • engine/variable_test.go (1 hunks)
  • engine/vm.go (3 hunks)
  • engine/vm_test.go (3 hunks)
Additional comments not posted (15)
engine/variable.go (6)

10-10: LGTM!

The introduction of errMaxVariables with a descriptive error message is appropriate.


12-12: LGTM!

The introduction of maxVariables with a default value of 0 (indicating no limit) is sensible and aligns with the existing design.


13-18: LGTM!

The replacement of the atomic counter with a mutex-protected structure for varCounter enhances thread safety and prevents potential race conditions.


21-23: LGTM!

The use of Lock and Unlock in lastVariable ensures thread-safe access to the variable count.


31-37: LGTM!

The addition of the limit check and panic mechanism in NewVariable is a robust way to enforce resource constraints. The use of Lock and Unlock ensures thread-safe access to the variable count.


Line range hint 144-179:
LGTM!

The test function Test_maxVariables covers various scenarios and uses assert.Panics and assert.Equal to accurately validate the expected behavior.

engine/variable_test.go (1)

144-179: LGTM!

The test function Test_maxVariables covers various scenarios and uses assert.Panics and assert.Equal to accurately validate the expected behavior.

engine/vm_test.go (2)

273-280: LGTM!

The test function TestVM_SetMaxVariables verifies the behavior of the SetMaxVariables method and uses assert.Equal to accurately validate the expected behavior.


Line range hint 301-321:
LGTM!

The modifications to TestVM_ResetEnv ensure that the test accurately validates the count of variables and the maxVariables value after the environment reset. The use of assert.Equal ensures that the test accurately validates the expected behavior.

engine/vm.go (3)

73-75: LGTM! The addition of the maxVariables field is straightforward.

The new field aligns with the PR objectives to manage the maximum number of variables in the VM.


282-288: LGTM! Consider adding a check for non-negative values.

The SetMaxVariables method is clear and aligns with the PR objectives. However, it might be beneficial to include a check to ensure that the value is non-negative.

func (vm *VM) SetMaxVariables(n uint64) {
+  if n < 0 {
+    panic("maxVariables cannot be negative")
+  }
  vm.maxVariables = n
  maxVariables = n
}

Line range hint 291-300: LGTM! The modification to ResetEnv is straightforward.

The changes align with the PR objectives to manage the maximum number of variables in the VM.

engine/text_test.go (2)

27-27: LGTM! The modification to varCounter initialization is straightforward.

The change aligns with the PR objectives to enhance encapsulation and clarity.


486-486: LGTM! The modification to varCounter in the test loop is straightforward.

The change aligns with the PR objectives to enhance encapsulation and clarity.

engine/builtin_test.go (1)

955-955: Verify the initialization of varCounter.count.

The change from varCounter = 1 to varCounter.count = 1 suggests that varCounter is now a struct. Ensure that this initialization is correct and aligns with the new struct definition. Verify that all usages of varCounter in the test suite are updated accordingly.

Verification successful

Initialization of varCounter.count is correct and consistent.

The change from varCounter = 1 to varCounter.count = 1 aligns with the struct definition of varCounter. The usage of varCounter.count is consistent across the codebase, confirming the correctness of the initialization.

  • engine/variable.go: Definition and usage of varCounter.count.
  • engine/vm_test.go: Usage of varCounter.count.
  • engine/text_test.go: Usage of varCounter.count.
  • engine/vm.go: Usage of varCounter.count.
  • engine/variable_test.go: Usage of varCounter.count.
  • engine/builtin_test.go: Initialization of varCounter.count.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the initialization and usage of `varCounter` in the test suite.

# Test: Search for the definition and usage of `varCounter`. Expect: Correct struct definition and consistent usage.
rg --type go $'varCounter'

Length of output: 1066

@bdeneux bdeneux requested review from ccamel and amimart July 23, 2024 09:25
@bdeneux bdeneux self-assigned this Jul 23, 2024
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

Outside diff range, codebase verification and nitpick comments (1)
engine/vm_test.go (1)

Line range hint 301-321:
Consider adding comments to explain assertions.

Adding comments to explain the purpose of each assertion can improve readability and maintainability of the test.

vm.SetMaxVariables(20) // Set max variables to 20

varCounter.count = 10 // Simulate existing variable count
varContext = NewVariable() // Create a new variable context
rootContext = NewAtom("non-root") // Set root context to a non-root atom
rootEnv = &Env{
	binding: binding{
		key:   newEnvKey(varContext),
		value: NewAtom("non-root"),
	},
}
maxVariables = 30 // Set max variables to 30

t.Run("Reset environment", func(t *testing.T) {
	vm.ResetEnv()

	assert.Equal(t, uint64(1), varCounter.count) // Verify variable count is reset to 1
	assert.Equal(t, "root", rootContext.String()) // Verify root context is reset
	assert.Equal(t, newEnvKey(varContext), rootEnv.binding.key) // Verify root environment key is reset
	assert.Equal(t, NewAtom("root"), rootEnv.binding.value) // Verify root environment value is reset
	assert.Equal(t, uint64(20), maxVariables) // Verify max variables is reset to 20
})
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e8d9489 and 0358f8f.

Files selected for processing (3)
  • engine/variable_test.go (1 hunks)
  • engine/vm.go (3 hunks)
  • engine/vm_test.go (3 hunks)
Files skipped from review as they are similar to previous changes (2)
  • engine/variable_test.go
  • engine/vm.go

engine/vm_test.go Outdated Show resolved Hide resolved
Copy link
Member

@amimart amimart left a comment

Choose a reason for hiding this comment

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

Looks good thanks :)

@bdeneux bdeneux merged commit b5a8728 into main Jul 23, 2024
2 checks passed
@bdeneux bdeneux deleted the feat/handle-max-variables branch July 23, 2024 12:09
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.

🛡️ High Memory Consumption leading to Network Outage
3 participants