Skip to content

Comments

Minor fixes#1623

Merged
MrgSub merged 1 commit intostagingfrom
07-04-minor_fixes
Jul 4, 2025
Merged

Minor fixes#1623
MrgSub merged 1 commit intostagingfrom
07-04-minor_fixes

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 4, 2025

READ CAREFULLY THEN REMOVE

Remove bullet points that are not relevant.

PLEASE REFRAIN FROM USING AI TO WRITE YOUR CODE AND PR DESCRIPTION. IF YOU DO USE AI TO WRITE YOUR CODE PLEASE PROVIDE A DESCRIPTION AND REVIEW IT CAREFULLY. MAKE SURE YOU UNDERSTAND THE CODE YOU ARE SUBMITTING USING AI.

  • Pull requests that do not follow these guidelines will be closed without review or comment.
  • If you use AI to write your PR description your pr will be close without review or comment.
  • If you are unsure about anything, feel free to ask for clarification.

Description

Please provide a clear description of your changes.


Type of Change

Please delete options that are not relevant.

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature with breaking changes)
  • 📝 Documentation update
  • 🎨 UI/UX improvement
  • 🔒 Security enhancement
  • ⚡ Performance improvement

Areas Affected

Please check all that apply:

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • Authentication/Authorization
  • Data Storage/Management
  • API Endpoints
  • Documentation
  • Testing Infrastructure
  • Development Workflow
  • Deployment/Infrastructure

Testing Done

Describe the tests you've done:

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed
  • Cross-browser testing (if UI changes)
  • Mobile responsiveness verified (if UI changes)

Security Considerations

For changes involving data or authentication:

  • No sensitive data is exposed
  • Authentication checks are in place
  • Input validation is implemented
  • Rate limiting is considered (if applicable)

Checklist

  • I have read the CONTRIBUTING document
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • I have updated the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix/feature works
  • All tests pass locally
  • Any dependent changes are merged and published

Additional Notes

Add any other context about the pull request here.

Screenshots/Recordings

Add screenshots or recordings here if applicable.


By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.

Summary by CodeRabbit

  • Chores

    • Updated workflow names in configuration files to include environment-specific suffixes for better clarity across local, staging, and production environments.
  • Refactor

    • Modified workflow creation logic to allow new workflow instances without checking for existing running instances or including the last page of threads in processing.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 4, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes remove checks that previously prevented the creation of duplicate or concurrent workflow instances by commenting out logic that searched for existing running workflows before creating new ones. Additionally, workflow names in configuration files are updated to include environment-specific suffixes for clarity.

Changes

File(s) Change Summary
apps/server/src/pipelines.ts Commented out logic checking for existing running workflow instances and fetching the last page of threads. Control flow now always creates new workflow instances.
apps/server/wrangler.jsonc Updated workflow names in all environments to include environment-specific suffixes (e.g., -staging, -prod).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MainWorkflow
    participant ZeroWorkflow
    participant ThreadWorkflow

    Client->>MainWorkflow: Request to create workflow
    MainWorkflow->>ZeroWorkflow: Create ZERO_WORKFLOW (no existence check)
    ZeroWorkflow->>ThreadWorkflow: Create THREAD_WORKFLOW (no existence check)
    Note over MainWorkflow,ThreadWorkflow: No prior check for existing running instances
Loading

Possibly related PRs

  • Avoiding Duplicates #1356: The main PR reverses the deduplication logic introduced in the retrieved PR by commenting out the checks for existing running workflow instances before creating new ones, directly undoing the core functionality added in the retrieved PR.

Suggested reviewers

  • nizzyabi

Poem

In the warren of code, workflows hop anew,
No more checks for twins—just hop right through!
With names now tailored for each habitat,
The pipelines leap—imagine that!
🐇✨

Hop, skip, deploy—no duplicate fear,
The rabbits of staging and prod now cheer!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 007d845 and 4077ef9.

