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(affiliate): Use DB transaction for username generation; add more stats for update… #2579

Merged
merged 3 commits into from
Nov 18, 2024

Conversation

teddyding
Copy link
Contributor

@teddyding teddyding commented Nov 17, 2024

Changelist

[Describe or list the changes made in this PR]

Test Plan

[Describe how this PR was tested (if applicable)]

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 transaction management for username generation and affiliate info updates.
    • Introduced timing metrics for improved performance tracking during tasks.
  • Bug Fixes

    • Improved error handling for username collisions and insertion failures.
  • Tests

    • Updated test cases for username generation to reflect new expected outputs and improve clarity.
    • Modified tests for subaccount username generation to align with the latest username changes.
  • Chores

    • Removed and updated adjectives and nouns in the respective JSON files, impacting the generation process.

Copy link
Contributor

coderabbitai bot commented Nov 17, 2024

Walkthrough

The pull request introduces significant modifications to the runTask functions in two files: subaccount-username-generator.ts and update-affiliate-info.ts. The subaccount-username-generator.ts file implements transaction management for username generation, enhancing error handling and logging. The update-affiliate-info.ts file adds timing metrics to monitor the execution duration of the affiliate info update task. Additionally, test cases for username generation are updated to reflect new expected outputs. These changes aim to improve robustness and performance tracking while maintaining the existing core functionalities.

Changes

File Path Change Summary
indexer/services/roundtable/src/tasks/subaccount-username-generator.ts - Added transaction management using a Transaction object.
- Renamed start to taskStart.
- Enhanced error handling and logging for username collisions and insertions.
- Introduced timing metrics for task execution.
indexer/services/roundtable/src/tasks/update-affiliate-info.ts - Initialized taskStart for overall task duration tracking.
- Added updateAffiliateInfoStartTime for affiliate update timing.
- Maintained existing error handling and logging.
indexer/services/roundtable/__tests__/helpers/usernames-helper.test.ts - Restructured tests for generateUsernameForSubaccount function.
- Split initial test case into two for clarity.
- Updated expected usernames and simplified logic.
indexer/services/roundtable/__tests__/tasks/subaccount-username-generator.test.ts - Updated expected usernames in tests for successful creation of usernames for subaccounts.
indexer/services/roundtable/src/helpers/adjectives.json - Removed several adjectives and re-inserted "zippy" at the end of the list.
indexer/services/roundtable/src/helpers/nouns.json - Removed several nouns from the list, reducing the available set.

Possibly related PRs

Suggested labels

feature:indexer/affiliates

Suggested reviewers

  • affanv14
  • jerryfan01234

🐰 In the realm of code, where bunnies hop,
Transactions now manage, no need to stop.
With timing in place, our tasks run so bright,
Error logs whisper, all errors in sight.
Username generation, now robust and clear,
Hopping through changes, we celebrate here! 🌟


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.

@teddyding teddyding marked this pull request as ready for review November 18, 2024 17:02
@teddyding teddyding requested a review from a team as a code owner November 18, 2024 17:02
@teddyding teddyding changed the title Use DB transaction for username generation; add more stats for update… fix(affiliate): Use DB transaction for username generation; add more stats for update… Nov 18, 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

🧹 Outside diff range and nitpick comments (3)
indexer/services/roundtable/src/tasks/update-affiliate-info.ts (2)

59-70: Consider enhancing metrics for better observability.

The timing metric could be improved in several ways:

  1. The metric name includes "txn" but only measures the update operation, not the entire transaction
  2. Missing tags/labels that could help with metric categorization
  3. Cache update timing is not measured separately

Consider this improvement:

     const updateAffiliateInfoStartTime: number = Date.now();
     await AffiliateInfoTable.updateInfo(windowStartTime.toISO(), windowEndTime.toISO(), txId);
