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

[WEB-2706] fix: Make SQL transactions smaller #6085

Open
wants to merge 1 commit into
base: preview
Choose a base branch
from

Conversation

SatishGandham
Copy link
Collaborator

@SatishGandham SatishGandham commented Nov 22, 2024

  • Change batch size to 50 for inserting issues
  • Fallback to server when mentions filter is used
  • Split load workspace into multiple transactions

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new utility function to determine when to fetch issues from the server based on query parameters.
  • Improvements

    • Enhanced bulk issue insertion efficiency with concurrent processing.
    • Implemented explicit transaction management for batch inserts during workspace data loading.
    • Updated issue retrieval logic to streamline decision-making on data sources.
  • Bug Fixes

    • Improved error handling and control flow in issue synchronization and retrieval processes.

- Fallback to server when mentions filter is used
- Split load workspace into multiple transactions
Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

Walkthrough

The changes involve modifications to several files related to the Storage class and issue handling within a local database context. Key updates include a reduction in the BATCH_SIZE constant, improvements to the getIssue and getSubIssues methods for better control flow and error handling, and enhancements to the addIssuesBulk function for more efficient bulk insertions. Additionally, a new utility function is introduced to streamline the decision-making process for fetching issues from the server or local persistence.

Changes

File Path Change Summary
web/core/local-db/storage.sqlite.ts - BATCH_SIZE constant reduced from 500 to 50.
- Updated getIssue method with additional status check.
- Modified getSubIssues method to check workspace_synced_at.
web/core/local-db/utils/load-issues.ts - addIssuesBulk method's batchSize default changed from 100 to 50.
- Updated insertion logic to use Promise.all for concurrent operations.
web/core/local-db/utils/load-workspace.ts - Added explicit transaction management for batch inserts in loadWorkSpaceData function.
web/core/services/issue/issue.service.ts - Updated getIssues method to use getIssuesShouldFallbackToServer for control flow.
web/helpers/issue.helper.ts - Added new function getIssuesShouldFallbackToServer to evaluate server fallback conditions.

Possibly related PRs

Suggested labels

⚡performance, 🧹chore

Suggested reviewers

  • rahulramesha
  • pushya22

🐇 In the database, we hop and play,
With issues loaded in a new way.
Batches small, but swift they go,
Through transactions, we make it flow.
So let’s cheer for the code we write,
In the local store, everything’s right! 🌟


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

🧹 Outside diff range and nitpick comments (6)
web/core/local-db/utils/load-issues.ts (2)

40-40: Consider enhancing performance logging.

While the current logging is helpful, consider adding more granular performance metrics:

-  log("Inserted issues in ", `${insertEnd - insertStart}ms`, batchSize, issues.length);
+  const totalTime = insertEnd - insertStart;
+  const avgTimePerBatch = totalTime / Math.ceil(issues.length / batchSize);
+  log(
+    "Bulk insert completed",
+    `Total time: ${totalTime}ms`,
+    `Avg time per batch: ${avgTimePerBatch.toFixed(2)}ms`,
+    `Batch size: ${batchSize}`,
+    `Total issues: ${issues.length}`
+  );

Line range hint 18-41: Consider adding telemetry for monitoring bulk operation performance.

To better understand the impact of these optimizations in production:

  • Consider implementing metrics collection for bulk operation timings
  • Track success/failure rates of batch operations
  • Monitor transaction sizes and execution times

This data would help in:

  • Validating the effectiveness of the batch size reduction
  • Identifying potential bottlenecks
  • Fine-tuning the batch size based on real-world usage
web/core/local-db/utils/load-workspace.ts (1)

123-144: Consider optimizing the data loading strategy.

The current implementation loads all data into memory before processing and processes each data type sequentially. This could be optimized for better memory usage and performance.

Consider these improvements:

  1. Stream data in chunks instead of loading everything into memory:
async function* streamWorkspaceData(workspaceSlug: string) {
  yield { type: 'labels', data: await getLabels(workspaceSlug) };
  yield { type: 'modules', data: await getModules(workspaceSlug) };
  // ... etc
}
  1. Process data types concurrently with controlled concurrency:
const concurrency = 2; // Process 2 data types at a time
const chunks = streamWorkspaceData(workspaceSlug);
for await (const chunk of chunks) {
  await withTransaction(() => 
    batchInserts(chunk.data, chunk.type, schemas[chunk.type])
  );
}
  1. Add progress tracking for better observability:
const total = await countWorkspaceData(workspaceSlug);
let processed = 0;
// ... during processing
processed += chunk.data.length;
log(`Progress: ${processed}/${total} (${(processed/total*100).toFixed(1)}%)`);

Would you like me to help implement any of these improvements?

web/core/local-db/storage.sqlite.ts (3)

24-24: LGTM! Consider monitoring performance impact.

The reduction in batch size from 500 to 50 aligns with the PR objective of making SQL transactions smaller. This should help reduce memory pressure and improve concurrency. However, since this is a significant reduction, it would be valuable to monitor:

  • Transaction completion times
  • Database connection pool usage
  • Overall system performance

