Skip to content

prisma: add retry logic for P2028 transient errors#1256

Merged
elie222 merged 2 commits intomainfrom
fix/p2028-retry-logic
Jan 11, 2026
Merged

prisma: add retry logic for P2028 transient errors#1256
elie222 merged 2 commits intomainfrom
fix/p2028-retry-logic

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jan 11, 2026

User description

Adds a utility to retry Prisma operations that fail with P2028 ("Transaction already closed") errors, which occur in E2E tests due to Neon connection pooling.

  • Created withPrismaRetry utility with exponential backoff
  • Wrapped failing updateMany, create, and $transaction calls in retry logic
  • Targets transient errors causing ~7% failure rate in E2E tests

Summary by CodeRabbit

  • Improvements
    • Enhanced resilience of database operations for rule execution, draft tracking, conversation status management, and label operations through improved error handling mechanisms.

✏️ Tip: You can customize this high-level summary in your review settings.


Generated description

Below is a concise technical summary of the changes proposed in this PR:
Introduces a withPrismaRetry utility to enhance the resilience of database operations across the inbox-zero-ai module. Wraps critical Prisma calls in the rule execution engine, draft tracking, conversation status management, and follow-up label operations to automatically retry transient P2028 errors, addressing stability issues observed in E2E tests.

TopicDetails
CLI Doc Update Update the .claude command documentation to reflect the preferred use of GitHub MCP for resolving PR comments, with gh CLI as a fallback option.
Modified files (1)
  • .claude/commands/address-pr-comments.md
Latest Contributors(1)
UserCommitDate
elie222chore-add-whitelistabl...January 09, 2026
Prisma Resilience Implement a withPrismaRetry utility with linear backoff to automatically handle transient P2028 errors during Prisma database operations, integrating this retry logic into key inbox-zero-ai components such as rule execution, draft tracking, conversation status updates, and follow-up label management to improve application stability.
Modified files (5)
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
Latest Contributors(2)
UserCommitDate
elie222refactor-polish-follow...January 11, 2026
joshwerner001@gmail.comFollow-up-remindersJanuary 08, 2026
This pull request is reviewed by Baz. Review like a pro on (Baz).

@vercel
Copy link

vercel bot commented Jan 11, 2026

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

Project Deployment Review Updated (UTC)
inbox-zero Ready Ready Preview Jan 11, 2026 11:44pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 11, 2026

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between d5c6d25 and 6e6b587.

📒 Files selected for processing (2)
  • .claude/commands/address-pr-comments.md
  • apps/web/utils/prisma-retry.ts
 ________________________________________
< Your docs say ‘TBD’. I’m here to ‘Do’. >
 ----------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).

Tip

You can disable sequence diagrams in the walkthrough.

Disable the reviews.sequence_diagrams setting in your project's settings in CodeRabbit to disable sequence diagrams in the walkthrough.

📝 Walkthrough

Walkthrough

This pull request introduces a new withPrismaRetry utility function that wraps Prisma database operations with exponential backoff retry logic, specifically targeting transient P2028 "Transaction already closed" errors. The utility is then applied across multiple files to improve resilience of database writes and transactions without altering existing functionality or API signatures.

Changes

Cohort / File(s) Summary
Prisma Retry Utility
apps/web/utils/prisma-retry.ts
New utility function introduced with configurable retry logic (default 3 retries, 100ms delay). Implements linear backoff with P2028 error detection and propagation of non-retriable errors.
Rule Execution with Enhanced Persistence
apps/web/utils/ai/choose-rule/run-rules.ts
Wrapped two prisma.executedRule.create calls and one updateMany call with withPrismaRetry. Expanded executeMatchedRule to include additional fields (messageId, threadId, automated, status, reason, matchMetadata, rule relation, emailAccount, createdAt) in record creation for enhanced context tracking.
Transactional Updates
apps/web/utils/reply-tracker/draft-tracking.ts
Wrapped multiple Prisma operations (update, $transaction) with withPrismaRetry across trackSentDraftStatus function paths, maintaining identical transactional semantics with added retry mechanism.
Utility Retry Application
apps/web/utils/follow-up/labels.ts, apps/web/utils/reply-tracker/handle-conversation-status.ts
Applied withPrismaRetry wrapper to single updateMany operations in each file; no logic changes beyond retry introduction.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • baz-reviewer
  • anakarentorosserrano-star

