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(ledger): tx reversion handles empty middle accounts #711

Merged
merged 1 commit into from
Feb 26, 2025

Conversation

CrosleyZack
Copy link
Contributor

Suppose we have three accounts:

account_one with balance 10
account_two with balance 0
world

If we create a transaction with postings
account_one -5-> account_two
account_two -5-> world

we will end up with final balances

account_one with balance 5
account_two with balance 0
world

When trying to revert this transaction, we will:

  1. Get balances for destination accounts, in this case account_one and account_two [line 388]
  2. Reverse our postings so our sources are world and account_two [line 395]
  3. Iterating over postings, we will deduct posting.Amount from each of world and account 2 [line 405]
  4. Verify that all three accounts are non negative [line 415]

In this example, because account_two has no balance we will deduct 5 credits from it and end up with -5, thus the reversion is failed. However, this only occurs because we account for the credits being removed from account_two and not the credits being added.

The solution is to track both the source and destination when adjusting credits on line 405 so we can add in the five credits that will be added to account_two from world so they exist in order to be deducted via the reversion

@CrosleyZack CrosleyZack requested a review from a team as a code owner February 25, 2025 17:49
Copy link

coderabbitai bot commented Feb 25, 2025

Walkthrough

This change updates the revertTransaction method within the controller for ledger transactions. When a transaction is reverted without forcing the operation, the destination account’s balance is now explicitly updated by adding the reverted amount. Additionally, a new test scenario is introduced to validate the creation and reversion of transactions through an empty passthrough account, ensuring that the functionality behaves as expected.

Changes

File Path Changes Summary
internal/.../controller_default.go Modified the revertTransaction method to update the destination account’s balance by adding the reverted amount when the transaction is non-forced.
test/e2e/.../api_transactions_revert_test.go Added a new test scenario for creating and reverting transactions through an empty passthrough account, verifying that the operation succeeds and the transaction is correctly reverted.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Transaction Caller
    participant C as DefaultController
    participant B as Balance Map

    Client->>C: revertTransaction(tx)
    alt Non-forced Transaction Reversal
        C->>B: Retrieve current balance for posting.Destination
        C->>B: Add posting.Amount to current balance
    end
    C-->>Client: Transaction reverted with updated balances
Loading

Poem

In the code's garden, I hop with delight,
Reverting transactions by day and by night.
Balances get a boost, neatly computed,
With every update, errors diluted.
Hoppy changes—leap high, code bright!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cabdc82 and b5dd7c3.

📒 Files selected for processing (2)
  • internal/controller/ledger/controller_default.go (1 hunks)
  • test/e2e/api_transactions_revert_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/controller/ledger/controller_default.go
  • test/e2e/api_transactions_revert_test.go

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 generate docstrings to generate docstrings for 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.