+    stats.timing(
+      `${config.SERVICE_NAME}.update-affiliate-info.update_operation.timing`,
+      Date.now() - updateAffiliateInfoStartTime,
+      { operation: 'update_info', window_size: windowEndTime.diff(windowStartTime).as('days') }
+    );
+
+    const cacheUpdateStartTime: number = Date.now();
     await PersistentCacheTable.upsert({
       key: PersistentCacheKeys.AFFILIATE_INFO_UPDATE_TIME,
       value: windowEndTime.toISO(),
     }, { txId });
+    stats.timing(
+      `${config.SERVICE_NAME}.update-affiliate-info.cache_update.timing`,
+      Date.now() - cacheUpdateStartTime,
+      { operation: 'cache_update' }
+    );

     await Transaction.commit(txId);
-    stats.timing(
-      `${config.SERVICE_NAME}.update-affiliate-info.update-txn.timing`,
-      Date.now() - updateAffiliateInfoStartTime,
-    );

79-80: Enhance the total timing metric with additional context.

While the total timing metric is useful, it could provide more context about the task execution.

Consider adding tags to provide more context:

-  stats.timing(`${config.SERVICE_NAME}.update-affiliate-info.total.timing`, Date.now() - taskStart);
+  stats.timing(
+    `${config.SERVICE_NAME}.update-affiliate-info.total.timing`,
+    Date.now() - taskStart,
+    {
+      status: 'success',
+      window_start: windowStartTime.toISO(),
+      window_end: windowEndTime.toISO(),
+    }
+  );
indexer/services/roundtable/src/tasks/subaccount-username-generator.ts (1)

45-45: Address the TODO comment or remove if obsolete.

The comment // NEXT: use TxnID. at line 45 appears to be a leftover note or a reminder for future implementation. If the transaction ID (txId) is already being used correctly in the code, consider removing this comment to avoid confusion. If additional implementation is needed regarding the transaction ID, please address it accordingly.

Would you like assistance in updating the code to utilize the transaction ID where necessary?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c26c8b8 and afe2f3c.

📒 Files selected for processing (2)
  • indexer/services/roundtable/src/tasks/subaccount-username-generator.ts (1 hunks)
  • indexer/services/roundtable/src/tasks/update-affiliate-info.ts (3 hunks)
🔇 Additional comments (1)
indexer/services/roundtable/src/tasks/update-affiliate-info.ts (1)

21-24: LGTM! Well-structured transaction management.

The transaction properly wraps both the cache operations and affiliate info updates, ensuring atomicity. The timing variable naming is consistent with other files.

Comment on lines 96 to 97
at: 'update-wallet-total-volume#runTask',
message: 'Error when updating totalVolume in wallets table',
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the logging context and message in the error handler.

At lines 96-97, the logger.error function is using an incorrect context and message:

  • The at field is set to 'update-wallet-total-volume#runTask', which does not match the current function context.
  • The message states 'Error when updating totalVolume in wallets table', which is unrelated to the username generation task.

Please update the logging to reflect the correct context and message for this function.

