Skip to content

Fix traffic boost suggestion cache refresh#3332

Merged
alecgeatches merged 2 commits intoadd/traffic-boostfrom
fix/traffic-boost-existing-suggestions
May 19, 2025
Merged

Fix traffic boost suggestion cache refresh#3332
alecgeatches merged 2 commits intoadd/traffic-boostfrom
fix/traffic-boost-existing-suggestions

Conversation

@alecgeatches
Copy link
Contributor

@alecgeatches alecgeatches commented May 16, 2025

Description

This fixes a regression introduced by the caching changes in #3293 (comment) that caused generated suggestions to improperly save due to a cache emptying error.

In short, we were using the wp_cache_flush_group() function without the proper checks, which resulted in a stale cache value for suggestions. A more in-depth explanation is below.

Generating suggestions flow (new post)

Here's how a request runs to generate suggestions:

  1. User clicks "Boost Traffic" button on a new post.

  2. The browser calls into the traffic-boost/<post-id>/get-suggestions endpoint to determine if suggestions already exist:

    1. This calls into the get_existing_suggestions() REST handler.

    2. This goes into Inbound_Smart_Link::get_existing_suggestions(), which eventually calls down into Smart_Link::get_smart_links().

    3. No cache currently exists for the new post, so the code queries for pending smart links and saves the result to cache. As this is a new post, there are no pending links, so an empty array [] is saved to cache.

  3. Because there are no existing suggestions, the browser makes a call to traffic-boost/<post-id>/generate:

    1. This calls into the generate_link_suggestions() REST handler.

    2. After generating new suggestions, the code calls into Inbound_Smart_Link::delete_pending_suggestions(), because $discard_previous is true by default.

    3. delete_pending_suggestions() then deletes any existing pending links (of which there are none) and calls self::flush_cache_by_post_id().

    4. Finally, flush_cache_by_post_id() calls wp_cache_flush_group() on the group cache for the post, which should clear out any existing cached data.

The bug

The final step is where the bug happens. Looking at the documentation for wp_cache_flush_group(), there's also this important caveat:

Before calling this function, always check for group flushing support using the wp_cache_supports( 'flush_group' ) function.

Our code was not doing this step properly, and even though the wp_cache_flush_group() function exists, wp_cache_supports( 'flush_group' ) returns false on WPVIP. Note that the prior code was correctly using this check, and this bug was introduced during the caching refactor.

In step 2.3, the code saves an empty array to the post's suggestion cache, and step 3.4 doesn't actually clear that cache. In subsequent requests, get-suggestions has a cached value of [] which is returned. When the cache is properly cleared on step 3.4, the next get-suggestions request will make a new query and correctly return all of the existing suggestions.

By properly clearing out cached post values one at a time, we bypass the caching issue and fix the bug.

Other changes

I reduced the wp_cache_set() times from a maximum of MONTH_IN_SECONDS to WEEK_IN_SECONDS or DAY_IN_SECONDS. This isn't strictly necessary, but I think a month of cache time is probably too long in retrospect for most of these queries. Shorter cache times also means that cache-related bugs will clear up quicker.

How has this been tested?

This has been tested locally, and by pushing to a sandbox environment and ensuring caching works. To test locally, use this branch and clear your existing cache:

vip dev-env exec -- wp cache flush

Alternatively, to test on a production or child environment on VIP, use this command:

vip @<side-id>.<environment> -- wp cache flush

Summary by CodeRabbit

  • Chores
    • Reduced cache expiration times for smart link data, resulting in more frequent updates.
    • Improved cache flushing reliability by adding an additional capability check before clearing cache groups.

@alecgeatches alecgeatches self-assigned this May 16, 2025
@alecgeatches alecgeatches requested a review from a team as a code owner May 16, 2025 19:52
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 16, 2025

📝 Walkthrough

Walkthrough

The changes update cache expiration durations for smart link-related data, reducing them from one month to either one week or one day in two model classes. Additionally, a capability check is added before flushing cache groups to ensure compatibility. No public APIs or method signatures were altered.

Changes

File(s) Change Summary
src/Models/class-inbound-smart-link.php Reduced cache expiration for pending inbound smart link suggestions count from one month to one day.
src/Models/class-smart-link.php Reduced cache durations for smart link UID-to-post mapping (one month to one week), smart link IDs per post (one month to one day), and link counts per post (one month to one week). Added a capability check before flushing cache groups.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SmartLinkModel
    participant Cache

    User->>SmartLinkModel: Request smart link data
    SmartLinkModel->>Cache: Check for cached data (shorter expiration)
    alt Cache hit
        Cache-->>SmartLinkModel: Return cached data
    else Cache miss
        SmartLinkModel->>SmartLinkModel: Generate data
        SmartLinkModel->>Cache: Store data with new expiration
        SmartLinkModel-->>User: Return generated data
    end
Loading
sequenceDiagram
    participant System
    participant SmartLinkModel
    participant Cache

    System->>SmartLinkModel: Request cache flush by post ID
    SmartLinkModel->>SmartLinkModel: Check if cache group flush is supported
    alt Supported
        SmartLinkModel->>Cache: Flush cache group
    else Not supported
        SmartLinkModel-->>System: Skip group flush
    end
Loading

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 94667bd and 2e1a5c3.

📒 Files selected for processing (2)
  • src/Models/class-inbound-smart-link.php (1 hunks)
  • src/Models/class-smart-link.php (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{html,php}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the HTML and PHP code to ensure it is well-structured and adheres ...

**/*.{html,php}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the HTML and PHP code to ensure it is well-structured and adheres to best practices.
  • Ensure the code follows WordPress coding standards and is well-documented.
  • Confirm the code is secure and free from vulnerabilities.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Verify code compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/Models/class-inbound-smart-link.php
  • src/Models/class-smart-link.php
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: E2E against WordPress latest
  • GitHub Check: build
🔇 Additional comments (5)
src/Models/class-inbound-smart-link.php (1)

1101-1101: Good change - reducing cache lifetime improves freshness

Reducing the cache expiration time from one month to one day will help ensure that the count of pending inbound smart link suggestions stays fresh and reduces the impact of cache-related issues.

src/Models/class-smart-link.php (4)

225-225: Appropriate cache duration reduction

Reducing the cache lifetime from one month to one week is a good practice for cache freshness while still maintaining decent performance.


364-364: Good cache duration adjustment

Reducing the cache lifetime for the UID-to-smart-link mapping from one month to one week helps maintain cache freshness.


964-964: Appropriate cache expiration for dynamic data

Changing the cache duration for smart link IDs to one day is appropriate since this data is more dynamic and benefits from more frequent refreshing.


1166-1166: Good balance of performance and freshness

Setting the cache expiration for link counts to one week instead of one month provides a good balance between performance and data freshness.

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

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.

@acicovic acicovic added this to the 3.19.0 milestone May 18, 2025
Copy link
Collaborator

@acicovic acicovic left a comment

Choose a reason for hiding this comment

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

Thank you so much for the detailed explanation. Works well in my testing!

@acicovic acicovic added the Feature: Engagement Boost Ticket/PR related to Engagement Boost label May 18, 2025
@alecgeatches alecgeatches merged commit 4f2f1b6 into add/traffic-boost May 19, 2025
38 checks passed
@alecgeatches alecgeatches deleted the fix/traffic-boost-existing-suggestions branch May 19, 2025 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Feature: Engagement Boost Ticket/PR related to Engagement Boost

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants