Skip to content

perf: optimize getLuckyUser for single user scenarios #19503 #22384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

ajayjha1
Copy link
Contributor

@ajayjha1 ajayjha1 commented Jul 10, 2025

This PR optimizes the getLuckyUser function to handle single-user scenarios more efficiently by adding an early return before expensive operations are performed.

Performance Impact:

Before: Single user scenarios performed 6+ database queries, calendar API calls, and complex calculations

After: Single user scenarios return in microseconds with zero external calls

Fixes #19503 (Performance optimization for single user round-robin scenarios)


Summary by cubic

Optimized getLuckyUser to return immediately for single-user scenarios, skipping all database and API calls for faster performance.

  • Performance
  • Single-user cases now return instantly with no external queries or calculations.

@ajayjha1 ajayjha1 requested a review from a team as a code owner July 10, 2025 12:49
Copy link

vercel bot commented Jul 10, 2025

@ajayjha1 is attempting to deploy a commit to the cal Team on Vercel.

A member of the Team first needs to authorize it.

@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Jul 10, 2025
@graphite-app graphite-app bot requested a review from a team July 10, 2025 12:49
@github-actions github-actions bot added consumer High priority Created by Linear-GitHub Sync performance area: performance, page load, slow, slow endpoints, loading screen, unresponsive labels Jul 10, 2025
@dosubot dosubot bot added this to the v5.5 milestone Jul 10, 2025
Copy link

graphite-app bot commented Jul 10, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/10/25)

1 reviewer was added to this PR based on Keith Williams's automation.

"Add community label" took an action on this PR • (07/10/25)

1 label was added to this PR based on Keith Williams's automation.

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.

cubic reviewed 2 files and found no issues. Review PR in cubic.dev.

@ajayjha1 ajayjha1 force-pushed the lucky-user-single branch from bef71d1 to c1456a9 Compare July 10, 2025 13:50
Copy link
Contributor

@Devanshusharma2005 Devanshusharma2005 left a comment

Choose a reason for hiding this comment

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

@ajayjha1 can you please try to address the unit tests failing. Marking it draft until then. Feel free to rfr

@Devanshusharma2005 Devanshusharma2005 marked this pull request as draft July 10, 2025 17:15
@ajayjha1
Copy link
Contributor Author

@Devanshusharma2005 I only changed the getLuckyUser.ts file, and all the tests for that passed. The failing test case seems unrelated to my changes. However, I think it might be due to some edge cases not covered, possibly because of different time zones. Let me know if you’d like me to look into and resolve that issue.

@ajayjha1 ajayjha1 marked this pull request as ready for review July 11, 2025 12:01
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.

cubic reviewed 2 files and found no issues. Review PR in cubic.dev.

Copy link
Contributor

@kart1ka kart1ka left a comment

Choose a reason for hiding this comment

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

Left a comment

Comment on lines 1482 to 1520

it("returns the single user immediately if only one user is available", async () => {
const singleUser = buildUser({
id: 42,
username: "singleuser",
name: "Single User",
email: "singleuser@example.com",
bookings: [],
});

// Mocks should not be called for data fetching in this case
const spyCalendar = vi.spyOn(CalendarManagerMock, "getBusyCalendarTimes");
const spyPrismaUser = vi.spyOn(prismaMock.user, "findMany");
const spyPrismaHost = vi.spyOn(prismaMock.host, "findMany");
const spyPrismaBooking = vi.spyOn(prismaMock.booking, "findMany");

await expect(
getLuckyUser({
availableUsers: [singleUser],
eventType: {
id: 1,
isRRWeightsEnabled: false,
team: { rrResetInterval: RRResetInterval.MONTH, rrTimestampBasis: RRTimestampBasis.CREATED_AT },
},
allRRHosts: [],
routingFormResponse: null,
})
).resolves.toStrictEqual(singleUser);

// Ensure no unnecessary data fetching occurred
expect(spyCalendar).not.toHaveBeenCalled();
expect(spyPrismaUser).not.toHaveBeenCalled();
expect(spyPrismaHost).not.toHaveBeenCalled();
expect(spyPrismaBooking).not.toHaveBeenCalled();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

when early return does not happen, this test throws error instead of failing gracefully.

Copy link
Contributor

Choose a reason for hiding this comment

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

The test is still not failing gracefully. The issue is still not resolved.

@kart1ka kart1ka marked this pull request as draft July 13, 2025 14:54
@ajayjha1 ajayjha1 marked this pull request as ready for review July 14, 2025 10:18
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.

cubic found 1 issue across 2 files. Review it in cubic.dev

React with 👍 or 👎 to teach cubic. Tag @cubic-dev-ai to give specific feedback.

});

