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

[bugfix][protocol] make funding payment event ordering deterministic #921

Merged

Conversation

lucas-dydx
Copy link
Contributor

@lucas-dydx lucas-dydx commented Jan 3, 2024

Changelist

Make the funding payment event ordering deterministic. Should address this Github issue.

Test Plan

Not tested since the change is fairly simple and doesn't affect anything in state (only events).

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.

Copy link

coderabbitai bot commented Jan 3, 2024

Walkthrough

The update in the UpdateSubaccounts function introduces a sorting mechanism for perpetual IDs within the fundingPayments processing loop. This adjustment guarantees that the order of event emission is consistent and deterministic, which is crucial for maintaining the integrity of the system's operations and for the predictability of its behavior.

Changes

File Path Change Summary
protocol/x/subaccounts/keeper/subaccount.go Modified the UpdateSubaccounts function to sort perpetual IDs before processing fundingPayments to ensure deterministic event emission.

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 with CodeRabbit Bot (@coderabbitai)

  • You can directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • You can tag CodeRabbit on specific lines of code or entire files in the PR by tagging @coderabbitai in a comment. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • You can tag @coderabbitai in a PR comment and ask questions about the PR and the codebase. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid.
    • @coderabbitai read the files in the src/scheduler package and generate README in the markdown format.

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.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

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

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

