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

Use a separate queue for indexing embeddings and summaries, to prevent blocking the main SB indexing thread #61

Merged
merged 1 commit into from
Aug 21, 2024

Conversation

justyns
Copy link
Owner

@justyns justyns commented Aug 21, 2024

related: silverbulletmd/silverbullet#1021

Summary by CodeRabbit

  • New Features

    • Introduced queuing mechanisms for embedding and summary indexing, enhancing performance.
    • Simplified function signatures for indexing embeddings and summaries.
  • Bug Fixes

    • Improved logging for the indexing process, providing clear insights into execution duration.

Copy link
Contributor

coderabbitai bot commented Aug 21, 2024

Walkthrough

Walkthrough

The changes to the src/embeddings.ts file focus on enhancing the functionality and usability of embedding and summarization processes. Key modifications include refactoring function parameters for simplicity, introducing queuing mechanisms for embedding and summary tasks, and improving logging for better observability during execution. These updates streamline operations and ensure that indexing processes remain efficient and organized.

Changes

File Change Summary
src/embeddings.ts Refactored indexEmbeddings, indexSummary, and queueEmbeddingGeneration functions to accept a single string parameter, page. Added processEmbeddingsQueue and processSummaryQueue for handling queued tasks. Updated logging in indexSummary to include processing duration. Imports for mq and MQMessage added for queuing functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Queue
    participant EmbeddingService
    participant SummaryService

    User->>Queue: Queue page indexing event
    Queue->>EmbeddingService: Process embedding generation
    EmbeddingService->>Queue: Generate embeddings
    Queue->>SummaryService: Process summary generation
    SummaryService->>Queue: Generate summary
    Queue->>User: Respond with indexing status
Loading

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 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, codebase verification and nitpick comments (5)
src/embeddings.ts (5)

Line range hint 73-84: Add error handling for embedding generation.

Consider adding error handling for the embedding generation process to ensure robustness.

Use this diff to add error handling:

    try {
      const embedding = await currentEmbeddingProvider.generateEmbeddings({
        text: paragraphText,
      });
    } catch (error) {
      log("error", `Failed to generate embeddings for paragraph: ${error}`);
      continue;
    }

Line range hint 150-161: Add error handling for summary generation.

Consider adding error handling for the summary generation process to ensure robustness.

Use this diff to add error handling:

    try {
      summary = await summaryProvider.singleMessageChat(
        "Contents of " + page + ":\n" + pageText + "\n\n" + summaryPrompt,
      );
    } catch (error) {
      log("error", `Failed to generate summary for page: ${error}`);
      return;
    }

Consider adding error handling for space.readPage in indexEmbeddings.

While the function checks for tree.children after parsing, it lacks explicit error handling for space.readPage. Adding error handling would improve robustness against potential issues like file not found or read permissions.

  • src/embeddings.ts: Add error handling for space.readPage.
Analysis chain

Line range hint 73-84: Verify page reading and parsing logic.

Ensure that the logic for reading and parsing the page content is correctly implemented and handles potential errors.

Run the following script to verify the usage of space.readPage and markdown.parseMarkdown:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of space.readPage and markdown.parseMarkdown.

# Test: Search for the usage of space.readPage and markdown.parseMarkdown. Expect: Correct usage and error handling.
rg --type typescript -A 5 $'space.readPage'
rg --type typescript -A 5 $'markdown.parseMarkdown'

Length of output: 163


Script:

#!/bin/bash
# Description: Verify the usage of space.readPage and markdown.parseMarkdown with corrected file type.

# Test: Search for the usage of space.readPage and markdown.parseMarkdown. Expect: Correct usage and error handling.
rg --type ts -A 5 $'space.readPage'
rg --type ts -A 5 $'markdown.parseMarkdown'

Length of output: 4411


223-243: Consider adding error handling for mq.send operations.

The mq.send calls in the queueEmbeddingGeneration function lack error handling, which could lead to unhandled exceptions if the message queue fails. It's recommended to wrap these operations in try-catch blocks or implement other error-handling mechanisms to ensure robustness.

  • src/embeddings.ts: Lines where mq.send is used.
Analysis chain

Verify queuing logic.

Ensure that the logic for queuing embedding and summary indexing tasks is correctly implemented and handles potential errors.

Run the following script to verify the usage of mq.send:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of mq.send for queuing operations.

# Test: Search for the usage of mq.send. Expect: Correct usage and error handling.
rg --type typescript -A 5 $'mq.send'

Length of output: 70


Script:

#!/bin/bash
# Description: Verify the usage of mq.send for queuing operations.