// Mocks should not be called for data fetching in this case
const spyCalendar = vi.spyOn(CalendarManagerMock, "getBusyCalendarTimes");
Copy link
Contributor

Choose a reason for hiding this comment

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

Spies created in this test are never restored, which can leak mocked implementations or call history into other tests executed later in the same process and cause flaky behaviour. Call mockRestore() (or vi.restoreAllMocks()) in an afterEach/finally block.

Copy link
Contributor

coderabbitai bot commented Jul 15, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

"""

Walkthrough

The changes refactor the logic for optimizing the "single user" scenario in the lucky user selection process. Early-return logic is now implemented within the data-fetching layer to prevent unnecessary data retrieval when only one user is available. The test suite is updated to verify this behavior, ensuring no redundant data-fetching occurs.

Changes

File(s) Change Summary
.../server/getLuckyUser.ts Added early-return logic in getLuckyUser and getLuckyUser_requiresDataToBePreFetched to handle single-user cases without fetching data.
.../server/getLuckyUser.test.ts Added test verifying that no data fetching occurs when only one user is present; used afterEach to restore mocks for test isolation.

Assessment against linked issues

Objective Addressed Explanation
Avoid fetching all data if only one possible lucky user (#19503)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Poem

A single user hops in view,
No need to fetch the whole crew!
Early returns now save the day,
Test bunnies cheer, “Hooray, hooray!”
With mocks restored and code refined,
This lucky user’s easy to find.
🐇✨

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes
"""

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
  • 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.

Support

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

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 generate unit tests to generate unit tests for 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
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 (2)
packages/lib/server/getLuckyUser.ts (2)

511-514: Consider removing commented code instead of keeping it.

The commented-out early return logic should be removed rather than kept as comments, as it's no longer needed and adds noise to the codebase.

-  // Early return if only one available user to avoid unnecessary data fetching
-  // if (getLuckyUserParams.availableUsers.length === 1) {
-  //   return getLuckyUserParams.availableUsers[0];
-  // }

573-576: Consider removing commented code instead of keeping it.

Similar to the previous comment, this commented-out early return logic should be removed to keep the code clean.

-  // Early return if only one user is available
-  // if (availableUsers.length === 1) {
-  //   return { luckyUser: availableUsers[0], usersAndTheirBookingShortfalls: [] };
-  // }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 202d248 and 56b3579.

📒 Files selected for processing (2)
  • packages/lib/server/getLuckyUser.test.ts (3 hunks)
  • packages/lib/server/getLuckyUser.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/lib/server/getLuckyUser.test.ts (2)
packages/lib/test/builder.ts (1)
  • buildUser (286-340)
packages/lib/server/getLuckyUser.ts (1)
  • getLuckyUser (505-539)
⏰ 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). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Security Check
🔇 Additional comments (3)
packages/lib/server/getLuckyUser.ts (1)

634-646: LGTM! Excellent optimization implementation.

The early return logic at the data-fetching level is well-implemented. It correctly returns empty data structures for all expected return values when only one user is available, effectively avoiding expensive database queries and external API calls. This approach is more efficient than performing the check after data has been fetched.

packages/lib/server/getLuckyUser.test.ts (2)

29-31: LGTM! Proper mock restoration implemented.

The afterEach hook correctly addresses the mock restoration issue mentioned in past review comments by calling vi.restoreAllMocks() after each test. This ensures test isolation and prevents mocked implementations from leaking between tests.


1487-1520: Excellent test coverage for the single-user optimization.

This test case effectively verifies that the optimization works as intended:

  1. Correct setup: Creates a single user scenario
  2. Proper verification: Uses spies to ensure no external calls are made
  3. Comprehensive coverage: Checks all relevant mock functions (calendar, user, host, booking queries)
  4. Clear assertions: Verifies both the return value and the absence of external calls

The test correctly validates that the performance optimization prevents unnecessary data fetching operations in single-user scenarios.