📒 Files selected for processing (2)
  • apps/server/src/pipelines.ts (4 hunks)
  • apps/server/wrangler.jsonc (3 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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
Collaborator Author

MrgSub commented Jul 4, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@MrgSub MrgSub marked this pull request as ready for review July 4, 2025 17:00
Copy link
Collaborator Author

MrgSub commented Jul 4, 2025

Merge activity

  • Jul 4, 5:00 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 4, 5:00 PM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit 5e99498 into staging Jul 4, 2025
5 of 6 checks passed
@MrgSub MrgSub deleted the 07-04-minor_fixes branch July 4, 2025 17:00
Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

Modified email processing pipeline configuration and workflow management, focusing on environment separation and concurrent processing capabilities.

  • Updated workflow naming in apps/server/wrangler.jsonc by adding environment suffixes ('-staging', '-prod') to prevent naming collisions
  • Removed workflow instance checks in apps/server/src/pipelines.ts for MainWorkflow, enabling parallel processing
  • Commented out last page fetching logic in ZeroWorkflow
  • Disabled thread workflow instance verification, potentially allowing concurrent thread processing

2 files reviewed, 2 comments
Edit PR Review Bot Settings | Greptile

Comment on lines 106 to +113
log('[MAIN_WORKFLOW] Creating workflow instance with current history');
const existingInstance = await env.ZERO_WORKFLOW.get(
`${connectionId}__${historyId}`,
).catch(() => null);
if (existingInstance && (await existingInstance.status()).status === 'running') {
log('[MAIN_WORKFLOW] History already processing:', existingInstance.id);
return;
}
// const existingInstance = await env.ZERO_WORKFLOW.get(
// `${connectionId}__${historyId}`,
// ).catch(() => null);
// if (existingInstance && (await existingInstance.status()).status === 'running') {
// log('[MAIN_WORKFLOW] History already processing:', existingInstance.id);
// return;
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Removing the duplicate workflow check could lead to multiple concurrent workflows processing the same history. Make sure this is the intended behavior and that concurrent processing is handled properly.

Comment on lines +285 to +297
// const lastPage = await step.do(
// `[ZERO_WORKFLOW] Get last page ${connectionId}`,
// async () => {
// log('[ZERO_WORKFLOW] Getting last page of threads');
// const lastThreads = await driver.list({
// folder: 'inbox',
// query: 'NOT is:spam',
// maxResults: 10,
// });
// log('[ZERO_WORKFLOW] Found threads in last page:', lastThreads.threads.length);
// return lastThreads.threads.map((thread) => thread.id);
// },
// );
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Removing last page processing means only history-based updates will be processed. Verify this won't miss any critical updates that might not trigger history events.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bug: Thread Workflow Duplicate Processing

The THREAD_WORKFLOW duplicate prevention logic, including the existing instance check and deterministic ID assignment (${threadId}__${connectionId}), has been commented out. This allows multiple workflow instances to be created for the same thread and connection, resulting in duplicate processing, race conditions, resource waste, and potential data corruption.

apps/server/src/pipelines.ts#L337-L351

});
// const existingInstance = await env.THREAD_WORKFLOW.get(
// `${threadId.toString()}__${connectionId.toString()}`,
// ).catch(() => null);
// if (
// existingInstance &&
// (await existingInstance.status()).status === 'running'
// ) {
// log('[ZERO_WORKFLOW] Thread already processing:', isProcessing, threadId);
// await env.gmail_processing_threads.delete(threadId.toString());
// return;
// }
const instance = await env.THREAD_WORKFLOW.create({
// id: `${threadId.toString()}__${connectionId.toString()}`,
params: { connectionId, threadId, providerId: foundConnection.providerId },

Fix in CursorFix in Web


Bug: Workflow Duplication Causes Resource Waste

The duplicate workflow prevention logic for ZERO_WORKFLOW and THREAD_WORKFLOW instances has been commented out. This includes the check for existing running instances and the use of deterministic IDs for workflow creation. As a result, multiple workflow instances can be created for the same history or thread, leading to duplicate processing, resource waste, race conditions, and potential data inconsistencies.

apps/server/src/pipelines.ts#L106-L350

log('[MAIN_WORKFLOW] Creating workflow instance with current history');
// const existingInstance = await env.ZERO_WORKFLOW.get(
// `${connectionId}__${historyId}`,
// ).catch(() => null);
// if (existingInstance && (await existingInstance.status()).status === 'running') {
// log('[MAIN_WORKFLOW] History already processing:', existingInstance.id);
// return;
// }
const instance = await env.ZERO_WORKFLOW.create({
// id: `${connectionId}__${historyId}`,
params: {
connectionId,
historyId: historyId,
nextHistoryId: historyId,
},
});
log('[MAIN_WORKFLOW] Created instance:', {
id: instance.id,
status: await instance.status(),
});
}
},
);
} else {
log('[MAIN_WORKFLOW] Unsupported provider:', providerId);
throw new Error(`Unsupported provider: ${providerId}`);
}
log('[MAIN_WORKFLOW] Workflow completed successfully');
} catch (error) {
log('[MAIN_WORKFLOW] Error in workflow:', error);
log('[MAIN_WORKFLOW] Error details:', {
providerId: event.payload.providerId,
historyId: event.payload.historyId,
subscriptionName: event.payload.subscriptionName,
errorMessage: error instanceof Error ? error.message : String(error),
errorStack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
}
}
export class ZeroWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(
event: Readonly<WorkflowEvent<Params<'connectionId' | 'historyId' | 'nextHistoryId'>>>,
step: WorkflowStep,
) {
log('[ZERO_WORKFLOW] Starting workflow with payload:', event.payload);
try {
const { connectionId, historyId, nextHistoryId } = event.payload;
const historyProcessingKey = `history_${connectionId}__${historyId}`;
const isProcessing = await env.gmail_processing_threads.get(historyProcessingKey);
if (isProcessing === 'true') {
return log('[ZERO_WORKFLOW] History already being processed:', {
connectionId,
historyId,
processingStatus: isProcessing,
});
}
await env.gmail_processing_threads.put(historyProcessingKey, 'true', { expirationTtl: 3600 });
log('[ZERO_WORKFLOW] Set processing flag for history:', historyProcessingKey);
const { db, conn } = createDb(env.HYPERDRIVE.connectionString);
const foundConnection = await step.do(
`[ZERO_WORKFLOW] Find Connection ${connectionId}`,
async () => {
log('[ZERO_WORKFLOW] Finding connection:', connectionId);
const [foundConnection] = await db
.select()
.from(connection)
.where(eq(connection.id, connectionId.toString()));
if (!foundConnection) throw new Error(`Connection not found ${connectionId}`);
if (!foundConnection.accessToken || !foundConnection.refreshToken)
throw new Error(`Connection is not authorized ${connectionId}`);
log('[ZERO_WORKFLOW] Found connection:', foundConnection.id);
return foundConnection;
},
);
const driver = connectionToDriver(foundConnection);
if (foundConnection.providerId === EProviders.google) {
log('[ZERO_WORKFLOW] Processing Google provider workflow');
const history = await step.do(
`[ZERO_WORKFLOW] Get Gmail History ${foundConnection.id} ${historyId}`,
async () => {
try {
log('[ZERO_WORKFLOW] Getting Gmail history with ID:', historyId);
const { history } = await driver.listHistory<gmail_v1.Schema$History>(
historyId.toString(),
);
if (!history.length) throw new Error(`No history found ${historyId} ${connectionId}`);
log('[ZERO_WORKFLOW] Found history entries:', history.length);
return history;
} catch (error) {
log('[ZERO_WORKFLOW] Failed to get Gmail history:', {
historyId,
connectionId: foundConnection.id,
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
},
);
await step.do(
`[ZERO_WORKFLOW] Update next history id ${foundConnection.id} ${nextHistoryId}`,
async () => {
log('[ZERO_WORKFLOW] Updating next history ID:', nextHistoryId);
await env.gmail_history_id.put(connectionId.toString(), nextHistoryId.toString());
},
);
const threadsAdded = await step.do(
`[ZERO_WORKFLOW] Get new Threads ${connectionId}`,
async () => {
log('[ZERO_WORKFLOW] Finding threads with changed messages');
const historiesWithChangedMessages = history.filter(
(history) => history.messagesAdded?.length,
);
const threadsAdded = [
...new Set(
historiesWithChangedMessages.flatMap((history) =>
history
.messagesAdded!.map((message) => message.message?.threadId)
.filter((threadId): threadId is string => threadId !== undefined),
),
),
];
log('[ZERO_WORKFLOW] Found new threads:', threadsAdded.length);
return threadsAdded;
},
);
const threadsAddLabels = await step.do(
`[ZERO_WORKFLOW] Get Threads with new labels ${connectionId}`,
async () => {
log('[ZERO_WORKFLOW] Finding threads with new labels');
const historiesWithNewLabels = history.filter((history) => history.labelsAdded?.length);
const threadsWithLabelsAdded = [
...new Set(
historiesWithNewLabels.flatMap((history) =>
history
.labelsAdded!.filter((label) => label.message?.threadId)
.map((label) => label.message!.threadId)
.filter((threadId): threadId is string => threadId !== undefined),
),
),
];
log('[ZERO_WORKFLOW] Found threads with new labels:', threadsWithLabelsAdded.length);
return threadsWithLabelsAdded;
},
);
const threadsRemoveLabels = await step.do(
`[ZERO_WORKFLOW] Get Threads with removed labels ${connectionId}`,
async () => {
log('[ZERO_WORKFLOW] Finding threads with removed labels');
const historiesWithRemovedLabels = history.filter(
(history) => history.labelsRemoved?.length,
);
const threadsWithLabelsRemoved = [
...new Set(
historiesWithRemovedLabels.flatMap((history) =>
history
.labelsRemoved!.filter((label) => label.message?.threadId)
.map((label) => label.message!.threadId)
.filter((threadId): threadId is string => threadId !== undefined),
),
),
];
log(
'[ZERO_WORKFLOW] Found threads with removed labels:',
threadsWithLabelsRemoved.length,
);
return threadsWithLabelsRemoved;
},
);
// const lastPage = await step.do(
// `[ZERO_WORKFLOW] Get last page ${connectionId}`,
// async () => {
// log('[ZERO_WORKFLOW] Getting last page of threads');
// const lastThreads = await driver.list({
// folder: 'inbox',
// query: 'NOT is:spam',
// maxResults: 10,
// });
// log('[ZERO_WORKFLOW] Found threads in last page:', lastThreads.threads.length);
// return lastThreads.threads.map((thread) => thread.id);
// },
// );
const threadsToProcess = await step.do(
`[ZERO_WORKFLOW] Get threads to process ${connectionId}`,
async () => {
log('[ZERO_WORKFLOW] Combining threads to process');
const threadsToProcess = [
...new Set([
...threadsAdded,
// ...lastPage,
...threadsAddLabels,
...threadsRemoveLabels,
]),
];
log('[ZERO_WORKFLOW] Total threads to process:', threadsToProcess.length);
return threadsToProcess;
},
);
await step.do(
`[ZERO_WORKFLOW] Send Thread Workflow Instances ${connectionId}`,
async () => {
const maxConcurrentThreads = 5;
const delayBetweenBatches = 2000;
for (let i = 0; i < threadsToProcess.length; i += maxConcurrentThreads) {
const batch = threadsToProcess.slice(i, i + maxConcurrentThreads);
await Promise.all(
batch.map(async (threadId) => {
try {
const isProcessing = await env.gmail_processing_threads.get(
threadId.toString(),
);
if (isProcessing) {
log('[ZERO_WORKFLOW] Thread already processing:', isProcessing, threadId);
return;
}
await env.gmail_processing_threads.put(threadId.toString(), 'true', {
expirationTtl: 1800,
});
// const existingInstance = await env.THREAD_WORKFLOW.get(
// `${threadId.toString()}__${connectionId.toString()}`,
// ).catch(() => null);
// if (
// existingInstance &&
// (await existingInstance.status()).status === 'running'
// ) {
// log('[ZERO_WORKFLOW] Thread already processing:', isProcessing, threadId);
// await env.gmail_processing_threads.delete(threadId.toString());
// return;
// }
const instance = await env.THREAD_WORKFLOW.create({
// id: `${threadId.toString()}__${connectionId.toString()}`,

Fix in CursorFix in Web


Bug: Recent Emails Processing Issue

The lastPage processing logic was commented out, which removes the processing of the most recent 10 inbox threads. As a result, recent threads not captured by Gmail history changes (e.g., threadsAdded, threadsAddLabels, threadsRemoveLabels) will not be processed. This leads to a functional regression where new or recently updated emails may be missed.

apps/server/src/pipelines.ts#L284-L306

// const lastPage = await step.do(
// `[ZERO_WORKFLOW] Get last page ${connectionId}`,
// async () => {
// log('[ZERO_WORKFLOW] Getting last page of threads');
// const lastThreads = await driver.list({
// folder: 'inbox',
// query: 'NOT is:spam',
// maxResults: 10,
// });
// log('[ZERO_WORKFLOW] Found threads in last page:', lastThreads.threads.length);
// return lastThreads.threads.map((thread) => thread.id);
// },
// );
const threadsToProcess = await step.do(
`[ZERO_WORKFLOW] Get threads to process ${connectionId}`,
async () => {
log('[ZERO_WORKFLOW] Combining threads to process');
const threadsToProcess = [
...new Set([
...threadsAdded,
// ...lastPage,

Fix in CursorFix in Web


BugBot free trial expires on July 22, 2025
You have used $0.00 of your $50.00 spend limit so far. Manage your spend limit in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

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