Skip to content

Fix race condition in Unsplash search that causes mixed results#24583

Merged
9larsons merged 3 commits into
TryGhost:mainfrom
niranjan-uma-shankar:fix-search-debounce
Jun 12, 2026
Merged

Fix race condition in Unsplash search that causes mixed results#24583
9larsons merged 3 commits into
TryGhost:mainfrom
niranjan-uma-shankar:fix-search-debounce

Conversation

@niranjan-uma-shankar

@niranjan-uma-shankar niranjan-uma-shankar commented Aug 2, 2025

Copy link
Copy Markdown
Contributor

This PR fixes a race condition in the Unsplash search flow where results from an intermediate search term (e.g., "germ") may appear alongside the final term (e.g., "germany") when users pause briefly while typing.

Fixes: #24584

Root cause

The race condition occurs due to the combination of:

  1. A debounce in _search() delaying API calls.

  2. The updateSearch() method triggering a UI reset too early, before this.photos is populated.

  3. No mechanism to discard results from outdated search terms.

I could consistently reproduce results on a ~50Mbps connection:

  • Type "germany" with a brief ~1s pause after "m".
  • "germ" triggers a search.
  • Before that request completes, the user continues typing to "germany", triggering a new search.
  • Since both API calls resolve asynchronously, the results from "germ" are populated, followed by the results from "germany" being appended to the previous results, leading to incorrect UI state.

Changes made

The fix adds validation to ensure that search results are only applied if the returned term matches the current user input. Each _makeRequest() call captures the term at the time it was made, and the response handler checks if it still matches the latest search term. If not, the results are discarded.

Before

  • Typing "Germany" with a brief pause shows results for "Germ" at the top.
  • Network requests shows search fired for both "germ" and "germany".
Screen.Recording.2025-08-02.at.3.47.40.PM.mp4

After

  • Typing "Germany" with a brief pause at "Germ" discards the old search results, ensuring that the relevant result for "Germany" appears at the top.
  • Network requests shows search fired for both "germ" and "germany". The fix ensures that only the results for "germany" are included in the results.
Screen.Recording.2025-08-02.at.3.50.05.PM.mp4

Testing Instructions

  1. Throttle your network to ~50Mbps.
  2. Open the editor for either a post or page.
  3. Click on "Add feature image".
  4. In the Unsplash search bar, type a term slowly with a pause in the middle (e.g., "para" → pause → "chute").
  5. Ensure that only results for the final input (e.g., "parachute") are shown.
  6. Try with other terms and varying pause durations to confirm consistent behaviour.
  7. Ensure that other behaviours (such as lazy loading paginated content in Unsplash results) remain unaffected.

@coderabbitai

coderabbitai Bot commented Aug 2, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The code modifies the Unsplash image search service to prevent stale search results from being appended when the user changes the search term during an asynchronous request. It introduces a mechanism to track the search term at the time of the request and ensures that only results matching the latest search term are processed. This involves updating the _search task to capture the search term, passing it through _makeRequest, and updating _addPhotosFromResponse to check for term consistency before adding photos.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent race condition in Unsplash search causing mixed/incorrect results (#24584)
Ensure only results for the latest search term are appended in Unsplash search (#24584)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b5dedb0 and ce8db6c.

📒 Files selected for processing (1)
  • ghost/admin/app/services/unsplash.js (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: niranjan-uma-shankar
PR: TryGhost/Ghost#24557
File: apps/admin-x-settings/src/components/settings/general/TimeZone.tsx:7-7
Timestamp: 2025-08-01T12:44:07.467Z
Learning: In Ghost development, PRs may depend on unpublished changes from SDK packages. When this occurs, TypeScript compilation errors for missing exports are expected and documented in the PR description until the dependency packages are published and updated. This is normal workflow for cross-repository feature development.
⏰ 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: Unit tests (Node 22.13.1)
  • GitHub Check: E2E tests
  • GitHub Check: Lint
  • GitHub Check: Admin tests - Chrome
🔇 Additional comments (4)
ghost/admin/app/services/unsplash.js (4)

112-118: LGTM! Race condition fix correctly implemented.

The search term is properly captured after the debounce timeout and passed to the request. This ensures that only results matching the final search term (after user stops typing) are processed, effectively preventing the race condition where intermediate search results could mix with final results.


120-126: Excellent race condition prevention logic.

The guard clause effectively prevents stale search results from being added when the search term has changed during the asynchronous request. The validation logic is correct and the comments clearly explain the purpose.


201-201: Parameter passing correctly implemented.

The captured search term is properly forwarded through the promise chain to _addPhotosFromResponse, completing the race condition fix implementation.


114-126: Complete solution effectively addresses the race condition.

The implementation successfully solves the Unsplash search race condition described in the PR objectives. By capturing the search term at request time and validating it before adding photos, the fix ensures that only results matching the current search term are displayed, preventing mixed results from intermediate searches.

The solution is well-designed with:

  • Minimal code changes that don't affect existing functionality
  • Clear parameter flow from search initiation to result processing
  • Proper handling of both search and non-search requests
  • Good code documentation explaining the fix

Also applies to: 201-201

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 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.
    • @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 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.

niranjan-uma-shankar and others added 3 commits June 10, 2026 16:05
The search debouncing was causing new search results to get appended to old search results, instead of overwriting the results. This fix captures the
search term at request time and validates it matches the current search term
before applying results, ensuring only relevant search results are displayed.
ref TryGhost#24583

- a stale search response was still able to overwrite the stored pagination links, so loading more results could fetch pages for the previous search term
- applies the same stale search term guard to pagination extraction and adds unit tests covering both the discarded and accepted response paths
@9larsons 9larsons force-pushed the fix-search-debounce branch from ce8db6c to 3d45c2d Compare June 10, 2026 21:06
@9larsons 9larsons enabled auto-merge (squash) June 12, 2026 00:38

@9larsons 9larsons left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@niranjan-uma-shankar Thanks for this! I think there's still some gaps in the logic, though this ought to improve the gap here. Ultimately, we're moving to React and we'll need to rebuild all of this.

@9larsons 9larsons merged commit 93b0aa1 into TryGhost:main Jun 12, 2026
38 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community [triage] Community features and bugs needs:review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Featured image: Race condition in Unsplash search causes incorrect results

3 participants