Skip to content

Conversation

@dognose24
Copy link
Contributor

@dognose24 dognose24 commented Dec 5, 2025

Fixes STATS-184.

This PR fixes an issue where the post stats cache could get stuck on invalid data or a WP_Error and never refresh. When corrupted or malformed cache entries exist in post meta, subsequent calls to fetch_post_stats() would always return that bad data instead of refetching from WPCOM.

With this change, invalid or error cache entries trigger a fresh remote fetch and a self-healing cache update, while still honoring the existing cache expiration mechanism for valid data.

Proposed changes:

  • Introduce the refresh_post_stats_cache() helper to handle the fetch from WPCOM + update post meta flow
  • Detect and recover from invalid cache entries in fetch_post_stats()

Other information:

  • Have you written new tests for your changes, if applicable?
  • Have you checked the E2E test CI results, and verified that your changes do not break them?
  • Have you tested your changes on WordPress.com, if applicable (if so, you'll see a generated comment below with a script to run)?

Jetpack product discussion

Does this pull request change what data or activity we track or use?

No.

Testing instructions:

  • Test on the case in the issue from the support ticket
  • Ensure the This individual post views count of Blog Stats in any post is correctly aligned with /stats/post/{post-id}/{site-slug}.

@github-actions
Copy link
Contributor

github-actions bot commented Dec 5, 2025

Are you an Automattician? Please test your changes on all WordPress.com environments to help mitigate accidental explosions.

  • To test on WoA, go to the Plugins menu on a WoA dev site. Click on the "Upload" button and follow the upgrade flow to be able to upload, install, and activate the Jetpack Beta plugin. Once the plugin is active, go to Jetpack > Jetpack Beta, select your plugin (Jetpack or WordPress.com Site Helper), and enable the update/blog_stats_debug branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack update/blog_stats_debug
bin/jetpack-downloader test jetpack-mu-wpcom-plugin update/blog_stats_debug

Interested in more tips and information?

  • In your local development environment, use the jetpack rsync command to sync your changes to a WoA dev blog.
  • Read more about our development workflow here: PCYsg-eg0-p2
  • Figure out when your changes will be shipped to customers here: PCYsg-eg5-p2

@github-actions
Copy link
Contributor

github-actions bot commented Dec 5, 2025

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • ✅ Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add a "[Type]" label (Bug, Enhancement, Janitorial, Task).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • ✅ Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!

@dognose24 dognose24 added the [Type] Bug When a feature is broken and / or not performing as intended label Dec 5, 2025
@jp-launch-control
Copy link

jp-launch-control bot commented Dec 5, 2025

Code Coverage Summary

Coverage changed in 1 file.

File Coverage Δ% Δ Uncovered
projects/packages/stats/src/class-wpcom-stats.php 85/130 (65.38%) -1.02% 2 ❤️‍🩹

Full summary · PHP report · JS report

@dognose24 dognose24 changed the title Debug missing Blog Stats post views Improve Post Stats cache handling for invalid or error data Dec 5, 2025
@dognose24 dognose24 requested a review from Copilot December 5, 2025 22:18
@dognose24 dognose24 added [Status] Needs Review This PR is ready for review. and removed [Status] In Progress labels Dec 5, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR improves post stats cache handling by refactoring the cache refresh logic into a dedicated method and preventing invalid data from being cached. The changes address an issue where errors or empty results would be stored in the cache, potentially causing repeated problems on subsequent requests.

Key Changes

  • Extracted cache refresh logic into a new refresh_post_stats_cache() method for better code organization and reusability
  • Added conditional caching that skips storing WP_Error objects and empty results in post meta
  • Updated all cache refresh points in fetch_post_stats() to use the new method consistently

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
projects/packages/stats/src/class-wpcom-stats.php Refactored cache refresh logic into refresh_post_stats_cache() method and added guards to prevent caching errors or empty results
projects/packages/stats/changelog/update-blog_stats_debug Added changelog entry for the changes

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +546 to 555
protected function refresh_post_stats_cache( $endpoint, $args, $post_id, $meta_name ) {
$wpcom_stats = $this->fetch_remote_stats( $endpoint, $args );
update_post_meta( $post_id, $meta_name, array( time() => $wpcom_stats ) );

// Don't write error or empty results to cache.
if ( ! is_wp_error( $wpcom_stats ) && ! empty( $wpcom_stats ) ) {
update_post_meta( $post_id, $meta_name, array( time() => $wpcom_stats ) );
}

return $wpcom_stats;
}
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The new refresh_post_stats_cache method and the updated cache handling logic (preventing caching of errors and empty results) lack test coverage. The existing test file tests/php/WPCOM_Stats_Test.php has comprehensive tests for other methods, but fetch_post_stats and the cache_in_meta parameter of get_post_views are not tested.

Consider adding tests to verify:

  1. Errors are not cached when fetch_remote_stats returns a WP_Error
  2. Empty results are not cached when fetch_remote_stats returns an empty array
  3. Valid results are properly cached with the correct timestamp structure
  4. The method correctly falls back to refreshing when cached data is malformed

Copilot uses AI. Check for mistakes.
Comment on lines +549 to +552
// Don't write error or empty results to cache.
if ( ! is_wp_error( $wpcom_stats ) && ! empty( $wpcom_stats ) ) {
update_post_meta( $post_id, $meta_name, array( time() => $wpcom_stats ) );
}
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

This creates an inconsistency with the fetch_stats method (lines 445-484), which caches both errors and successful responses (see line 466 and 481). The fetch_stats method caches WP_Error objects with the comment "WP_Error or string (JSON encoded object)" on line 454.

Consider aligning the caching behavior between both methods. If errors and empty results should not be cached, the same logic should apply to fetch_stats. Otherwise, if caching errors is intentional (e.g., to prevent repeated failed API calls), both methods should follow the same pattern.

Copilot uses AI. Check for mistakes.
@dognose24 dognose24 requested review from a team, jeherve and kangzj December 5, 2025 22:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Block] Blog Stats [Package] Stats Data [Status] Needs Review This PR is ready for review. [Type] Bug When a feature is broken and / or not performing as intended

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants