Skip to content

Comments

Hotfix#1341

Merged
MrgSub merged 1 commit intostagingfrom
06-17-hotfix
Jun 17, 2025
Merged

Hotfix#1341
MrgSub merged 1 commit intostagingfrom
06-17-hotfix

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jun 17, 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

  • New Features

    • Enhanced user and connection management with new capabilities for updating user records, deleting connections, managing user hotkeys, and updating user settings.
    • Added support for synchronizing and updating user writing style matrices.
  • Refactor

    • Streamlined database operations by centralizing access through a global environment, replacing direct context-based database usage.
    • Simplified logic for updating user settings, shortcuts, and writing style matrices via new database interface methods.
  • Style

    • Added informational log messages for Gmail watch setup in subscription management.
  • Documentation

    • Updated documentation to clarify usage and warnings for certain database methods.
  • Chores

    • Exported additional utility functions for writing style matrix updates.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

Warning

Rate limit exceeded

@MrgSub has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 48 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 717240c and 08fd471.

📒 Files selected for processing (14)
  • apps/server/src/ctx.ts (0 hunks)
  • apps/server/src/lib/auth.ts (4 hunks)
  • apps/server/src/lib/driver/utils.ts (2 hunks)
  • apps/server/src/lib/factories/base-subscription.factory.ts (2 hunks)
  • apps/server/src/lib/factories/google-subscription.factory.ts (1 hunks)
  • apps/server/src/lib/server-utils.ts (1 hunks)
  • apps/server/src/main.ts (8 hunks)
  • apps/server/src/services/writing-style-service.ts (4 hunks)
  • apps/server/src/trpc/index.ts (0 hunks)
  • apps/server/src/trpc/routes/connections.ts (3 hunks)
  • apps/server/src/trpc/routes/settings.ts (3 hunks)
  • apps/server/src/trpc/routes/shortcut.ts (2 hunks)
  • apps/server/src/trpc/trpc.ts (3 hunks)
  • apps/server/wrangler.jsonc (1 hunks)

Walkthrough

This set of changes refactors database access across several server modules, removing direct ORM interactions and context-based database injection in favor of encapsulated methods on a global database instance accessed via Cloudflare Workers' environment. It introduces new helper methods for user, connection, settings, and writing style matrix management, and updates service and router modules to use this new interface. Additionally, some helper functions are now exported, and logging is added to the Google subscription factory.

Changes

File(s) Change Summary
apps/server/src/ctx.ts Removed db property from HonoVariables type and its import.
apps/server/src/lib/factories/google-subscription.factory.ts Added console logging to setupGmailWatch for debugging information.
apps/server/src/main.ts Added new helper methods for user, connection, hotkey, settings, and writing style matrix management.
apps/server/src/services/writing-style-service.ts Refactored to use new db.syncUserMatrix; exported two helper functions.
apps/server/src/trpc/index.ts Removed db from the context object passed to the TRPC router caller.
apps/server/src/trpc/routes/connections.ts Replaced context-based DB access with global DB methods for set/delete connection mutations.
apps/server/src/trpc/routes/settings.ts Replaced direct ORM queries with global DB helper methods for user settings get/save.
apps/server/src/trpc/routes/shortcut.ts Replaced context-based DB access with global DB method for updating user hotkeys.

Sequence Diagram(s)

sequenceDiagram
    participant Router
    participant Env
    participant ZeroDB

    Router->>Env: Get global-db instance
    Env-->>Router: Return ZeroDB instance
    Router->>ZeroDB: Call helper method (e.g., updateUser, deleteConnection, etc.)
    ZeroDB-->>Router: Perform DB operation and return result
Loading
sequenceDiagram
    participant Service
    participant Env
    participant ZeroDB

    Service->>Env: Get global-db instance
    Env-->>Service: Return ZeroDB instance
    Service->>ZeroDB: syncUserMatrix(connectionId, emailStyleMatrix)
    ZeroDB-->>Service: Synchronize writing style matrix
Loading

Possibly related PRs

  • Mail-0/Zero#1318: Involves Gmail push notification workflows and introduces a Google subscription factory, closely related to logging changes and subscription management in this PR.

Poem

A rabbit hopped through fields of code,
Refactoring where the data flowed.
Contexts trimmed, new helpers sprout,
Global DB—no need to shout!
With logs and exports, all in sync,
The server’s stronger now, I think.
🐇✨

✨ 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 Jun 17, 2025

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

@MrgSub MrgSub marked this pull request as ready for review June 17, 2025 22:20
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: 5

🧹 Nitpick comments (7)
apps/server/src/trpc/routes/shortcut.ts (1)