@lucas-dydx lucas-dydx marked this pull request as ready for review January 3, 2024 21:48
@@ -280,7 +280,10 @@ func (k Keeper) UpdateSubaccounts(
// Emit an event indicating a funding payment was paid / received for each settled funding
// payment. Note that `fundingPaid` is positive if the subaccount paid funding,
// and negative if the subaccount received funding.
for perpetualId, fundingPaid := range fundingPayments {
// Note the perpetual IDs are sorted first to ensure event emission determinism.
sortedPerpsWithFunding := lib.GetSortedKeys[lib.Sortable[uint32]](fundingPayments)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: sortedPerpIds as the variable name?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated!

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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 3e2c518 and 9c364a4.
Files selected for processing (1)
  • protocol/x/subaccounts/keeper/subaccount.go (1 hunks)
Additional comments: 2
protocol/x/subaccounts/keeper/subaccount.go (2)
  • 283-289: The changes introduced in lines 283-289 ensure that the perpetual IDs are sorted before emitting funding payment events, which is intended to address the non-deterministic behavior previously reported. This is a logical change that should ensure deterministic ordering of events. However, it is important to verify that the sorting function lib.GetSortedKeys is correctly implemented and that it does not introduce any side effects or performance issues, especially considering that this function is likely to be called frequently.
Verification successful

The previous script did not yield any results, which could be due to the specificity of the pattern used in ast-grep. To ensure we are not missing any matches due to pattern specificity, let's broaden the search to find any usage of GetSortedKeys without specifying the type.


Since the ast-grep command did not produce any results, I will use ripgrep (rg) to search for the string "GetSortedKeys" within the codebase to confirm its existence and implementation.


The ripgrep search has confirmed the existence of the GetSortedKeys function in multiple files. To verify its implementation, I will generate a script to view the content of collections.go where the function is defined.


The GetSortedKeys function is defined in the collections.go file and its implementation is as follows:

// GetSortedKeys returns the keys of the map in sorted order.
func GetSortedKeys[R interface {
	~[]K
	sort.Interface
}, K comparable, V any](m map[K]V) []K {
	keys := make([]K, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Sort(R(keys))
	return keys
}

This function takes a map as input and returns a slice of keys sorted according to the sort order defined by the type R, which must implement sort.Interface. The function appears to be generic and should work correctly for sorting keys of any type that can be ordered, including uint32 as used in the PR.

Based on the implementation, there are no obvious side effects or performance issues, assuming that the sorting interface is implemented efficiently for the types used.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the implementation of lib.GetSortedKeys for uint32 types.
ast-grep --lang go --pattern $'lib.GetSortedKeys[lib.Sortable[uint32]]($_)'

Length of output: 76



Script:

#!/bin/bash
# Broaden the search to find any usage of GetSortedKeys
ast-grep --lang go --pattern $'lib.GetSortedKeys($_)'

Length of output: 54



Script:

#!/bin/bash
# Search for the string "GetSortedKeys" to confirm its existence and implementation
rg 'GetSortedKeys'

Length of output: 2980



Script:

#!/bin/bash
# View the implementation of GetSortedKeys in collections.go
cat protocol/lib/collections.go

Length of output: 2807

* 283-289: Given the nature of the changes, it would be prudent to consider if any specific labels such as `bug` or `refactor` are applicable to this PR, as per the checklist provided in the PR objectives. This helps in categorizing the PR correctly for future reference and may aid in the changelog generation process.

Comment on lines 283 to 289
// Note the perpetual IDs are sorted first to ensure event emission determinism.
sortedPerpsWithFunding := lib.GetSortedKeys[lib.Sortable[uint32]](fundingPayments)
for _, perpetualId := range sortedPerpsWithFunding {
fundingPaid := fundingPayments[perpetualId]
ctx.EventManager().EmitEvent(
types.NewCreateSettledFundingEvent(
*u.SettledSubaccount.Id,
Copy link

Choose a reason for hiding this comment

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

While the author of the PR has stated that tests are not necessary because the changes do not affect the state, only the events, it is still recommended to perform tests to ensure that the deterministic ordering of events does not introduce any regressions or unexpected behavior. This is particularly important because the ordering of events can have downstream effects on clients and services that consume these events.

+ // TODO: Add tests to ensure deterministic ordering of events and check for any regressions.

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
// Note the perpetual IDs are sorted first to ensure event emission determinism.
sortedPerpsWithFunding := lib.GetSortedKeys[lib.Sortable[uint32]](fundingPayments)
for _, perpetualId := range sortedPerpsWithFunding {
fundingPaid := fundingPayments[perpetualId]
ctx.EventManager().EmitEvent(
types.NewCreateSettledFundingEvent(
*u.SettledSubaccount.Id,
// Note the perpetual IDs are sorted first to ensure event emission determinism.
// TODO: Add tests to ensure deterministic ordering of events and check for any regressions.
sortedPerpsWithFunding := lib.GetSortedKeys[lib.Sortable[uint32]](fundingPayments)
for _, perpetualId := range sortedPerpsWithFunding {
fundingPaid := fundingPayments[perpetualId]
ctx.EventManager().EmitEvent(
types.NewCreateSettledFundingEvent(
*u.SettledSubaccount.Id,

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9c364a4 and 354db12.
Files selected for processing (1)
  • protocol/x/subaccounts/keeper/subaccount.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/subaccounts/keeper/subaccount.go

@lucas-dydx lucas-dydx merged commit b1cbf42 into main Jan 3, 2024
16 of 17 checks passed
@lucas-dydx lucas-dydx deleted the lucas-dydx/protocol-deterministic-funding-event-ordering branch January 3, 2024 23:04
@roy-dydx
Copy link
Contributor

@Mergifyio backport release/protocol/v2.x

Copy link

mergify bot commented Mar 12, 2024

backport release/protocol/v2.x

🟠 Waiting for conditions to match

  • merged [📌 backport requirement]

roy-dydx added a commit that referenced this pull request Mar 12, 2024
…921) (#1166)

Co-authored-by: lucas-dydx <76970939+lucas-dydx@users.noreply.github.com>
@roy-dydx
Copy link
Contributor

roy-dydx commented May 2, 2024

https://github.com/Mergifyio backport release/protocol/v3.x

Copy link

mergify bot commented May 2, 2024

backport release/protocol/v3.x

🟠 Waiting for conditions to match

  • merged [📌 backport requirement]

roy-dydx added a commit that referenced this pull request May 2, 2024
…921) (#1455)

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

Successfully merging this pull request may close these issues.

None yet

3 participants