Poem

🐰 Retries and waits with patient grace,
Each Prisma call finds safer space,
Transient ghosts don't stand a chance,
When backoff logic leads the dance!
Database dreams stay strong and true, 🌟

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: introducing retry logic for Prisma P2028 transient errors, which is the core objective across all modified files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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

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

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.

1 issue found across 5 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="apps/web/utils/prisma-retry.ts">

<violation number="1" location="apps/web/utils/prisma-retry.ts:23">
P2: Comment incorrectly describes the backoff strategy as 'exponential' when it's actually linear (100ms, 200ms, 300ms). Either update the comment to say 'Linear backoff' or change the implementation to true exponential backoff.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

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

🤖 Fix all issues with AI agents
In @apps/web/utils/prisma-retry.ts:
- Around line 30-31: The final unreachable statement `throw new Error("Prisma
retry exhausted")` should be removed (or replaced only if TypeScript requires
it) because all paths in the retry function (e.g., the function containing the
retry loop in prisma-retry.ts) already either return on success or throw on
failure; delete that dangling throw to eliminate dead code and keep return-type
correctness by relying on the existing throws inside the loop (or add an
explicit unreachable type assertion only if the compiler demands it).
🧹 Nitpick comments (2)
apps/web/utils/prisma-retry.ts (1)

22-26: Backoff is linear, not exponential.

The comment says "Exponential backoff" but delayMs * attempt produces linear delays (100ms, 200ms, 300ms). True exponential would be delayMs * 2^(attempt-1) yielding 100ms, 200ms, 400ms.

This works fine for the current use case, but the comment is misleading.

Option 1: Fix comment to match implementation
-        // Exponential backoff: 100ms, 200ms, 300ms...
+        // Linear backoff: 100ms, 200ms, 300ms...
Option 2: Implement actual exponential backoff
-        // Exponential backoff: 100ms, 200ms, 300ms...
-        const backoff = delayMs * attempt;
+        // Exponential backoff: 100ms, 200ms, 400ms...
+        const backoff = delayMs * Math.pow(2, attempt - 1);
apps/web/utils/reply-tracker/handle-conversation-status.ts (1)

148-165: Consider wrapping upsert with retry logic for consistency.

The threadTracker.upsert operation at lines 148-165 is not wrapped with withPrismaRetry, while the updateMany above (lines 124-135) is wrapped. Both operations target the same table and could potentially encounter P2028 errors.