@CrosleyZack CrosleyZack force-pushed the crosley/ledger-fix-tx-reversion branch from 3660f41 to 3b32fc5 Compare February 25, 2025 19:15
Comment on lines 409 to 415
if _, ok := balances[posting.Destination]; ok {
// if this source is also a destination
balances[posting.Destination][posting.Asset] = balances[posting.Destination][posting.Asset].Add(
balances[posting.Destination][posting.Asset],
posting.Amount,
)
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

If the destination is also a source, which it should only appear in balances if it is (see lines 388-390), then add the posting amount into the tracked balance.

@CrosleyZack CrosleyZack force-pushed the crosley/ledger-fix-tx-reversion branch from 3b32fc5 to 667e480 Compare February 25, 2025 19:17
@gfyrag gfyrag changed the title fix(ledger) tx reversion handles empty middle accounts fix(ledger): tx reversion handles empty middle accounts Feb 26, 2025
Copy link

codecov bot commented Feb 26, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 81.70%. Comparing base (a929bff) to head (b5dd7c3).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #711      +/-   ##
==========================================
+ Coverage   81.49%   81.70%   +0.20%     
==========================================
  Files         133      135       +2     
  Lines        7170     7290     +120     
==========================================
+ Hits         5843     5956     +113     
- Misses       1023     1027       +4     
- Partials      304      307       +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@CrosleyZack CrosleyZack force-pushed the crosley/ledger-fix-tx-reversion branch from 667e480 to 6f0046f Compare February 26, 2025 13:50
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 (1)
test/e2e/api_transactions_revert_test.go (1)

222-283: Test case successfully validates the fix for empty passthrough accounts.

The new test scenario correctly validates the expected behavior of reverting transactions through empty passthrough accounts. This aligns with the PR objective of fixing transactions involving accounts with zero balances.

A few suggestions for improvement:

  1. For consistency with other test blocks, consider moving the RevertTransaction call inside a BeforeEach block.
  2. Consider adding balance verification after reversion to fully validate that all accounts return to their original state.
 When("trying to revert the passthrough transaction", func() {
-   _, err := RevertTransaction(
-     ctx,
-     testServer.GetValue(),
-     operations.V2RevertTransactionRequest{
-       Ledger:          "default",
-       ID:              tx.ID,
-       AtEffectiveDate: pointer.For(true),
-     },
-   )
-   Expect(err).To(Succeed())
+   BeforeEach(func() {
+     _, err := RevertTransaction(
+       ctx,
+       testServer.GetValue(),
+       operations.V2RevertTransactionRequest{
+         Ledger:          "default",
+         ID:              tx.ID,
+         AtEffectiveDate: pointer.For(true),
+       },
+     )
+     Expect(err).To(Succeed())
+   })
+   
+   It("should restore original account balances", func() {
+     // Add balance checks for alice, bob, and world accounts
+     // to verify they return to their original state
+   })
 })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 667e480 and 6f0046f.

📒 Files selected for processing (2)
  • internal/controller/ledger/controller_default.go (1 hunks)
  • test/e2e/api_transactions_revert_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/controller/ledger/controller_default.go

@CrosleyZack CrosleyZack force-pushed the crosley/ledger-fix-tx-reversion branch from 6f0046f to 674744e Compare February 26, 2025 13:58
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: 2

🧹 Nitpick comments (1)
test/e2e/api_transactions_revert_test.go (1)

229-257: Consider adding additional assertions for account balances.

While the test validates that the transaction is reverted, it doesn't explicitly verify that the account balances are correctly restored after reversion, which is the core issue being fixed. Consider adding balance checks before and after reversion.

Add balance verification to fully validate the fix:

// Add after transaction creation
balanceWalter, err := GetAccount(ctx, testServer.GetValue(), operations.V2GetAccountRequest{
    Ledger: "default",
    Address: "walter",
})
Expect(err).NotTo(HaveOccurred())
Expect(balanceWalter.Balances["USD"]).To(Equal("-100")) // Walter sent 100 USD

balanceWendy, err := GetAccount(ctx, testServer.GetValue(), operations.V2GetAccountRequest{
    Ledger: "default",
    Address: "wendy",
})
Expect(err).NotTo(HaveOccurred())
Expect(balanceWendy.Balances["USD"]).To(Equal("0")) // Wendy received and sent 100 USD

// Add after transaction reversion
balanceWalterAfter, err := GetAccount(ctx, testServer.GetValue(), operations.V2GetAccountRequest{
    Ledger: "default",
    Address: "walter",
})
Expect(err).NotTo(HaveOccurred())
Expect(balanceWalterAfter.Balances["USD"]).To(Equal("0")) // Balance restored

balanceWendyAfter, err := GetAccount(ctx, testServer.GetValue(), operations.V2GetAccountRequest{
    Ledger: "default",
    Address: "wendy",
})
Expect(err).NotTo(HaveOccurred())
Expect(balanceWendyAfter.Balances["USD"]).To(Equal("0")) // Still zero
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6f0046f and 674744e.

📒 Files selected for processing (2)
  • internal/controller/ledger/controller_default.go (1 hunks)
  • test/e2e/api_transactions_revert_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/controller/ledger/controller_default.go
🔇 Additional comments (1)
test/e2e/api_transactions_revert_test.go (1)

222-283: Well-structured test case for passthrough account scenario.

This new test case effectively validates the fix for handling transaction reversion through an empty passthrough account. The test creates a transaction where "wendy" acts as both a destination and source account in different postings, which directly addresses the issue described in the PR objectives.

A few observations:

  1. The test correctly creates a transaction with two linked postings (walter → wendy → world)
  2. It verifies that the transaction can be reverted properly
  3. The assertions check both that the transaction is marked as reverted and that the timestamp is preserved

This test provides good coverage for the scenario where an intermediate account with zero balance is involved in a transaction that needs to be reverted.

@CrosleyZack CrosleyZack force-pushed the crosley/ledger-fix-tx-reversion branch 3 times, most recently from 65fc253 to cabdc82 Compare February 26, 2025 16:15
@CrosleyZack CrosleyZack force-pushed the crosley/ledger-fix-tx-reversion branch from cabdc82 to b5dd7c3 Compare February 26, 2025 16:23
@gfyrag gfyrag enabled auto-merge February 26, 2025 16:30
@gfyrag gfyrag disabled auto-merge February 26, 2025 16:30
@gfyrag gfyrag added this pull request to the merge queue Feb 26, 2025
Merged via the queue into formancehq:main with commit 08f8e2a Feb 26, 2025
10 checks passed
CrosleyZack added a commit to CrosleyZack/ledger that referenced this pull request Feb 26, 2025
@altitude
Copy link
Member

Thank you @CrosleyZack!

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.

3 participants