@ajayjha1
Copy link
Contributor Author

@kart1ka can you check it now? I’ve made the updates.

@CarinaWolli CarinaWolli modified the milestones: v5.5, v5.6 Jul 16, 2025
@dosubot dosubot bot modified the milestone: v5.6 Jul 16, 2025
Copy link
Contributor

@kart1ka kart1ka left a comment

Choose a reason for hiding this comment

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

Left a comment.

Comment on lines 1482 to 1520

it("returns the single user immediately if only one user is available", async () => {
const singleUser = buildUser({
id: 42,
username: "singleuser",
name: "Single User",
email: "singleuser@example.com",
bookings: [],
});

// Mocks should not be called for data fetching in this case
const spyCalendar = vi.spyOn(CalendarManagerMock, "getBusyCalendarTimes");
const spyPrismaUser = vi.spyOn(prismaMock.user, "findMany");
const spyPrismaHost = vi.spyOn(prismaMock.host, "findMany");
const spyPrismaBooking = vi.spyOn(prismaMock.booking, "findMany");

await expect(
getLuckyUser({
availableUsers: [singleUser],
eventType: {
id: 1,
isRRWeightsEnabled: false,
team: { rrResetInterval: RRResetInterval.MONTH, rrTimestampBasis: RRTimestampBasis.CREATED_AT },
},
allRRHosts: [],
routingFormResponse: null,
})
).resolves.toStrictEqual(singleUser);

// Ensure no unnecessary data fetching occurred
expect(spyCalendar).not.toHaveBeenCalled();
expect(spyPrismaUser).not.toHaveBeenCalled();
expect(spyPrismaHost).not.toHaveBeenCalled();
expect(spyPrismaBooking).not.toHaveBeenCalled();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

The test is still not failing gracefully. The issue is still not resolved.

@kart1ka kart1ka marked this pull request as draft July 16, 2025 15:07
@ajayjha1
Copy link
Contributor Author

Hi @kart1ka,
Thanks for your feedback! Could you please clarify what you mean by “failing gracefully” in this context?

Do you mean:

  • The test should fail with a specific, custom error message (not a generic TypeError)?
  • The test should use a particular assertion style (e.g., .rejects.toThrow(...) instead of .resolves.toStrictEqual(...))?
  • Or is there another behavior you’re looking for when the early return is missing?

@github-actions github-actions bot added the ❗️ migrations contains migration files label Jul 24, 2025
@ajayjha1 ajayjha1 force-pushed the lucky-user-single branch from 43db475 to d1022f4 Compare July 24, 2025 12:36
@ajayjha1 ajayjha1 marked this pull request as ready for review July 24, 2025 12:42
@kart1ka
Copy link
Contributor

kart1ka commented Jul 29, 2025

Hi @kart1ka, Thanks for your feedback! Could you please clarify what you mean by “failing gracefully” in this context?

Do you mean:

  • The test should fail with a specific, custom error message (not a generic TypeError)?
  • The test should use a particular assertion style (e.g., .rejects.toThrow(...) instead of .resolves.toStrictEqual(...))?
  • Or is there another behavior you’re looking for when the early return is missing?

When early return is missing, the code just crashes as the error thrown is not handled in the test.

@kart1ka kart1ka marked this pull request as draft July 29, 2025 04:50
@ajayjha1 ajayjha1 force-pushed the lucky-user-single branch from 94036de to 84795d8 Compare July 29, 2025 09:34
@ajayjha1
Copy link
Contributor Author

@kart1ka Please check it. test runs successfully in both the cases whether the early return present or not and that should be the expected case ig.

@ajayjha1 ajayjha1 marked this pull request as ready for review July 29, 2025 09:43
@dosubot dosubot bot added the 🧹 Improvements Improvements to existing features. Mostly UX/UI label Jul 29, 2025
@kart1ka kart1ka marked this pull request as draft August 5, 2025 03:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
community Created by Linear-GitHub Sync consumer High priority Created by Linear-GitHub Sync 🧹 Improvements Improvements to existing features. Mostly UX/UI ❗️ migrations contains migration files performance area: performance, page load, slow, slow endpoints, loading screen, unresponsive
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[CAL-5212] Don't fetch all data if only one possible lucky user
4 participants