♻️ Proposed fix
   if (trackerType) {
-    await prisma.threadTracker.upsert({
-      where: {
-        emailAccountId_threadId_messageId: {
-          emailAccountId,
-          threadId,
-          messageId,
+    await withPrismaRetry(() =>
+      prisma.threadTracker.upsert({
+        where: {
+          emailAccountId_threadId_messageId: {
+            emailAccountId,
+            threadId,
+            messageId,
+          },
         },
-      },
-      update: {},
-      create: {
-        emailAccountId,
-        threadId,
-        messageId,
-        type: trackerType,
-        sentAt,
-      },
-    });
+        update: {},
+        create: {
+          emailAccountId,
+          threadId,
+          messageId,
+          type: trackerType,
+          sentAt,
+        },
+      }),
+    );
   }
📜 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 cb278ff and d5c6d25.

📒 Files selected for processing (5)
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
🧰 Additional context used
📓 Path-based instructions (16)
**/*.{ts,tsx}

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

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use import type for types
Make sure all enum members are literal values
Don't use TypeScript const enum
Don't declare empty interfaces
Don't let variables evolve into any type through reassignments
Don't use the any type
Don't misuse the non-null assertion operator (!) in TypeScript files
Don't use implicit any type on variable declarations
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
Use consistent accessibility modifiers on class properties and methods
Use function types instead of object types wit...

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/*.{ts,tsx,js,jsx}

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

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
apps/web/**/*.{ts,tsx}

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

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Do not export types/interfaces that are only used within the same file. Export later if needed
Infer types from Zod schemas using z.infer<typeof schema> instead of duplicating as separate interfaces

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/*.ts

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

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/*.{tsx,ts,css}

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

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: Don't use accessKey attribute on any HTML element
Don't set aria-hidden="true" on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assign tabIndex to non-interactive HTML elements
Don't use positive integers for tabIndex property
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include a title element for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
Assign tabIndex to non-interactive HTML elements with aria-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include a type attribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden)
Always include a lang attribute on the html element
Always include a title attribute for iframe elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
!(pages/_document).{jsx,tsx}

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

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/*.{js,ts,jsx,tsx}

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

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

**/*.{js,ts,jsx,tsx}: Add helper functions to the bottom of files, not the top!
All imports go at the top of files, no mid-file dynamic imports.

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/{utils,helpers,lib}/**/*.{ts,tsx}

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

Logger should be passed as a parameter to helper functions instead of creating their own logger instances

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
apps/web/**/*.{ts,tsx,js,jsx}

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

apps/web/**/*.{ts,tsx,js,jsx}: Use @/ path aliases for imports from project root
Use proper error handling with try/catch blocks
Prefer self-documenting code over comments; use descriptive variable and function names instead of explaining intent with comments. Never add comments that just describe what the code does. Only add comments for 'why' not 'what'
Add helper functions to the bottom of files, not the top
All imports go at the top of files, no mid-file dynamic imports
Use getActionErrorMessage(error.error) from @/utils/error to extract user-friendly error messages

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
apps/web/**/*.{ts,tsx,css}

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

Follow tailwindcss patterns with prettier-plugin-tailwindcss

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
apps/web/**/*.{ts,tsx,js,jsx,json}

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

Client-side environment variables must be prefixed with NEXT_PUBLIC_

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,rs,kt,swift,m}

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

Prefer self-documenting code over comments; use descriptive variable and function names instead of explaining intent with comments. Never add comments that just describe what the code does - code should explain itself. Only add comments for 'why' not 'what'.

Files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts

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

LLM-related code must be organized in specific directories: apps/web/utils/ai/ for main implementations, apps/web/utils/llms/ for core utilities and configurations, and apps/web/__tests__/ for LLM-specific tests

Files:

  • apps/web/utils/ai/choose-rule/run-rules.ts
apps/web/utils/ai/**/*.ts

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

apps/web/utils/ai/**/*.ts: LLM feature functions must import from zod for schema validation, use createScopedLogger from @/utils/logger, chatCompletionObject and createGenerateObject from @/utils/llms, and import EmailAccountWithAI type from @/utils/llms/types
LLM feature functions must follow a standard structure: accept options with inputData and emailAccount parameters, implement input validation with early returns, define separate system and user prompts, create a Zod schema for response validation, and use createGenerateObject to execute the LLM call
System prompts must define the LLM's role and task specifications
User prompts must contain the actual data and context, and should be kept separate from system prompts
Always define a Zod schema for LLM response validation and make schemas as specific as possible to guide the LLM output
Use descriptive scoped loggers for each LLM feature, log inputs and outputs with appropriate log levels, and include relevant context in log messages
Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures using withRetry
Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Use TypeScript types for all LLM function parameters and return values, and define clear interfaces for complex input/output structures
Keep related AI functions in the same file or directory, extract common patterns into utility functions, and document complex AI logic with clear comments

Files:

  • apps/web/utils/ai/choose-rule/run-rules.ts
🧠 Learnings (11)
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures using `withRetry`

Applied to files:

  • apps/web/utils/prisma-retry.ts
  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
📚 Learning: 2025-11-25T14:38:42.022Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-11-25T14:38:42.022Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Import Prisma using the project's centralized utility: `import prisma from '@/utils/prisma'`

Applied to files:

  • apps/web/utils/reply-tracker/handle-conversation-status.ts
  • apps/web/utils/follow-up/labels.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls

Applied to files:

  • apps/web/utils/follow-up/labels.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

