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-970] Add debug logs to roundtable task, fix case where marketId!=perpetualId #1786

Merged
merged 15 commits into from
Jun 27, 2024

Conversation

dydxwill
Copy link
Contributor

@dydxwill dydxwill commented Jun 26, 2024

Changelist

calculateEquity function was failing when marketId!=perpetualId, as is the case for dydx (perpetualId=63, marketId=1000001)

Test Plan

Tested in e2e env.

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

    • Added support for a new branch to trigger workflows in the mainnet.
  • Bug Fixes

    • Improved test cases to handle scenarios with missing prices and mismatches between perpetualId and marketId.
  • Logging Enhancements

    • Introduced detailed logging to track account/subaccount information and errors during PNL tick creation and equity calculation.
  • Performance Improvements

    • Enhanced market and perpetual market updates during equity calculations for better accuracy.

Copy link
Contributor

coderabbitai bot commented Jun 26, 2024

Warning

Review failed

The pull request is closed.

Walkthrough

This update introduces significant enhancements and new test scenarios for the PNL tick creation and calculation logic. It includes additional logging to track key details, error conditions, and significant changes in equity or total PNL. The changes also ensure the workflow triggers for a new branch, 'wl/pnldbg2', alongside other branches.

Changes

Files Change Summaries
.github/workflows/indexer-build-and-push-mainnet.yml Added 'wl/pnldbg2' branch to trigger workflow along with existing branches.
indexer/services/roundtable/__tests__/helpers/pnl-ticks-helper.test.ts Added new test cases for missing price scenario and perpetualId/marketId mismatch in calculateEquity.
indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts Added detailed logging for tracking PNL tick creation and calculation of equity and total PNL.
indexer/services/roundtable/src/tasks/create-pnl-ticks.ts Imported perpetualMarketRefresher and added call to updatePerpetualMarkets() in runTask function.

Poem

Amidst the code where numbers dance,
We've given equity a fighting chance.
Logs now track each tick and tale,
To ensure our PNL won't derail.
So here's a cheer, a code delight,
For branches new and tests so bright! 🌟 👾


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 Configration 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.

@dydxwill dydxwill changed the title Add debug logs to roundtable task, fix case where market price doesn't exist yet [CT-970] Add debug logs to roundtable task, fix case where market price doesn't exist yet Jun 26, 2024
Copy link

linear bot commented Jun 26, 2024

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f320246 and 03f2f70.

Files selected for processing (3)
  • .github/workflows/indexer-build-and-push-mainnet.yml (1 hunks)
  • indexer/services/roundtable/tests/helpers/pnl-ticks-helper.test.ts (1 hunks)
  • indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts (7 hunks)
Additional comments not posted (4)
.github/workflows/indexer-build-and-push-mainnet.yml (1)

6-6: Confirm appropriateness of new branch trigger for workflow.

The addition of the 'wl/pnldbg2' branch to the workflow triggers is noted. Please confirm that this branch is intended for changes that should trigger Mainnet deployments.

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

76-101: Review added logging statements for clarity and necessity.

Logging has been added to getPnlTicksCreateObjects to provide insights into the process of creating PNL ticks. Ensure that these logs provide clear, actionable information and do not expose sensitive data.


Line range hint 316-388: Validate new logging in getNewPnlTick for utility and security.

The extensive logging in getNewPnlTick is useful for debugging but ensure it does not lead to potential leakage of sensitive information. Validate that the logged data is necessary and properly sanitized.

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

351-381: Review new test case for handling missing market prices.

The new test case calculateEquity with missing price is designed to test the equity calculation when a market price is missing. Ensure this test adequately covers all edge cases related to missing market prices.

