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

[CT-1307] Make pnl ticks computation consistent within a transaction. #2548

Merged
merged 1 commit into from
Oct 30, 2024

Conversation

vincentwschau
Copy link
Contributor

@vincentwschau vincentwschau commented Oct 29, 2024

Changelist

Fetch the latest block within the same transaction as other PnL tick data to avoid race conditions.

Test Plan

Unit tests.

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

    • Enhanced PnL tick creation process by integrating the latest block data for improved accuracy.
  • Bug Fixes

    • Updated test cases to reflect changes in the parameters and logic for creating new PnL ticks.
  • Documentation

    • Clarified method signatures and updated internal documentation to align with new function parameters.

@vincentwschau vincentwschau requested a review from a team as a code owner October 29, 2024 15:22
Copy link

linear bot commented Oct 29, 2024

Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes in this pull request focus on modifying the pnl-ticks-helper module, specifically the getNewPnlTicks function and its associated tests. The handling of blockHeight and blockTime has been streamlined, with these parameters being removed from the function signature and replaced by values derived from the latest block. The test suite has been updated to reflect these changes, ensuring accuracy in the creation of new PnL ticks. Additionally, minor adjustments have been made to the test lifecycle management.

Changes

File Path Change Summary
indexer/services/roundtable/__tests__/helpers/pnl-ticks-helper.test.ts Updated tests for getNewPnlTicks to reflect changes in parameters and logic; adjusted setup and teardown processes for better state management.
indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts Modified getPnlTicksCreateObjects to remove blockHeight and blockTime, now fetching values from latestBlock; updated logging statements.
indexer/services/roundtable/src/tasks/create-pnl-ticks.ts Changed runTask to call getPnlTicksCreateObjects with only txId, simplifying the function's input parameters.

Possibly related PRs

Suggested labels

indexer, feature:indexer/affiliates

🐰 In the garden where the ticks grow,
A new way to count, as we now know.
With blocks and time, we’ve made it clear,
Creating PnL ticks brings us cheer!
So hop along, let’s test and play,
With every tick, we’ll find our way! 🥕


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.

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: 2

🧹 Outside diff range and nitpick comments (2)
indexer/services/roundtable/src/tasks/create-pnl-ticks.ts (2)

Line range hint 61-69: Consider updating error logging to reflect actual function parameters.

The error logging still includes latestBlockHeight and latestBlockTime even though these are no longer passed to getPnlTicksCreateObjects. Consider updating the logging to be consistent with the new implementation.

 logger.error({
   at: 'create-pnl-ticks#runTask',
   message: 'Error when getting pnl ticks',
   error,
-  latestBlockHeight,
-  latestBlockTime,
   txId,
 });

Transaction isolation level should be explicitly set to prevent race conditions

The code starts transactions but doesn't set an isolation level explicitly. While the default PostgreSQL isolation level (READ COMMITTED) prevents dirty reads, for operations involving PNL calculations that need consistent reads across tables, you should explicitly set REPEATABLE READ or SERIALIZABLE isolation level.

  • In create-pnl-ticks.ts, after Transaction.start(), add Transaction.setIsolationLevel(txId, IsolationLevel.REPEATABLE_READ) to ensure consistent reads across the transaction.
  • Add the same for the transaction in the chunked ticks processing loop.
🔗 Analysis chain

Line range hint 57-74: Verify transaction isolation level for race condition prevention.

The code uses transactions to ensure consistency, which is good. However, to fully prevent race conditions, we should verify that the appropriate transaction isolation level is being used.


Let me gather more information about how the transaction is being used in the PNL ticks creation.


Let me check one more thing to understand the default isolation level in the database configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for transaction isolation level configuration
rg -A 5 "isolation.*level" 
# Also check the Transaction class implementation
ast-grep --pattern 'class Transaction {
  $$$
}'

Length of output: 3713


Script:

#!/bin/bash
# Search for transaction start and isolation level usage in create-pnl-ticks
rg -B 5 -A 5 "Transaction\.(start|setIsolationLevel)" indexer/services/roundtable/src/tasks/create-pnl-ticks.ts

