Skip to content

Comments

Retry on precondition check fail#910

Merged
elie222 merged 1 commit intomainfrom
fix/precondition-retry
Nov 5, 2025
Merged

Retry on precondition check fail#910
elie222 merged 1 commit intomainfrom
fix/precondition-retry

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Nov 5, 2025

Summary by CodeRabbit

Release Notes

  • Improvements

    • Enhanced Gmail synchronization with improved error detection and recovery. Implemented adaptive retry logic with progressive backoff delays for specific error conditions, improving reliability during sync operations.
  • Chores

    • Version bump (v2.17.37 → v2.17.38)

@vercel
Copy link

vercel bot commented Nov 5, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Nov 5, 2025 9:59am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 2025

Walkthrough

Adds support for failedPrecondition error category to Gmail retry logic, enabling detection of 400-status errors with specific reasons and implementing a shorter exponential backoff strategy (1–10 seconds) for such errors alongside existing rate-limit and server-error retry mechanisms.

Changes

Cohort / File(s) Summary
Gmail Retry Logic
apps/web/utils/gmail/retry.ts, apps/web/utils/gmail/retry.test.ts
Enhanced retry detection and delay calculation to recognize and handle failed precondition errors (400 status with specific reason). isRetryableError now returns isFailedPrecondition flag; calculateRetryDelay accepts new isFailedPrecondition parameter and applies short backoff (1–10s); withGmailRetry propagates the flag through retry logic and logging.
Version Bump
version.txt
Version incremented from v2.17.37 to v2.17.38.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant withGmailRetry
    participant isRetryableError
    participant calculateRetryDelay

    Caller->>withGmailRetry: Execute Gmail operation
    alt Operation fails
        withGmailRetry->>isRetryableError: Check error (status, reason, message)
        isRetryableError-->>withGmailRetry: {isRateLimit, isServerError, isFailedPrecondition}
        alt Retryable
            withGmailRetry->>calculateRetryDelay: Calculate delay (isRateLimit, isServerError, isFailedPrecondition, attempt)
            alt isFailedPrecondition=true
                calculateRetryDelay-->>withGmailRetry: Short backoff (1–10s exponential)
            else isRateLimit=true
                calculateRetryDelay-->>withGmailRetry: Rate-limit backoff
            else isServerError=true
                calculateRetryDelay-->>withGmailRetry: Server-error backoff
            end
            withGmailRetry->>withGmailRetry: Sleep & retry
        else Not retryable
            withGmailRetry-->>Caller: Throw error
        end
    else Success
        withGmailRetry-->>Caller: Return result
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Key areas for attention:
    • Verify isFailedPrecondition detection logic correctly identifies 400 errors with "failedPrecondition" reason/message
    • Confirm new backoff formula (1s → 2s → 4s → 8s → capped at 10s) is appropriate and correctly implemented
    • Validate that all call sites to calculateRetryDelay have been updated with the new parameter in correct position
    • Ensure test coverage adequately exercises the new parameter across all retry scenarios

Possibly related PRs

Poem

🐰 A precondition failed, we hop once more,
With backoff dance (one, two, four…)—short and sure.
From 400 errors, a swift retry we brew,
Capped at ten seconds—renewed! ✨

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Retry on precondition check fail' directly describes the main change: adding retry logic for failed precondition errors in Gmail operations.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/precondition-retry

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (3)
apps/web/utils/gmail/retry.ts (2)

66-68: Update the function comment to include failed preconditions.

The comment states the function determines if an error is retryable for "rate limit or server error", but it now also handles failed preconditions. Update the documentation to reflect this change.

Apply this diff:

 /**
- * Determines if an error is retryable (rate limit or server error)
+ * Determines if an error is retryable (rate limit, server error, or failed precondition)
  */

165-169: Update the function documentation to include failed preconditions.

The comment describes retry handling for rate limits and server errors but doesn't mention failed preconditions, which are now also handled.