Line range hint 401-407: Consider enhancing error handling.

The fallback mechanism is well implemented, but consider adding error handling for scenarios where:

  1. The local DB query fails
  2. The server call fails
 getSubIssues = async (workspaceSlug: string, projectId: string, issueId: string) => {
+  try {
     const workspace_synced_at = await this.getOption("workspace_synced_at");
     if (!workspace_synced_at) {
       const issueService = new IssueService();
       return await issueService.subIssues(workspaceSlug, projectId, issueId);
     }
     return await getSubIssuesWithDistribution(issueId);
+  } catch (error) {
+    console.error("Failed to get sub-issues:", error);
+    // Fallback to server as last resort
+    const issueService = new IssueService();
+    return await issueService.subIssues(workspaceSlug, projectId, issueId);
+  }
 };

Line range hint 24-407: Consider adding performance monitoring.

To validate the impact of these changes, especially the reduced batch size, consider implementing monitoring for:

  1. Transaction timing metrics
  2. Memory usage patterns
  3. Server fallback frequency
  4. Error rates

This will help in fine-tuning these values in production.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b72d180 and 837320d.

📒 Files selected for processing (5)
  • web/core/local-db/storage.sqlite.ts (2 hunks)
  • web/core/local-db/utils/load-issues.ts (2 hunks)
  • web/core/local-db/utils/load-workspace.ts (1 hunks)
  • web/core/services/issue/issue.service.ts (2 hunks)
  • web/helpers/issue.helper.ts (2 hunks)
🔇 Additional comments (7)
web/core/local-db/utils/load-issues.ts (1)

18-18: LGTM! Batch size reduction aligns with optimization goals.

The reduction in batch size from 100 to 50 should help reduce transaction lock times and improve concurrency.

Let's verify if this batch size is consistently applied across the codebase:

✅ Verification successful

Different batch sizes are appropriate for different operations

The batch size of 50 for addIssuesBulk and 500 for batchInserts are justified because:

  • addIssuesBulk handles issues which likely contain more data and complex relationships
  • batchInserts is used for simpler entities (labels, modules, states) that are less resource-intensive
  • Each function uses transactions appropriately for their use case
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other batch size configurations that might need alignment
rg -g '*.{ts,js}' 'batchSize.*=.*[0-9]+' --no-heading

Length of output: 300


Script:

#!/bin/bash
# Let's check the usage context of batchInserts in load-workspace.ts
rg -A 10 "batchInserts" web/core/local-db/utils/load-workspace.ts

Length of output: 1336

web/core/local-db/utils/load-workspace.ts (1)

123-144: Changes successfully achieve the PR objective.

The implementation effectively makes SQL transactions smaller by:

  • Splitting bulk inserts into separate transactions per data type
  • Isolating different data categories (labels, modules, etc.)
  • Reducing the scope of each transaction

This aligns perfectly with the PR objective to "Make SQL transactions smaller" and should help reduce database lock contention.

web/helpers/issue.helper.ts (2)

2-2: LGTM!

The isEmpty import from lodash is appropriately placed and necessary for the new utility function.


313-325: Verify integration with transaction handling system.

The function helps determine when to use local DB vs server, which is crucial for the PR's objective of optimizing SQL transactions. However, we should verify its integration with the transaction handling system.

✅ Verification successful

Let's gather more specific information about how this function is integrated with transaction handling.


Let's check one more aspect to understand the complete flow of the local DB integration.


Function is properly integrated with transaction handling system

The implementation is correctly integrated with the transaction system:

  • The function getIssuesShouldFallbackToServer is used in IssueService to determine whether to use local DB or server
  • When local DB is used, proper transaction handling is implemented in addIssuesBulk with BEGIN/COMMIT blocks
  • The function helps optimize SQL transactions by:
    • Preventing complex queries (with expand/mentions) from hitting local DB
    • Directing them to server instead, which aligns with the PR's goal of "Make SQL transactions smaller"
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how this function is used in transaction-related code

# Look for files that import and use this function
rg -l "getIssuesShouldFallbackToServer" 

# Look for transaction-related code that might need to use this function
rg -l "transaction|batch" --type ts

Length of output: 1059


Script:

#!/bin/bash
# Check the actual usage of getIssuesShouldFallbackToServer in issue.service.ts
rg -A 10 "getIssuesShouldFallbackToServer" web/core/services/issue/issue.service.ts

# Check transaction handling in load-issues.ts since it's likely the main integration point
rg -A 10 "transaction" web/core/local-db/utils/load-issues.ts

# Look for the connection between these systems
rg -B 5 -A 10 "IssueService" web/core/local-db/utils/load-issues.ts

Length of output: 2248


Script:

#!/bin/bash
# Check the persistence implementation to understand the transaction handling
rg -B 5 -A 10 "getIssues" web/core/local-db/storage.sqlite.ts

