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

Fix: deterministically fetch perp info from state #2341

Merged
merged 4 commits into from
Sep 25, 2024

Conversation

ttl33
Copy link
Contributor

@ttl33 ttl33 commented Sep 25, 2024

Changelist

Problem: The ordering a map iteration in go is not deterministic. If the iteration loop completes, the final result is the same. However, if the loop exits in the middle (ie goes over the gas limit -> abort), then the different sets of perp ids have been iterated on; therefore creates a non-deterministic behavior in terms of gas usage.

Fix: deterministically order the perp ids to iterate over by sorting first.

Test Plan

Unit test

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features

    • Introduced a new perpetual position for SOL, enhancing the available options for users.
  • Bug Fixes

    • Improved clarity in the naming of variables related to subaccount and perpetual IDs, ensuring better understanding and maintenance.
  • Tests

    • Added a new test to validate consistent gas usage for the GetAllRelevantPerpetuals method, ensuring reliability under varying conditions.

@ttl33 ttl33 requested a review from a team as a code owner September 25, 2024 15:10
Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Warning

Rate limit exceeded

@ttl33 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 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 5cac752 and 51b0cf5.

Walkthrough

The pull request introduces a new perpetual position variable for SOL in the positions.go file, modifies variable names in the subaccount.go file for clarity, and adds a deterministic gas usage test in subaccount_test.go. These changes enhance code clarity and ensure consistent behavior in gas consumption during method execution.

Changes

File Path Change Summary
protocol/testutil/constants/positions.go Added a new variable PerpetualPosition_OneSolLong, initialized with specific parameters for a perpetual position representing 1 SOL.
protocol/x/subaccounts/keeper/subaccount.go Renamed subaccountIds to subaccountIdsMap and perpIds to perpIdsMap for clarity. Introduced sorting for perpetual IDs to ensure determinism, creating a new variable perpIdsOrdered for sorted keys. Adjusted loop to iterate over perpIdsOrdered.
protocol/x/subaccounts/keeper/subaccount_test.go Added a new test function TestGetAllRelevantPerpetuals_Deterministic to validate gas usage consistency across multiple executions of the GetAllRelevantPerpetuals method, ensuring it raises an error when gas limits are exceeded.

Possibly related PRs

Suggested labels

refactor

Suggested reviewers

  • roy-dydx
  • jayy04

Poem

🐰 In the fields where code does play,
A new position hops today.
With names made clear and tests so bright,
Gas flows steady, a joyful sight!
Perpetuals dance, in order they stand,
A leap for clarity, oh so grand! 🌟


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>, please review it.
    • 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 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 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 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 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.

Comment on lines 6037 to 6041
// expectations
expectedNetCollateral *big.Int
expectedInitialMargin *big.Int
expectedMaintenanceMargin *big.Int
expectedErr error
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Not needed.

Comment on lines 773 to 774
subaccountIdsMap := make(map[types.SubaccountId]struct{})
perpIdsMap := make(map[uint32]struct{})
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Could be named as sets and not maps.

}
}

// Important: Sort the perpIds to ensure determinism!
perpIdsOrdered := lib.GetSortedKeys[lib.Sortable[uint32]](perpIdsMap)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit/non-blocking: sortedPerpIds to match convention elsewhere in code?