Applied to files:

  • apps/web/utils/follow-up/labels.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/*.test.{ts,tsx} : Mock Prisma using `vi.mock("@/utils/prisma")` and the provided mock from `@/utils/__mocks__/prisma`

Applied to files:

  • apps/web/utils/follow-up/labels.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Use Prisma for database queries in GET API routes

Applied to files:

  • apps/web/utils/follow-up/labels.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Use Prisma for all database queries in GET API routes

Applied to files:

  • apps/web/utils/follow-up/labels.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls

Applied to files:

  • apps/web/utils/follow-up/labels.ts
📚 Learning: 2026-01-08T15:09:06.736Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2026-01-08T15:09:06.736Z
Learning: Applies to apps/web/components/**/*.tsx : Use `getActionErrorMessage(error.error)` utility to extract user-friendly error messages from server actions, supporting optional `prefix` parameter

Applied to files:

  • apps/web/utils/ai/choose-rule/run-rules.ts
  • apps/web/utils/reply-tracker/draft-tracking.ts
📚 Learning: 2026-01-08T15:09:06.736Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2026-01-08T15:09:06.736Z
Learning: Applies to apps/web/utils/actions/!(*.validation).ts : Use `next-safe-action` for all server actions with `actionClient`, `.metadata()`, `.inputSchema()`, and `.action()` chain pattern

Applied to files:

  • apps/web/utils/ai/choose-rule/run-rules.ts
📚 Learning: 2026-01-07T21:07:34.062Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 1230
File: apps/web/utils/ai/document-filing/parse-filing-reply.ts:1-4
Timestamp: 2026-01-07T21:07:34.062Z
Learning: In files under apps/web/utils/ai (e.g., apps/web/utils/ai/document-filing/parse-filing-reply.ts), when you call createGenerateObject with a label parameter, do not create or attach a separate scoped logger. createGenerateObject logs internally using the provided label, so adding another logger duplicates logs. Prefer relying on createGenerateObject's internal logging for these cases.

Applied to files:

  • apps/web/utils/ai/choose-rule/run-rules.ts
🧬 Code graph analysis (4)
apps/web/utils/reply-tracker/handle-conversation-status.ts (1)
apps/web/utils/prisma-retry.ts (1)
  • withPrismaRetry (8-32)
apps/web/utils/follow-up/labels.ts (1)
apps/web/utils/prisma-retry.ts (1)
  • withPrismaRetry (8-32)
apps/web/utils/ai/choose-rule/run-rules.ts (3)
apps/web/utils/prisma-retry.ts (1)
  • withPrismaRetry (8-32)
apps/web/utils/action-item.ts (1)
  • sanitizeActionFields (200-289)
apps/web/utils/ai/choose-rule/types.ts (1)
  • serializeMatchReasons (62-91)
apps/web/utils/reply-tracker/draft-tracking.ts (1)
apps/web/utils/prisma-retry.ts (1)
  • withPrismaRetry (8-32)
⏰ 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). (4)
  • GitHub Check: Baz Reviewer
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (9)
apps/web/utils/reply-tracker/handle-conversation-status.ts (1)

124-135: LGTM on the retry wrapper for updateMany.

The withPrismaRetry wrapper is correctly applied to the updateMany operation.

apps/web/utils/follow-up/labels.ts (1)

119-131: LGTM!

The withPrismaRetry wrapper is correctly applied to the updateMany operation. The outer try/catch properly handles errors after retries are exhausted.

apps/web/utils/reply-tracker/draft-tracking.ts (4)

66-71: LGTM!

Retry wrapper correctly applied to the update operation.


93-108: LGTM!

Wrapping the $transaction with withPrismaRetry is appropriate since P2028 errors can occur during transaction execution.


192-201: LGTM!

The retry-wrapped update inside Promise.all is correctly structured—the provider call and DB update can proceed concurrently while the DB operation benefits from retry logic.


218-223: LGTM!

Retry wrapper correctly applied.

apps/web/utils/ai/choose-rule/run-rules.ts (3)

164-176: LGTM!

Retry wrapper correctly applied to the skipped-rule creation path.


318-346: LGTM!

The withPrismaRetry wrapper is correctly applied to the executedRule.create operation with nested createMany for action items. This is the critical write path that benefits from retry logic.


414-419: LGTM!

Retry wrapper correctly applied to the status update operation.

@elie222 elie222 merged commit e3c7a6d into main Jan 11, 2026
19 of 20 checks passed
@elie222 elie222 deleted the fix/p2028-retry-logic branch January 11, 2026 23:47
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

Comments