# Look for the actual SQL transaction implementation
rg -B 5 -A 10 "BEGIN" web/core/local-db/worker/db.ts

# Check if there are any other relevant transaction handlers
rg -B 5 -A 10 "addIssuesBulk" web/core/local-db/utils/load-issues.ts

Length of output: 3798

web/core/services/issue/issue.service.ts (2)

13-13: LGTM!

The import statement follows the project's conventions and is properly organized with other helper imports.


Line range hint 70-74: Verify the fallback logic implementation

The changes look good and align with the PR objectives to optimize SQL transactions. The control flow is cleaner with the extracted helper function.

Let's verify the implementation of the fallback logic:

✅ Verification successful

Fallback logic implementation is correct and well-structured

The helper function getIssuesShouldFallbackToServer correctly implements the fallback logic with clear conditions:

  • Falls back to server when there's an expand query without grouping
  • Falls back to server when mentions are present
  • Uses local persistence for all other cases

The implementation aligns with the service usage and maintains clean separation of concerns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of getIssuesShouldFallbackToServer helper

# Check the helper function implementation
echo "Checking helper function implementation..."
ast-grep --pattern 'export function getIssuesShouldFallbackToServer($_) {
  $$$
}'

# Check for any direct usage of expand or group_by checks that might have been missed
echo "Checking for any remaining direct checks..."
rg -l 'expand.*group_by' --type ts

Length of output: 382


Script:

#!/bin/bash
# Let's check the actual implementation in the helper file
echo "Checking helper implementation in issue.helper.ts..."
rg -A 10 "getIssuesShouldFallbackToServer" web/helpers/issue.helper.ts

# Let's also check how it's used in the service
echo "Checking usage in issue.service.ts..."
rg -A 10 "getIssuesShouldFallbackToServer" web/core/services/issue/issue.service.ts

Length of output: 1593

web/core/local-db/storage.sqlite.ts (1)

385-388: LGTM! Improved robustness with better guards.

The additional checks enhance the method's reliability by:

  1. Ensuring the local DB is both enabled and ready before proceeding
  2. Using a more explicit array check

web/core/local-db/utils/load-issues.ts Show resolved Hide resolved
web/core/local-db/utils/load-workspace.ts Show resolved Hide resolved
Comment on lines +313 to +325
/**
* This is to check if the issues list api should fall back to server or use local db
* @param queries
* @returns
*/
export const getIssuesShouldFallbackToServer = (queries: any) => {
// If there is expand query and is not grouped then fallback to server
if (!isEmpty(queries.expand as string) && !queries.group_by) return true;
// If query has mentions then fallback to server
if (!isEmpty(queries.mentions)) return true;

return false;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety and documentation of the fallback function.

While the function implements the required fallback logic, there are several improvements that could make it more robust:

  1. Replace any type with a proper interface
  2. Enhance JSDoc with parameter details and return value
  3. Add input validation

Consider this implementation:

+interface IssueListQueries {
+  expand?: string;
+  group_by?: string;
+  mentions?: string;
+}

/**
+ * Determines if the issues list API should fall back to server-side processing
+ * @param queries - The query parameters for the issues list
+ * @param queries.expand - Expansion options for the response
+ * @param queries.group_by - Field to group results by
+ * @param queries.mentions - Filter for mentioned users
+ * @returns boolean - True if should use server, false if can use local DB
+ */
-export const getIssuesShouldFallbackToServer = (queries: any) => {
+export const getIssuesShouldFallbackToServer = (queries: IssueListQueries): boolean => {
+  if (!queries) return false;
+
   // If there is expand query and is not grouped then fallback to server
   if (!isEmpty(queries.expand as string) && !queries.group_by) return true;
   // If query has mentions then fallback to server
   if (!isEmpty(queries.mentions)) return true;

   return false;
};
📝 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
/**
* This is to check if the issues list api should fall back to server or use local db
* @param queries
* @returns
*/
export const getIssuesShouldFallbackToServer = (queries: any) => {
// If there is expand query and is not grouped then fallback to server
if (!isEmpty(queries.expand as string) && !queries.group_by) return true;
// If query has mentions then fallback to server
if (!isEmpty(queries.mentions)) return true;
return false;
};
interface IssueListQueries {
expand?: string;
group_by?: string;
mentions?: string;
}
/**
* Determines if the issues list API should fall back to server-side processing
* @param queries - The query parameters for the issues list
* @param queries.expand - Expansion options for the response
* @param queries.group_by - Field to group results by
* @param queries.mentions - Filter for mentioned users
* @returns boolean - True if should use server, false if can use local DB
*/
export const getIssuesShouldFallbackToServer = (queries: IssueListQueries): boolean => {
if (!queries) return false;
// If there is expand query and is not grouped then fallback to server
if (!isEmpty(queries.expand as string) && !queries.group_by) return true;
// If query has mentions then fallback to server
if (!isEmpty(queries.mentions)) return true;
return false;
};

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.

1 participant