# Test: Search for the usage of mq.send. Expect: Correct usage and error handling.
rg --type ts -A 5 $'mq.send'

Length of output: 440


Consider Adding Error Handling for space.readPage and markdown.parseMarkdown

While there is a check for tree.children to handle parsing results, explicit error handling for the space.readPage and markdown.parseMarkdown calls is missing. Consider wrapping these calls in try-catch blocks to handle potential exceptions gracefully.

  • In src/embeddings.ts, lines where space.readPage and markdown.parseMarkdown are used.
Analysis chain

Line range hint 150-161: Verify page reading and parsing logic.

Ensure that the logic for reading and parsing the page content is correctly implemented and handles potential errors.

Run the following script to verify the usage of space.readPage and markdown.parseMarkdown:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of space.readPage and markdown.parseMarkdown.

# Test: Search for the usage of space.readPage and markdown.parseMarkdown. Expect: Correct usage and error handling.
rg --type typescript -A 5 $'space.readPage'
rg --type typescript -A 5 $'markdown.parseMarkdown'

Length of output: 163


Script:

#!/bin/bash
# Description: Verify the usage of space.readPage and markdown.parseMarkdown.

# Test: Search for the usage of space.readPage and markdown.parseMarkdown in TypeScript files.
rg 'space.readPage' --glob '*.ts' -A 5
rg 'markdown.parseMarkdown' --glob '*.ts' -A 5

Length of output: 4419

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 68586ae and 19eee19.

Files ignored due to path filters (1)
  • silverbullet-ai.plug.yaml is excluded by none and included by none
Files selected for processing (1)
  • src/embeddings.ts (6 hunks)
Additional context used
Path-based instructions (1)
src/embeddings.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

Additional comments not posted (2)
src/embeddings.ts (2)

245-254: Verify queue statistics retrieval.

Ensure that the queue statistics are correctly retrieved and logged.

Run the following script to verify the usage of mq.getQueueStats:

Verification successful

Queue Statistics Retrieval Verified

The mq.getQueueStats function is used correctly in the processEmbeddingsQueue function. The queue statistics are retrieved and logged as expected.

  • Location: src/embeddings.ts
    • const queueStats = await mq.getQueueStats("aiEmbeddingsQueue");
    • console.log(AI: Embeddings queue stats: ${JSON.stringify(queueStats)});

The code correctly retrieves and logs the queue statistics. No issues found with this implementation.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of mq.getQueueStats for queue statistics retrieval.

# Test: Search for the usage of mq.getQueueStats. Expect: Correct usage and logging.
rg --type typescript -A 5 $'mq.getQueueStats'

Length of output: 79


Script:

#!/bin/bash
# Description: Verify the usage of mq.getQueueStats for queue statistics retrieval.

# Test: Search for the usage of mq.getQueueStats. Expect: Correct usage and logging.
rg -A 5 'mq.getQueueStats'

Length of output: 732


256-265: Verify queue statistics retrieval.

Ensure that the queue statistics are correctly retrieved and logged.

Run the following script to verify the usage of mq.getQueueStats:

Verification successful

Queue statistics retrieval is correctly implemented.

The mq.getQueueStats function is correctly used to retrieve and log the statistics for the "aiSummaryQueue" in src/embeddings.ts. No issues were found with its implementation.

  • src/embeddings.ts: Correct retrieval and logging of queue statistics for "aiSummaryQueue".
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of mq.getQueueStats for queue statistics retrieval.

# Test: Search for the usage of mq.getQueueStats. Expect: Correct usage and logging.
rg --type typescript -A 5 $'mq.getQueueStats'

Length of output: 79


Script:

#!/bin/bash
# Description: Verify the usage of mq.getQueueStats for queue statistics retrieval.

# Test: Search for the usage of mq.getQueueStats. Expect: Correct usage and logging.
rg --glob '*.ts' -A 5 'mq.getQueueStats'

Length of output: 746