Apply this diff:

 /**
  * Retries a Gmail API operation when rate limits or temporary server errors are encountered
- * - Rate limits: 429, 403 with specific reasons
- * - Server errors: 502, 503, 504
+ * - Rate limits: 429, 403 with specific reasons (30s delay)
+ * - Server errors: 502, 503, 504 (exponential backoff: 5s-80s)
+ * - Failed preconditions: 400 with failedPrecondition reason (short backoff: 1s-10s)
  */
apps/web/utils/gmail/retry.test.ts (1)

94-106: Consider adding tests for case-insensitivity and error message pattern matching.

The current test covers the basic case well. To ensure robustness, consider adding tests for:

  1. Case variations of the reason field (e.g., "FailedPrecondition", "FAILEDPRECONDITION")
  2. Detection via error message pattern when the reason field is absent

Example additional tests:

it("should identify failedPrecondition with different casing", () => {
  const errorInfo = {
    status: 400,
    reason: "FailedPrecondition", // Mixed case
    errorMessage: "Error",
  };
  const result = isRetryableError(errorInfo);
  
  expect(result.retryable).toBe(true);
  expect(result.isFailedPrecondition).toBe(true);
});

it("should identify failedPrecondition from error message", () => {
  const errorInfo = {
    status: 400,
    errorMessage: "Precondition check failed for operation",
  };
  const result = isRetryableError(errorInfo);
  
  expect(result.retryable).toBe(true);
  expect(result.isFailedPrecondition).toBe(true);
});
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b352f1 and 7691e3c.

📒 Files selected for processing (3)
  • apps/web/utils/gmail/retry.test.ts (4 hunks)
  • apps/web/utils/gmail/retry.ts (7 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • version.txt
  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • version.txt
  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
apps/web/utils/gmail/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/gmail-api.mdc)

Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

Include security tests in your test suites to verify authentication, authorization, and error handling.

Files:

  • apps/web/utils/gmail/retry.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.

Files:

  • apps/web/utils/gmail/retry.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

**/*.test.{ts,tsx}: Use Vitest (vitest) as the testing framework
Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)
In tests, mock the server-only module with vi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it with vi.mock("@/utils/prisma") and use the mock from @/utils/__mocks__/prisma
Use provided helpers for mocks: import { getEmail, getEmailAccount, getRule } from @/__tests__/helpers
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Clean up mocks between tests (e.g., vi.clearAllMocks() in beforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the Logger

Files:

  • apps/web/utils/gmail/retry.test.ts
🧠 Learnings (4)
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Add retry logic for transient failures using withRetry

Applied to files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Use proper error types and logging for failures

Applied to files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
📚 Learning: 2025-07-18T15:05:34.899Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Applied to files:

  • apps/web/utils/gmail/retry.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Applied to files:

  • apps/web/utils/gmail/retry.ts
  • apps/web/utils/gmail/retry.test.ts
🧬 Code graph analysis (1)
apps/web/utils/gmail/retry.test.ts (1)
apps/web/utils/gmail/retry.ts (2)
  • isRetryableError (69-105)
  • calculateRetryDelay (110-163)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
apps/web/utils/gmail/retry.ts (2)

94-97: LGTM! Detection logic is robust.

The failed precondition detection correctly checks for status 400 with case-insensitive matching on both the reason field and error message pattern, following the same pattern as rate limit and server error detection.


157-160: LGTM! Backoff strategy is appropriate.

The short exponential backoff (1s, 2s, 4s, 8s, capped at 10s) is well-suited for transient precondition failures and is appropriately shorter than the delays for rate limits (30s) and server errors (5s-80s).

apps/web/utils/gmail/retry.test.ts (2)

111-111: LGTM! Test calls correctly updated.

All existing calculateRetryDelay test calls have been properly updated to include the new isFailedPrecondition parameter (set to false), maintaining existing test behavior.

Also applies to: 116-118


162-166: LGTM! Backoff test validates key progression points.

The test correctly validates the exponential backoff progression (1s, 4s, 10s cap) for failed precondition retries, confirming both the exponential growth and the maximum delay cap.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 3 files

@elie222 elie222 merged commit 8803cfd into main Nov 5, 2025
16 checks passed
@elie222 elie222 deleted the fix/precondition-retry branch November 5, 2025 10:06
@coderabbitai coderabbitai bot mentioned this pull request Nov 7, 2025
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