Apply this diff to fix the logging:

 logger.error({
-  at: 'update-wallet-total-volume#runTask',
-  message: 'Error when updating totalVolume in wallets table',
+  at: 'subaccount-username-generator#runTask',
+  message: 'Error when generating usernames',
   error,
 });
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
at: 'update-wallet-total-volume#runTask',
message: 'Error when updating totalVolume in wallets table',
at: 'subaccount-username-generator#runTask',
message: 'Error when generating usernames',

} catch (error) {
await Transaction.rollback(txId);
logger.error({
at: 'update-wallet-total-volume#runTask',
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Update name to subaccount-username-generator.

@@ -149,10 +149,8 @@
"hip",
"holy",
"honest",
"hot",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Refactored both word lists and spot checked 34 proposed whitelist addresses

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

🧹 Outside diff range and nitpick comments (7)
indexer/services/roundtable/__tests__/tasks/subaccount-username-generator.test.ts (1)

Line range hint 31-61: Consider adding transaction-specific test cases.

Since the main implementation now uses DB transactions for username generation, consider adding test cases that verify:

  • Rollback behavior on partial failures
  • Concurrent username generation scenarios
  • Duplicate username handling within transactions

Example test structure:

it('Should rollback all username creations if any fails', async () => {
  // Setup: Create a scenario where one username creation would fail
  // Action: Run username generator
  // Assert: No usernames should be created due to transaction rollback
});

it('Should handle concurrent username generation correctly', async () => {
  // Setup: Create multiple subaccounts
  // Action: Run username generator concurrently
  // Assert: Each subaccount gets a unique username without conflicts
});
indexer/services/roundtable/__tests__/helpers/usernames-helper.test.ts (4)

21-21: Improve test description clarity.

The test description "Check result of generated username" could be more specific about what aspects are being verified.

Consider renaming to: "should generate expected usernames and ensure uniqueness across nonces"


40-51: Enhance test readability and maintainability.

The test logic could be improved in several ways:

  1. The magic number '10' should be defined as a constant with a meaningful name
  2. The comment has a typo ("difference" should be "different")
  3. The test's dual purpose (checking expected values and uniqueness) could be split into separate test cases

Consider this refactor:

+ const NONCE_TEST_COUNT = 10;
+ 
  const gotUserNames = [];
  for (let i = 0; i < addresses.length; i++) {
    const address = addresses[i];
    const namesForOneAddress = new Set();
-   for (let k = 0; k < 10; k++) {
+   for (let k = 0; k < NONCE_TEST_COUNT; k++) {
      const username: string = generateUsernameForSubaccount(address, 0, k);
      if (k === 0) {
        gotUserNames.push(username);
      }
      namesForOneAddress.add(username);
    }
-   // for same address, difference nonce should result in different username
+   // for same address, different nonces should result in different usernames
-   expect(namesForOneAddress.size).toEqual(10);
+   expect(namesForOneAddress.size).toEqual(NONCE_TEST_COUNT);
  }
  expect(gotUserNames).toEqual(expectedUsernames);

54-64: Improve determinism test implementation.

The test has similar issues to the previous one:

  1. Uses magic number '10'
  2. Contains the same comment typo
  3. Could be more explicit about testing determinism

Consider this refactor:

+ const DETERMINISM_TEST_ITERATIONS = 10;
+ 
  it('Check determinism of generated username', () => {
    for (let i = 0; i < addresses.length; i++) {
      const address = addresses[i];
      const namesForOneAddress = new Set();
-     for (let k = 0; k < 10; k++) {
+     for (let k = 0; k < DETERMINISM_TEST_ITERATIONS; k++) {
        const username: string = generateUsernameForSubaccount(address, 0, 0);
        namesForOneAddress.add(username);
      }
-     // for same address, difference nonce should result in different username
+     // Multiple calls with same inputs should produce the same username
      expect(namesForOneAddress.size).toEqual(1);
    }
  });

20-65: Consider adding more test coverage.

The current test suite could benefit from additional test cases:

  1. Error cases (e.g., invalid addresses)
  2. Boundary testing for nonce values
  3. Edge cases for subaccount IDs

Would you like me to provide examples of additional test cases?

indexer/services/roundtable/src/tasks/subaccount-username-generator.ts (2)

33-36: Track technical debt regarding table design.

The comment indicates a known technical debt regarding the subaccount_usernames table design.

Would you like me to create a GitHub issue to track this technical debt for future refactoring?


49-71: Consider enhancing collision metrics.

While the collision handling is good, consider adding these additional metrics for better monitoring:

  • Track consecutive collisions per address
  • Record collision frequency over time

Would you like me to propose the implementation for these additional metrics?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between afe2f3c and 3afa244.

📒 Files selected for processing (5)
  • indexer/services/roundtable/__tests__/helpers/usernames-helper.test.ts (1 hunks)
  • indexer/services/roundtable/__tests__/tasks/subaccount-username-generator.test.ts (1 hunks)
  • indexer/services/roundtable/src/helpers/adjectives.json (1 hunks)
  • indexer/services/roundtable/src/helpers/nouns.json (0 hunks)
  • indexer/services/roundtable/src/tasks/subaccount-username-generator.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • indexer/services/roundtable/src/helpers/nouns.json
🔇 Additional comments (9)
indexer/services/roundtable/__tests__/tasks/subaccount-username-generator.test.ts (1)

52-54: LGTM! Expected username updates look correct.

The updated expected usernames maintain the test's integrity while properly mapping to their respective addresses through the inline comments.

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

5-18: LGTM! Good test data coverage.

The test addresses provide good coverage including edge cases with similar addresses (differing by one character).

indexer/services/roundtable/src/tasks/subaccount-username-generator.ts (5)

13-23: LGTM! Good addition of performance monitoring.

The timing metrics for subaccount fetching will help track performance and identify potential bottlenecks.


25-27: LGTM! Good transaction management setup.

Transaction management is properly implemented with separate timing metrics.


75-91: LGTM! Comprehensive transaction completion and logging.

Good implementation with:

  • Proper transaction commit
  • Detailed logging including batch size and success count
  • Performance metrics

94-98: Fix incorrect error logging message.

The error message still references "updating totalVolume in wallets table" which is incorrect for this context.

As mentioned in the previous review, please apply this fix:

 logger.error({
   at: 'subaccount-username-generator#runTask',
-  message: 'Error when updating totalVolume in wallets table',
+  message: 'Error when generating usernames',
   error,
 });

101-104: LGTM! Good addition of total execution timing.

The total timing metric will help monitor the overall task performance.

indexer/services/roundtable/src/helpers/adjectives.json (2)

Line range hint 1-373: LGTM! Appropriate cleanup of adjectives.

The removal of potentially problematic adjectives ("hot", "humid", "lousy", "low", "pale", "rude", "used", "untidy", "zoom") improves the quality of generated usernames by eliminating terms that could be inappropriate or have negative connotations.


373-373: Verify the impact of adjective reordering on username generation.

Moving "zippy" to the end of the list could affect username generation if the order is used deterministically.

✅ Verification successful

Let me check the username generation logic in the found file to understand how adjectives are used.


Reordering adjectives has no impact on username generation

The username generation logic uses a seeded random number generator (seedrandom) to select adjectives randomly from the array. The order of adjectives in the array doesn't affect the randomness or deterministic nature of the selection since it uses Math.floor(rng() * adjectives.length) to generate random indices. Moving "zippy" to the end of the list will not impact the username generation process.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the username generation logic depends on the order of adjectives

# Search for files that import or use the adjectives.json
rg -l "adjectives.json" --type ts

# Look for any deterministic username generation logic that might depend on array indices
ast-grep --pattern 'function $FUNC($ARGS) {
  $$$
  adjectives[$_]
  $$$
}'

Length of output: 171


Script:

#!/bin/bash
# Check the implementation of username generation
cat indexer/services/roundtable/src/helpers/usernames-helper.ts

Length of output: 1138

@teddyding teddyding merged commit dbdaa87 into main Nov 18, 2024
15 of 16 checks passed
@teddyding teddyding deleted the td/username-txn branch November 18, 2024 17:58
Copy link
Contributor

mergify bot commented Nov 18, 2024

release /indexer/v7.x

❌ Sorry but I didn't understand the command. Please consult the commands documentation 📚.

@teddyding
Copy link
Contributor Author

@Mergifyio backport release/indexer/v7.x

Copy link
Contributor

mergify bot commented Nov 18, 2024

backport release/indexer/v7.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Nov 18, 2024
@coderabbitai coderabbitai bot mentioned this pull request Nov 18, 2024
6 tasks
teddyding added a commit that referenced this pull request Nov 18, 2024
…stats for update… (backport #2579) (#2581)

Co-authored-by: Teddy Ding <[email protected]>
adamfraser pushed a commit that referenced this pull request Nov 20, 2024
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