15-19: Consider caching the Durable-Object stub

env.ZERO_DB.get(env.ZERO_DB.idFromName('global-db')) is executed on every call path.
While cheap, repeating it in every resolver clutters code and adds avoidable overhead. Inject the stub once (e.g. in createContext) or wrap it in a helper.

apps/server/src/trpc/routes/connections.ts (1)

46-50: Deduplicate DB-stub acquisition

Same observation as in shortcut.ts – the stub retrieval is repeated in each resolver. Extracting const db = getZeroDb() (utility) or attaching it to ctx keeps resolvers slimmer and centralises the binding logic.

apps/server/src/trpc/routes/settings.ts (2)

17-20: Same DB-stub duplication comment as above

Factor out stub retrieval to keep resolvers terse.


36-45: No error handling around DB writes

insertUserSettings / updateUserSettings failures will bubble up as 500s without context.
Wrap in try/catch and return typed tRPC errors so the client can act accordingly.

apps/server/src/services/writing-style-service.ts (1)

192-194: Repeated stub acquisition inside retry loop

Inside pRetry the stub is fetched every retry. Minor, but caching the stub once before the retry would avoid unnecessary Durable-Object look-ups.

apps/server/src/main.ts (2)

63-67: Consider surfacing the deleted-row count from deleteConnection

Right now the result of the DELETE is discarded, so callers cannot distinguish “nothing deleted” (wrong IDs) from success.
Returning the rowCount (or .returning({ id: connection.id })) would improve error handling.


172-175: Docstring warns about “dangerous” usage without explaining why

Add a short rationale (e.g. “does not validate ownership – may leak data”) so future maintainers understand the risk.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c2cea41 and 717240c.

📒 Files selected for processing (8)
  • apps/server/src/ctx.ts (0 hunks)
  • apps/server/src/lib/factories/google-subscription.factory.ts (1 hunks)
  • apps/server/src/main.ts (6 hunks)
  • apps/server/src/services/writing-style-service.ts (2 hunks)
  • apps/server/src/trpc/index.ts (0 hunks)
  • apps/server/src/trpc/routes/connections.ts (1 hunks)
  • apps/server/src/trpc/routes/settings.ts (3 hunks)
  • apps/server/src/trpc/routes/shortcut.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • apps/server/src/ctx.ts
  • apps/server/src/trpc/index.ts
🔇 Additional comments (4)
apps/server/src/trpc/routes/connections.ts (1)

56-62: Race condition after deletion

activeConnection is fetched after await db.deleteConnection(...).
If getActiveConnection() still relies on that deleted row (e.g. through caching), it may resolve undefined, making the subsequent updateUser check always false.
Verify that behaviour is acceptable or fetch activeConnection before deletion.

apps/server/src/trpc/routes/settings.ts (1)

26-26: ctx.c may be undefined in tRPC context

ctx.c.executionCtx.waitUntil(...) assumes that c (the original Hono context) was forwarded into the tRPC context under the c key.
If that contract changes, this line throws at runtime. Guard or surface a clearer error.

apps/server/src/main.ts (2)

1-6: No issues detected with the new imports.

Everything compiles and typings look correct.


98-102: Potential missing index on userHotkeys.userId

findUserHotkeys will be executed frequently and filters solely on userId.
Verify that userId is either the PK or has a dedicated index; otherwise look-ups will degrade as the table grows.

Comment on lines +226 to +230
console.log(
`[SUBSCRIPTION] Setting up Gmail watch for connection: ${connectionData.id} ${topicName} projects/${serviceAccount.project_id}/topics/${topicName}`,
);
console.log(`[SUBSCRIPTION] Service Account: ${serviceAccount.client_email}`, serviceAccount);

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove sensitive logging of the whole service-account object

serviceAccount.private_key (and other secrets) ends up in the worker logs, which are readable by anyone with log access. This is a direct leakage of credentials and violates least-privilege & PCI/GDPR guidance.
Keep the contextual info but mask / drop secrets.