// SOL positions
PerpetualPosition_OneSolLong = *testutil.CreateSinglePerpetualPosition(
2,
big.NewInt(10_000_000_000), // 0.1 SOL
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Change to = 1 SOL to match name of the constant.

Copy link
Contributor

@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 and nitpick comments (2)
protocol/testutil/constants/positions.go (1)

102-108: LGTM! Consider adding a comment for clarity.

The addition of PerpetualPosition_OneSolLong is appropriate and consistent with other perpetual position constants in the file. It expands the test coverage to include SOL positions, which is valuable.

Consider adding a comment to clarify the meaning of the identifier 2:

 PerpetualPosition_OneSolLong = *testutil.CreateSinglePerpetualPosition(
-		2,
+		2, // SOL perpetual identifier
 		big.NewInt(10_000_000_000), // 0.1 SOL
 		big.NewInt(0),
 		big.NewInt(0),
 	)

This will help maintain clarity as more perpetuals are added in the future.

protocol/x/subaccounts/keeper/subaccount.go (1)

773-774: LGTM! Improved determinism and code clarity.

The changes to the GetAllRelevantPerpetuals function effectively address the issue of non-deterministic behavior caused by map iteration. Sorting the perpetual IDs ensures a consistent order of processing, which is crucial for blockchain applications. The renaming of maps (subaccountIdsMap and perpIdsMap) improves code clarity.

Consider using a more memory-efficient data structure for subaccountIdsMap since you're only checking for existence. You could use map[types.SubaccountId]struct{} instead of map[types.SubaccountId]bool. This doesn't allocate any memory for the value:

-subaccountIdsMap := make(map[types.SubaccountId]bool)
+subaccountIdsMap := make(map[types.SubaccountId]struct{})

And when setting a value:

-subaccountIdsMap[update.SubaccountId] = true
+subaccountIdsMap[update.SubaccountId] = struct{}{}

Also applies to: 779-779, 782-782, 784-784, 789-789, 793-795, 798-799

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f346663 and 3c44650.

📒 Files selected for processing (3)
  • protocol/testutil/constants/positions.go (1 hunks)
  • protocol/x/subaccounts/keeper/subaccount.go (1 hunks)
  • protocol/x/subaccounts/keeper/subaccount_test.go (2 hunks)
🔇 Additional comments not posted (2)
protocol/testutil/constants/positions.go (1)

102-108: Clarify the relationship between this change and the PR objectives.

The PR objectives mention addressing non-deterministic behavior in map iteration for perpetual IDs. While the addition of a new SOL position constant is valuable for testing, it's not immediately clear how this change relates to the stated objectives.

Could you please clarify:

  1. How does this new constant contribute to addressing the non-deterministic behavior issue?
  2. Are there additional changes in other files that use this constant to implement or test the solution?

To help verify the usage of this new constant, you can run the following script:

This will help us understand how the new constant is being used in the context of the PR objectives.

protocol/x/subaccounts/keeper/subaccount_test.go (1)

6110-6110: ⚠️ Potential issue

Syntax Error: Invalid 'for range' loop syntax

The loop at line 6110 uses for range 100, which is invalid Go syntax. To iterate 100 times, you should use:

-		for range 100 { // run 100 times since it's highly unlikely gas usage is deterministic over 100 times if there's non-determinism.
+		for i := 0; i < 100; i++ { // run 100 times to check for gas usage determinism.

Likely invalid or redundant comment.

Comment on lines 102 to 108
// SOL positions
PerpetualPosition_OneSolLong = *testutil.CreateSinglePerpetualPosition(
2,
big.NewInt(10_000_000_000), // 0.1 SOL
big.NewInt(0),
big.NewInt(0),
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding more SOL position constants for comprehensive testing.

While the addition of PerpetualPosition_OneSolLong is valuable, consider expanding the SOL-related test constants to match the coverage provided for other cryptocurrencies like BTC and ETH. This could include:

  1. A short SOL position
  2. Different sizes of SOL positions (e.g., 1 SOL, 0.01 SOL)
  3. Positions with non-zero funding values

Here's an example of additional constants you might want to add:

PerpetualPosition_OneSolShort = *testutil.CreateSinglePerpetualPosition(
    2,
    big.NewInt(-10_000_000_000), // -0.1 SOL
    big.NewInt(0),
    big.NewInt(0),
)

PerpetualPosition_OneSolLong = *testutil.CreateSinglePerpetualPosition(
    2,
    big.NewInt(100_000_000_000), // 1 SOL
    big.NewInt(0),
    big.NewInt(0),
)

PerpetualPosition_OneSolLong_PositiveFunding = *testutil.CreateSinglePerpetualPosition(
    2,
    big.NewInt(10_000_000_000), // 0.1 SOL
    big.NewInt(1000000), // Some positive funding
    big.NewInt(0),
)

These additional constants would provide a more comprehensive set of test scenarios for SOL-related functionality.

@ttl33 ttl33 merged commit cc1b795 into main Sep 25, 2024
21 of 22 checks passed
@ttl33 ttl33 deleted the tl/read-perp-deterministic branch September 25, 2024 16:46
@adamfraser
Copy link
Contributor

@Mergifyio backport release/indexer/v7.x

Copy link
Contributor

mergify bot commented Sep 25, 2024

backport release/indexer/v7.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Sep 25, 2024
@jonfung-dydx
Copy link
Contributor

@Mergifyio backport release/protocol/v6.x

Copy link
Contributor

mergify bot commented Sep 25, 2024

backport release/protocol/v6.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Sep 25, 2024
@adamfraser
Copy link
Contributor

@mergify backport release/protocol/v7.x

Copy link
Contributor

mergify bot commented Sep 25, 2024

backport release/protocol/v7.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Sep 25, 2024
@ttl33
Copy link
Contributor Author

ttl33 commented Sep 25, 2024

@mergify backport release/protocol/v5.2.x

jonfung-dydx added a commit that referenced this pull request Sep 25, 2024
…2345)

Co-authored-by: ttl33 <19664986+ttl33@users.noreply.github.com>
Co-authored-by: Jonathan Fung <jonathan@dydx.exchange>
Copy link
Contributor

mergify bot commented Sep 25, 2024

backport release/protocol/v5.2.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Sep 25, 2024
(cherry picked from commit cc1b795)

# Conflicts:
#	protocol/testutil/constants/positions.go
#	protocol/x/subaccounts/keeper/subaccount.go
#	protocol/x/subaccounts/keeper/subaccount_test.go
adamfraser pushed a commit that referenced this pull request Sep 25, 2024
…2346)

Co-authored-by: ttl33 <19664986+ttl33@users.noreply.github.com>
ttl33 added a commit that referenced this pull request Sep 25, 2024
…2354)

Co-authored-by: ttl33 <19664986+ttl33@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

5 participants