Comment on lines +223 to +243
export async function queueEmbeddingGeneration(
{ name: page, tree }: IndexTreeEvent,
) {
await initIfNeeded();

if (!canIndexPage(page)) {
return;
}

if (!tree.children) {
return;
}

if (await shouldIndexEmbeddings()) {
await mq.send("aiEmbeddingsQueue", page);
}

if (await shouldIndexSummaries()) {
await mq.send("aiSummaryQueue", page);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for queuing operations.

Consider adding error handling for the queuing operations to ensure robustness.

Use this diff to add error handling:

    try {
      await mq.send("aiEmbeddingsQueue", page);
    } catch (error) {
      log("error", `Failed to queue embedding task for page: ${error}`);
    }

    try {
      await mq.send("aiSummaryQueue", page);
    } catch (error) {
      log("error", `Failed to queue summary task for page: ${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
export async function queueEmbeddingGeneration(
{ name: page, tree }: IndexTreeEvent,
) {
await initIfNeeded();
if (!canIndexPage(page)) {
return;
}
if (!tree.children) {
return;
}
if (await shouldIndexEmbeddings()) {
await mq.send("aiEmbeddingsQueue", page);
}
if (await shouldIndexSummaries()) {
await mq.send("aiSummaryQueue", page);
}
}
export async function queueEmbeddingGeneration(
{ name: page, tree }: IndexTreeEvent,
) {
await initIfNeeded();
if (!canIndexPage(page)) {
return;
}
if (!tree.children) {
return;
}
if (await shouldIndexEmbeddings()) {
try {
await mq.send("aiEmbeddingsQueue", page);
} catch (error) {
log("error", `Failed to queue embedding task for page: ${error}`);
}
}
if (await shouldIndexSummaries()) {
try {
await mq.send("aiSummaryQueue", page);
} catch (error) {
log("error", `Failed to queue summary task for page: ${error}`);
}
}
}

Comment on lines +256 to +265
export async function processSummaryQueue(messages: MQMessage[]) {
await initIfNeeded();
for (const message of messages) {
const pageName: string = message.body;
console.log(`AI: Generating and indexing summary for ${pageName}`);
await indexSummary(pageName);
}
const queueStats = await mq.getQueueStats("aiSummaryQueue");
console.log(`AI: Summary queue stats: ${JSON.stringify(queueStats)}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for summary generation.

Consider adding error handling for the summary generation process to ensure robustness.

Use this diff to add error handling:

    try {
      await indexSummary(pageName);
    } catch (error) {
      console.error(`Failed to index summary for ${pageName}: ${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
export async function processSummaryQueue(messages: MQMessage[]) {
await initIfNeeded();
for (const message of messages) {
const pageName: string = message.body;
console.log(`AI: Generating and indexing summary for ${pageName}`);
await indexSummary(pageName);
}
const queueStats = await mq.getQueueStats("aiSummaryQueue");
console.log(`AI: Summary queue stats: ${JSON.stringify(queueStats)}`);
}
export async function processSummaryQueue(messages: MQMessage[]) {
await initIfNeeded();
for (const message of messages) {
const pageName: string = message.body;
console.log(`AI: Generating and indexing summary for ${pageName}`);
try {
await indexSummary(pageName);
} catch (error) {
console.error(`Failed to index summary for ${pageName}: ${error}`);
}
}
const queueStats = await mq.getQueueStats("aiSummaryQueue");
console.log(`AI: Summary queue stats: ${JSON.stringify(queueStats)}`);
}

Comment on lines +245 to +254
export async function processEmbeddingsQueue(messages: MQMessage[]) {
await initIfNeeded();
for (const message of messages) {
const pageName: string = message.body;
console.log(`AI: Generating and indexing embeddings for file ${pageName}`);
await indexEmbeddings(pageName);
}
const queueStats = await mq.getQueueStats("aiEmbeddingsQueue");
console.log(`AI: Embeddings queue stats: ${JSON.stringify(queueStats)}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for embedding generation.

Consider adding error handling for the embedding generation process to ensure robustness.

Use this diff to add error handling:

    try {
      await indexEmbeddings(pageName);
    } catch (error) {
      console.error(`Failed to index embeddings for file ${pageName}: ${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
export async function processEmbeddingsQueue(messages: MQMessage[]) {
await initIfNeeded();
for (const message of messages) {
const pageName: string = message.body;
console.log(`AI: Generating and indexing embeddings for file ${pageName}`);
await indexEmbeddings(pageName);
}
const queueStats = await mq.getQueueStats("aiEmbeddingsQueue");
console.log(`AI: Embeddings queue stats: ${JSON.stringify(queueStats)}`);
}
export async function processEmbeddingsQueue(messages: MQMessage[]) {
await initIfNeeded();
for (const message of messages) {
const pageName: string = message.body;
console.log(`AI: Generating and indexing embeddings for file ${pageName}`);
try {
await indexEmbeddings(pageName);
} catch (error) {
console.error(`Failed to index embeddings for file ${pageName}: ${error}`);
}
}
const queueStats = await mq.getQueueStats("aiEmbeddingsQueue");
console.log(`AI: Embeddings queue stats: ${JSON.stringify(queueStats)}`);
}

@justyns justyns merged commit 1c196af into main Aug 21, 2024
3 checks passed
@justyns justyns deleted the index-queue branch August 21, 2024 06:43
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