-    console.log(
-      `[SUBSCRIPTION] Setting up Gmail watch for connection: ${connectionData.id} ${topicName} projects/${serviceAccount.project_id}/topics/${topicName}`,
-    );
-    console.log(`[SUBSCRIPTION] Service Account: ${serviceAccount.client_email}`, serviceAccount);
+    console.log(
+      `[SUBSCRIPTION] Setting up Gmail watch for connection ${connectionData.id} on topic ${topicName}`,
+    );
+    // Only log non-sensitive identifiers
+    console.log('[SUBSCRIPTION] Service Account:', {
+      client_email: serviceAccount.client_email,
+      project_id: serviceAccount.project_id,
+    });
📝 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
console.log(
`[SUBSCRIPTION] Setting up Gmail watch for connection: ${connectionData.id} ${topicName} projects/${serviceAccount.project_id}/topics/${topicName}`,
);
console.log(`[SUBSCRIPTION] Service Account: ${serviceAccount.client_email}`, serviceAccount);
console.log(
`[SUBSCRIPTION] Setting up Gmail watch for connection ${connectionData.id} on topic ${topicName}`,
);
// Only log non-sensitive identifiers
console.log('[SUBSCRIPTION] Service Account:', {
client_email: serviceAccount.client_email,
project_id: serviceAccount.project_id,
});
🤖 Prompt for AI Agents
In apps/server/src/lib/factories/google-subscription.factory.ts around lines 226
to 230, the code logs the entire serviceAccount object including sensitive
fields like private_key, which exposes credentials in logs. Modify the logging
to exclude or mask sensitive fields by only logging non-sensitive properties
such as client_email or project_id, and avoid printing the full serviceAccount
object to prevent credential leakage.