Comment on lines +196 to +208
error,
account,
pnlTicksToBeCreatedAt,
blockHeight,
blockTime,
});
}
});
logger.info({
at: 'pnl-ticks-helper#getPnlTicksCreateObjects',
message: 'New ticks to create',
subaccountIds: _.map(newTicksToCreate, 'subaccountId'),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure error handling includes necessary details for debugging.

The error logging within getPnlTicksCreateObjects should include all relevant information to diagnose issues effectively. Consider adding more context if needed.

-        error,
-        account,
-        pnlTicksToBeCreatedAt,
-        blockHeight,
-        blockTime,
+        error: error.message,
+        account: account.id,  # Assuming `account` is an object
+        pnlTicksToBeCreatedAt: pnlTicksToBeCreatedAt.toISO(),
+        blockHeight: blockHeight.toString(),
+        blockTime: blockTime.toString(),

Committable suggestion was skipped due to low confidence.

@dydxwill dydxwill changed the title [CT-970] Add debug logs to roundtable task, fix case where market price doesn't exist yet [CT-970] Add debug logs to roundtable task, fix case where marketId!=perpetualId Jun 26, 2024
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 03f2f70 and 8b51353.

Files selected for processing (3)
  • indexer/services/roundtable/tests/helpers/pnl-ticks-helper.test.ts (4 hunks)
  • indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts (8 hunks)
  • indexer/services/roundtable/src/tasks/create-pnl-ticks.ts (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts
Additional comments not posted (3)
indexer/services/roundtable/src/tasks/create-pnl-ticks.ts (1)

8-8: Approved addition of perpetualMarketRefresher import.

The import and usage of perpetualMarketRefresher are crucial for ensuring that market data is up-to-date before processing PnL ticks, aligning with the PR's objectives to fix related issues.

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

20-24: Approved new imports and test setup enhancements.

The addition of new imports and the update call in the beforeEach hook are appropriate for the new test scenarios introduced. Ensure that updatePerpetualMarkets() is effectively mocked or isolated during testing to prevent unintended side effects.


359-417: Approved new test case for perpetualId/marketId mismatch scenario.

The test case is well-structured and addresses a critical scenario. Ensure comprehensive validation of the mismatch handling to cover potential edge cases that might not be represented by the current test setup.

Verification successful

Approved new test case for perpetualId/marketId mismatch scenario.

The test case is well-structured and addresses a critical scenario. The search results indicate that various edge cases involving perpetualId are covered in the tests. Ensure comprehensive validation of the mismatch handling to cover potential edge cases that might not be represented by the current test setup.

  • indexer/services/roundtable/__tests__/helpers/pnl-ticks-helper.test.ts
  • indexer/services/roundtable/__tests__/tasks/market-updater.test.ts
  • indexer/services/roundtable/__tests__/tasks/create-pnl-ticks.test.ts
  • indexer/services/ender/__tests__/handlers/order-fills/liquidation-handler.test.ts
  • indexer/services/ender/__tests__/handlers/funding-handler.test.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that all edge cases for `perpetualId/marketId` mismatch are covered in tests.
rg --type py "perpetualId" "*/__tests__/*"

Length of output: 96



Script:

#!/bin/bash
# Verify that all edge cases for `perpetualId/marketId` mismatch are covered in tests.
rg --type ts "perpetualId" "*/__tests__/*"

Length of output: 96



Script:

#!/bin/bash
# Locate all test files in the repository and search for `perpetualId`.
fd --type f --name "*.test.ts" | xargs rg "perpetualId"

Length of output: 107018

@@ -53,6 +54,7 @@ export default async function runTask(): Promise<void> {
const txId: number = await Transaction.start();
let newTicksToCreate: PnlTicksCreateObject[] = [];
try {
await perpetualMarketRefresher.updatePerpetualMarkets();
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure proper error handling and transaction management when updating perpetual markets.

The function updatePerpetualMarkets does not perform any write operations that could affect the transaction's atomicity. However, consider wrapping the call to updatePerpetualMarkets in a try-catch block to handle potential exceptions explicitly and maintain clean transaction boundaries.

  • File: indexer/services/roundtable/src/tasks/create-pnl-ticks.ts
  • Line: 57
Analysis chain

Ensure proper error handling and transaction management when updating perpetual markets.

The addition of perpetualMarketRefresher.updatePerpetualMarkets() within a transaction is a critical update. Ensure that this method does not have side effects that could affect the transaction's atomicity.

Consider wrapping the call to updatePerpetualMarkets() in a try-catch block to handle potential exceptions explicitly and maintain clean transaction boundaries.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that `updatePerpetualMarkets` does not perform any write operations that could affect the transaction's integrity.
ast-grep --lang typescript --pattern $'async function updatePerpetualMarkets() {
  $$$
}'

Length of output: 90



Script:

#!/bin/bash
# Searching for the definition of `updatePerpetualMarkets` to inspect its implementation
rg 'updatePerpetualMarkets' --glob '*.{ts,js}'

Length of output: 9773



Script:

#!/bin/bash
# Extracting the implementation of `updatePerpetualMarkets` from the identified file
ast-grep --lang typescript --pattern $'export async function updatePerpetualMarkets($_): Promise<void> {
  $$$
}' indexer/packages/postgres/src/loops/perpetual-market-refresher.ts

Length of output: 2064

@@ -73,6 +80,7 @@ describe('pnl-ticks-helper', () => {

beforeEach(async () => {
await testMocks.seedData();
await perpetualMarketRefresher.updatePerpetualMarkets();
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure isolation of market updates in test setup.

The updatePerpetualMarkets function is called in the test files but is not explicitly mocked. To prevent actual database or network interactions during tests, ensure that this function is properly mocked.

  • indexer/services/roundtable/__tests__/helpers/pnl-ticks-helper.test.ts
  • indexer/services/roundtable/__tests__/tasks/remove-expired-orders.test.ts
Analysis chain

Ensure isolation of market updates in test setup.

Calling updatePerpetualMarkets() in the beforeEach hook is crucial for setting a consistent state. However, ensure this is properly mocked to prevent actual database or network interactions during tests.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that `updatePerpetualMarkets` is mocked in tests to prevent real interactions.
rg --type py "updatePerpetualMarkets" "*/__tests__/*"

Length of output: 107



Script:

#!/bin/bash
# Verify that `updatePerpetualMarkets` is mocked in tests to prevent real interactions.
rg "updatePerpetualMarkets" "*/__tests__/*"

Length of output: 97



Script:

#!/bin/bash
# Find all TypeScript test files and search for `updatePerpetualMarkets` to verify if it is mocked.
fd --type f --extension ts --search-path "indexer/services/roundtable/__tests__" | xargs rg "updatePerpetualMarkets"

Length of output: 509



Script:

#!/bin/bash
# Verify if `updatePerpetualMarkets` is mocked in the identified test files.
rg "updatePerpetualMarkets" --context 10 "indexer/services/roundtable/__tests__/tasks/remove-expired-orders.test.ts" "indexer/services/roundtable/__tests__/helpers/pnl-ticks-helper.test.ts"

Length of output: 6610

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8b51353 and 02749a1.

Files selected for processing (1)
  • indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts (7 hunks)
Files skipped from review as they are similar to previous changes (1)
  • indexer/services/roundtable/src/helpers/pnl-ticks-helper.ts

@dydxwill dydxwill merged commit d165d10 into main Jun 27, 2024
11 checks passed
@dydxwill dydxwill deleted the wl/pnldbg2 branch June 27, 2024 17:10
@dydxwill
Copy link
Contributor Author

@Mergifyio backport release/indexer/v5.x

Copy link
Contributor

mergify bot commented Jun 27, 2024

backport release/indexer/v5.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Jun 27, 2024
dydxwill added a commit that referenced this pull request Jun 27, 2024
…perpetualId (backport #1786) (#1795)

Co-authored-by: dydxwill <119354122+dydxwill@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.

2 participants