# Check if IsolationLevel is imported and used
rg -B 2 -A 2 "IsolationLevel" indexer/services/roundtable/src/tasks/create-pnl-ticks.ts

# Look for the getPnlTicksCreateObjects implementation to understand transaction usage
ast-grep --pattern 'async function getPnlTicksCreateObjects($_) {
  $$$
}'

Length of output: 1141


Script:

#!/bin/bash
# Check database configuration files for default isolation level
rg -B 3 -A 3 "isolation" indexer/packages/postgres/src/config.ts
rg -B 3 -A 3 "isolation" indexer/packages/postgres/src/db.ts

# Check if there are any other files setting transaction isolation
rg -g "!*.md" -g "!*.test.*" -B 3 -A 3 "SET TRANSACTION ISOLATION LEVEL"

Length of output: 895

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2198a3b and bb9243e.

📒 Files selected for processing (3)
  • indexer/services/roundtable/tests/helpers/pnl-ticks-helper.test.ts (3 hunks)
  • indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts (2 hunks)
  • indexer/services/roundtable/src/tasks/create-pnl-ticks.ts (1 hunks)
🔇 Additional comments (5)
indexer/services/roundtable/src/tasks/create-pnl-ticks.ts (1)

58-58: LGTM! The change aligns with making block data fetching consistent.

The modification to only pass txId to getPnlTicksCreateObjects is a good improvement as it ensures the block data is fetched within the same transaction context, preventing potential race conditions.

indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts (2)

4-5: LGTM: Block fetching encapsulation improves consistency

The changes to fetch the latest block within the transaction context and removal of blockHeight/blockTime parameters from the function signature help prevent potential race conditions, making the PnL ticks computation more consistent.

Also applies to: 58-63


58-63: Verify impact on dependent systems

The change in how block data is obtained might affect systems that depend on this function. Please ensure that all dependent systems are aware of this change and can handle potential errors from block fetching.

Let's verify the usage of this function across the codebase:

✅ Verification successful

No impact on dependent systems - change is properly handled

The verification shows that the change in block data retrieval is safe and properly handled:

  1. The function is only used in two places:

    • create-pnl-ticks.ts: Has proper error handling with try-catch and transaction rollback
    • pnl-instrumentation.ts: Only imports a different function from the helper
  2. The test file confirms:

    • All database operations are wrapped in transactions
    • Error cases are properly tested
    • Block data is consistently used across the function

The change maintains transactional consistency and error handling, with no breaking changes to the interface or behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct calls to getPnlTicksCreateObjects
echo "Searching for direct function calls..."
rg "getPnlTicksCreateObjects\(" -A 2

# Search for any error handling patterns around this function
echo "Checking error handling patterns..."
rg "getPnlTicksCreateObjects.*catch" -A 5

Length of output: 1484


Script:

#!/bin/bash
# Let's examine the error handling in create-pnl-ticks.ts where the function is called
echo "Checking error handling in create-pnl-ticks.ts..."
cat indexer/services/roundtable/src/tasks/create-pnl-ticks.ts

# Let's also check the test file to understand the expected behavior
echo "Checking test file..."
cat indexer/services/roundtable/__tests__/helpers/pnl-ticks-helper.test.ts

# Let's check if there are any other files importing this helper
echo "Checking imports of pnl-ticks-helper..."
rg "from ['\"]\.\./helpers/pnl-ticks-helper" --type ts

Length of output: 22885

indexer/services/roundtable/__tests__/helpers/pnl-ticks-helper.test.ts (2)

480-481: LGTM!

The block data setup is correct and properly formatted for test verification.


500-500: LGTM!

The updated function call correctly reflects the new signature that only requires txId, aligning with the PR's objective of making PnL ticks computation consistent within a transaction.

@vincentwschau vincentwschau merged commit f6101a3 into main Oct 30, 2024
16 checks passed
@vincentwschau vincentwschau deleted the vincentc/make-pnl-ticks-task-consistent branch October 30, 2024 14:48
mergify bot pushed a commit that referenced this pull request Oct 30, 2024
vincentwschau added a commit that referenced this pull request Oct 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

2 participants