Comment on lines +132 to +140
async updateUserSettings(userId: string, settings: typeof defaultUserSettings) {
return await this.db
.update(userSettings)
.set({
settings,
updatedAt: new Date(),
})
.where(eq(userSettings.userId, userId));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

updateUserSettings silently no-ops when the row is absent

If a new user calls this method before insertUserSettings, nothing is written.
Either:

  1. Change this into an upsert (.onConflictDoUpdate)
  2. Or fall back to insertUserSettings when rowCount === 0.

This prevents hidden data loss.

🤖 Prompt for AI Agents
In apps/server/src/main.ts around lines 132 to 140, the updateUserSettings
method does not handle the case where the user settings row does not exist,
causing silent no-ops. To fix this, modify the method to perform an upsert using
.onConflictDoUpdate to insert or update the settings atomically, or
alternatively check the update result's rowCount and call insertUserSettings if
no rows were updated, ensuring data is not lost silently.

Comment on lines +104 to +120
async insertUserHotkeys(userId: string, shortcuts: (typeof userHotkeys.$inferInsert)[]) {
return await this.db
.insert(userHotkeys)
.values({
userId,
shortcuts,
createdAt: new Date(),
updatedAt: new Date(),
})
.onConflictDoUpdate({
target: userHotkeys.userId,
set: {
shortcuts,
updatedAt: new Date(),
},
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Upsert relies on userId being UNIQUE — is that constraint guaranteed?

onConflictDoUpdate({ target: userHotkeys.userId, … }) assumes a unique (or primary-key) constraint on userId.
If the table allows multiple rows per user the upsert will error at runtime.
Please confirm the schema or switch to a compound key (e.g. userId, shortcutId).

🤖 Prompt for AI Agents
In apps/server/src/main.ts around lines 104 to 120, the upsert operation uses
onConflictDoUpdate with userHotkeys.userId as the target, which requires userId
to have a unique or primary key constraint. Verify the database schema to ensure
userId is unique; if not, modify the conflict target to use a compound key such
as userId and shortcutId to avoid runtime errors during upsert.

Comment on lines +59 to +61
async updateUser(userId: string, data: Partial<typeof user.$inferInsert>) {
return await this.db.update(user).set(data).where(eq(user.id, userId));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

updateUser should also bump updatedAt and optionally return the mutated row

Updating a user without touching the updatedAt column makes auditing harder and breaks the implicit contract most tables have.
Drizzle also lets you append .returning() if callers need the fresh row.

-    return await this.db.update(user).set(data).where(eq(user.id, userId));
+    return await this.db
+      .update(user)
+      .set({ ...data, updatedAt: new Date() })
+      .where(eq(user.id, userId))
+      .returning();            # if callers need the updated row
📝 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
async updateUser(userId: string, data: Partial<typeof user.$inferInsert>) {
return await this.db.update(user).set(data).where(eq(user.id, userId));
}
async updateUser(userId: string, data: Partial<typeof user.$inferInsert>) {
return await this.db
.update(user)
.set({ ...data, updatedAt: new Date() })
.where(eq(user.id, userId))
.returning(); # if callers need the updated row
}
🤖 Prompt for AI Agents
In apps/server/src/main.ts around lines 59 to 61, the updateUser method
currently updates user data without modifying the updatedAt timestamp and does
not return the updated row. Modify the updateUser method to also set the
updatedAt field to the current timestamp during the update and append a
.returning() call to return the updated row to the caller.

Comment on lines +184 to +219
async syncUserMatrix(connectionId: string, emailStyleMatrix: EmailMatrix) {
await this.db.transaction(async (tx) => {
const [existingMatrix] = await tx
.select({
numMessages: writingStyleMatrix.numMessages,
style: writingStyleMatrix.style,
})
.from(writingStyleMatrix)
.where(eq(writingStyleMatrix.connectionId, connectionId))
.for('update');

if (!existingMatrix) {
const newStyle = initializeStyleMatrixFromEmail(emailStyleMatrix);

await tx.insert(writingStyleMatrix).values({
connectionId,
numMessages: 1,
style: newStyle,
});
} else {
const newStyle = createUpdatedMatrixFromNewEmail(
existingMatrix.numMessages,
existingMatrix.style as WritingStyleMatrix,
emailStyleMatrix,
);

await tx
.update(writingStyleMatrix)
.set({
numMessages: existingMatrix.numMessages + 1,
style: newStyle,
})
.where(eq(writingStyleMatrix.connectionId, connectionId));
}
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Race condition: two newcomers can still create duplicate matrix rows

Although the code locks the existing row with for update, if two concurrent transactions both find no row they’ll each attempt INSERT, and only one will win. The loser will throw a unique-constraint error.

Safer pattern:

-        await tx.insert(writingStyleMatrix).values({ … });
+        await tx
+          .insert(writingStyleMatrix)
+          .values({ … })
+          .onConflictDoUpdate({
+            target: writingStyleMatrix.connectionId,
+            set: {
+              numMessages: 1,
+              style: initializeStyleMatrixFromEmail(emailStyleMatrix),
+            },
+          });

This keeps the logic single-path and avoids aborted transactions.

📝 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
async syncUserMatrix(connectionId: string, emailStyleMatrix: EmailMatrix) {
await this.db.transaction(async (tx) => {
const [existingMatrix] = await tx
.select({
numMessages: writingStyleMatrix.numMessages,
style: writingStyleMatrix.style,
})
.from(writingStyleMatrix)
.where(eq(writingStyleMatrix.connectionId, connectionId))
.for('update');
if (!existingMatrix) {
const newStyle = initializeStyleMatrixFromEmail(emailStyleMatrix);
await tx.insert(writingStyleMatrix).values({
connectionId,
numMessages: 1,
style: newStyle,
});
} else {
const newStyle = createUpdatedMatrixFromNewEmail(
existingMatrix.numMessages,
existingMatrix.style as WritingStyleMatrix,
emailStyleMatrix,
);
await tx
.update(writingStyleMatrix)
.set({
numMessages: existingMatrix.numMessages + 1,
style: newStyle,
})
.where(eq(writingStyleMatrix.connectionId, connectionId));
}
});
}
async syncUserMatrix(connectionId: string, emailStyleMatrix: EmailMatrix) {
await this.db.transaction(async (tx) => {
const [existingMatrix] = await tx
.select({
numMessages: writingStyleMatrix.numMessages,
style: writingStyleMatrix.style,
})
.from(writingStyleMatrix)
.where(eq(writingStyleMatrix.connectionId, connectionId))
.for('update');
if (!existingMatrix) {
const newStyle = initializeStyleMatrixFromEmail(emailStyleMatrix);
await tx
.insert(writingStyleMatrix)
.values({
connectionId,
numMessages: 1,
style: newStyle,
})
.onConflictDoUpdate({
target: writingStyleMatrix.connectionId,
set: {
numMessages: 1,
style: initializeStyleMatrixFromEmail(emailStyleMatrix),
},
});
} else {
const newStyle = createUpdatedMatrixFromNewEmail(
existingMatrix.numMessages,
existingMatrix.style as WritingStyleMatrix,
emailStyleMatrix,
);
await tx
.update(writingStyleMatrix)
.set({
numMessages: existingMatrix.numMessages + 1,
style: newStyle,
})
.where(eq(writingStyleMatrix.connectionId, connectionId));
}
});
}
🤖 Prompt for AI Agents
In apps/server/src/main.ts around lines 184 to 219, the current syncUserMatrix
method can cause a race condition where two concurrent transactions both find no
existing row and attempt to insert, leading to a unique-constraint error. To fix
this, refactor the method to attempt an update first and check the affected rows
count; if no rows were updated, then perform an insert. This single-path logic
avoids the race condition and aborted transactions by not relying on locking and
conditional inserts.

Copy link
Collaborator Author

MrgSub commented Jun 17, 2025

Merge activity

  • Jun 17, 10:37 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jun 17, 10:37 PM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit b136573 into staging Jun 17, 2025
3 checks passed
@MrgSub MrgSub deleted the 06-17-hotfix branch June 17, 2025 22:37
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