Skip to content

Feature/8103 add settings changes detection#8140

Open
Miraeld wants to merge 11 commits intofeature/ri-recommendationsfrom
feature/8103-add-settings-changes-detection
Open

Feature/8103 add settings changes detection#8140
Miraeld wants to merge 11 commits intofeature/ri-recommendationsfrom
feature/8103-add-settings-changes-detection

Conversation

@Miraeld
Copy link
Contributor

@Miraeld Miraeld commented Mar 10, 2026

Description

Fixes #8103
This pull request introduces a new mechanism to automatically refresh performance recommendations when relevant WP Rocket settings change. It ensures that recommendations are only fetched when necessary, based on changes to key options or metrics, and adds robust unit and integration tests for this logic. The most important changes are as follows:

Type of change

  • New feature (non-breaking change which adds functionality).

Detailed scenario

What was tested

Automated Tests (✅ Passing):

  • Unit tests for SettingsSubscriber::maybe_fetch_after_settings_change() - 8 scenarios covering all status conditions (pending, loading, completed, failed), relevant vs irrelevant changes, and hash-based optimization
  • Unit tests for SettingsSubscriber::get_subscribed_events() - Verifies hook registration with correct parameters
  • Unit tests for DataManager::has_required_metrics() - 6 scenarios covering all core metrics (LCP, TTFB, CLS, TBT) validation
  • Integration tests for settings change detection with WordPress hooks and transient operations

Manual Tests (Recommended):

  1. Relevant Setting Change Triggers Fetch - Toggle "Minify CSS" → Save → Verify new recommendations fetched
  2. Irrelevant Setting Change Does NOT Trigger - Change "Cache Lifespan" → Save → Verify no fetch occurs
  3. No Fetch When Status Pending - Clear recommendations transient → Change setting → No fetch until status is completed
  4. Multiple Settings Changed - Toggle multiple options at once → Single fetch triggered
  5. Hash Unchanged Prevention - Save same settings twice → Second save doesn't trigger redundant fetch

How to test

Prerequisites:

  1. Enable Rocket Insights with active license
  2. Ensure Global Score is completed (status = "completed") - Visit Dashboard → Rocket Insights, test at least one URL
  3. Optional: Enable WP_DEBUG_LOG to monitor log entries in /wp-content/debug.log

Test 1: Relevant Setting Change Triggers Fetch

Steps:

  1. Go to Settings → WP Rocket → File Optimization
  2. Toggle Minify CSS files (OFF → ON or ON → OFF)
  3. Click Save Changes

Expected:

  • Settings save successfully
  • New recommendations are fetched from API
  • Transient wpr_ri_recommendations updated with new metrics_hash
  • Log shows: "Recommendations: Relevant settings changed, fetching new recommendations"

Test 2: Irrelevant Setting Change Does NOT Trigger Fetch

Steps:

  1. Go to Settings → WP Rocket → Advanced Rules
  2. Change Cache Lifespan (e.g., 10h → 20h)
  3. Click Save Changes

Expected:

  • Settings save successfully
  • NO fetch occurs
  • Log shows: "Recommendations: Settings changed but none affect recommendations"

Test 3: Multiple Relevant Settings at Once

Steps:

  1. Go to Settings → WP Rocket → File Optimization
  2. Change multiple settings: Enable Minify CSS, Minify JavaScript, Combine JavaScript
  3. Click Save Changes

Expected:

  • Single fetch triggered (not multiple)
  • New recommendations reflect all changes

Monitored Settings (21 total):

  • Minify CSS/JS, Combine CSS/JS, Defer JS, Delay JS, Async CSS, Critical CSS, Remove Unused CSS
  • LazyLoad (Images, Iframes, YouTube), Image Dimensions
  • CDN, Mobile Cache, Cache Logged Users, WebP Cache
  • Manual Preload, Sitemap Preload, Heartbeat Control, Google Fonts

Verification Methods:

# Check transient via WP-CLI
wp transient get wpr_ri_recommendations

# Check for metrics_hash field
wp transient get wpr_ri_recommendations | jq .metrics_hash

# Monitor logs (if WP_DEBUG_LOG enabled)
tail -f wp-content/debug.log | grep "Recommendations:"

Affected Features & Quality Assurance Scope

Primary Feature:

  • Rocket Insights → Recommendations System
  • Settings change detection and automatic recommendations refresh

Technical description

Documentation

Feature: Automatic Recommendations Refresh on Settings Change

  • Added a new SettingsSubscriber class that listens for changes to WP Rocket settings and triggers a recommendations refresh only if relevant settings are changed and the underlying metrics hash differs, preventing unnecessary API calls.
  • Registered the new subscriber in the service provider and plugin initialization to ensure it is loaded and active in the application lifecycle. [1] [2] [3] [4]

Enhancement: Metrics and Hash Validation

  • Added methods to DataManager for checking if required metrics exist and for determining if recommendations should be fetched, based on a hash of current metrics and enabled options. This helps avoid redundant recommendation fetches.
  • When saving recommendations, now includes the metrics hash in the cached data for accurate comparison on future settings changes. (Fb9cb8f5L261R345)

Testing: Unit, Fixture, and Integration Coverage

  • Added fixture and unit tests for has_required_metrics in DataManager, covering all edge cases of metric presence. [1] [2]
  • Added fixture, unit, and integration tests for the new subscriber’s logic, ensuring recommendations are only fetched when appropriate and that the event subscription is correct. [1] [2] [3]

Mandatory Checklist

Code validation

  • I validated all the Acceptance Criteria. If possible, provide screenshots or videos.
  • I triggered all changed lines of code at least once without new errors/warnings/notices.
  • I implemented built-in tests to cover the new/changed code.

Code style

  • I wrote a self-explanatory code about what it does.
  • I protected entry points against unexpected inputs.
  • I did not introduce unnecessary complexity.
  • Output messages (errors, notices, logs) are explicit enough for users to understand the issue and are actionnable.

Miraeld added 4 commits March 10, 2026 02:55
- Create SettingsSubscriber to monitor WP Rocket settings changes
- Subscribe to rocket_after_save_options hook
- Detect relevant settings changes (minify, lazyload, CDN, etc.)
- Only fetch recommendations when status is completed/failed
- Add has_required_metrics() method to DataManager
- Add should_fetch_recommendations() method with hash comparison
- Add calculate_metrics_hash() to prevent redundant fetches
- Update save_recommendations() to store metrics hash

Fixes #8103
- Add RecommendationsSettingsSubscriber to use statement
- Register ri_recommendations_settings_subscriber in ServiceProvider
- Add to $provides array for DI container
- Register subscriber in Plugin.php init_valid_key_subscribers()

Part of #8103
- Add MaybeFetchAfterSettingsChangeTest with 8 test scenarios
- Add GetSubscribedEventsTest for hook verification
- Add HasRequiredMetricsTest for metrics validation
- Test status conditions (pending, loading, completed, failed)
- Test relevant vs irrelevant settings changes
- Test hash comparison to prevent redundant fetches
- Add comprehensive fixtures for all test cases

Part of #8103
- Add MaybeFetchAfterSettingsChangeTest for WordPress hook integration
- Test rocket_after_save_options action trigger
- Test transient operations with real WordPress functions
- Test scenarios with completed/failed/pending statuses
- Verify fetch triggered only when conditions met
- Mark tests with @group RocketInsights and @group AdminOnly

Part of #8103
@Miraeld Miraeld linked an issue Mar 10, 2026 that may be closed by this pull request
12 tasks
@Miraeld Miraeld requested review from a team and Copilot March 10, 2026 02:12
@Miraeld Miraeld self-assigned this Mar 10, 2026
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

Adds an automatic “refresh recommendations on relevant WP Rocket settings changes” mechanism for Rocket Insights, using a metrics/options hash to avoid unnecessary API fetches, and introduces new unit/integration test coverage for the decision logic.

Changes:

  • Introduces a new Rocket Insights Recommendations SettingsSubscriber intended to react to settings saves and conditionally trigger a recommendations fetch.
  • Extends Recommendations\DataManager with required-metrics validation plus hash-based “should fetch” logic, and persists metrics_hash into the cached recommendations payload.
  • Adds unit + integration tests and fixtures covering settings-change detection and required-metrics checks.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
inc/Plugin.php Registers the new recommendations settings subscriber in the common subscriber list.
inc/Engine/Admin/RocketInsights/ServiceProvider.php Registers the new subscriber service in the Rocket Insights service provider.
inc/Engine/Admin/RocketInsights/Recommendations/SettingsSubscriber.php Implements settings-change detection and conditional fetch trigger.
inc/Engine/Admin/RocketInsights/Recommendations/DataManager.php Adds required-metrics check, hash computation/compare, and stores metrics_hash in cache.
tests/Unit/.../SettingsSubscriber/MaybeFetchAfterSettingsChangeTest.php Unit tests for the subscriber’s fetch decision logic.
tests/Unit/.../SettingsSubscriber/GetSubscribedEventsTest.php Unit test for subscriber hook registration.
tests/Unit/.../DataManager/HasRequiredMetricsTest.php Unit tests for required-metrics validation.
tests/Integration/.../SettingsSubscriber/MaybeFetchAfterSettingsChangeTest.php Integration test intended to validate hook-triggered behavior.
tests/Fixtures/.../SettingsSubscriber/MaybeFetchAfterSettingsChangeTest.php Fixture data for settings-change scenarios.
tests/Fixtures/.../DataManager/HasRequiredMetricsTest.php Fixture data for required-metrics scenarios.

@codacy-production
Copy link

codacy-production bot commented Mar 10, 2026

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
+0.00% (target: -0.10%) 89.66% (target: 50.00%)
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (89d01c2) 42866 19690 45.93%
Head commit (b5547fe) 42868 (+2) 19693 (+3) 45.94% (+0.00%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#8140) 29 26 89.66%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

Miraeld added 3 commits March 10, 2026 10:15
- Change SettingsSubscriber to use update_option_wp_rocket_settings instead of custom hook
- Add TRACKED_OPTIONS constant in DataManager as single source of truth
- Add get_tracked_option_keys() method to share option keys across classes
- Update get_enabled_options() to use constant instead of duplicate array
- Update has_relevant_changes() to use shared method from DataManager
- Remove custom rocket_after_save_options action from options.php

Addresses review feedback on PR #8140
- Update GetSubscribedEventsTest to check for update_option_wp_rocket_settings
- Update MaybeFetchAfterSettingsChangeTest to use WordPress native hook
- Remove unnecessary admin context setup from integration test

All tests passing: 16 unit tests, 2 integration tests
- Removed has_required_metrics() method
- Removed should_fetch_recommendations() method
- Removed calculate_metrics_hash() method
- Removed metrics_hash tracking from save_recommendations()
- Simplified SettingsSubscriber to not check hash (Task 2.1 responsibility)
- Deleted HasRequiredMetricsTest and related fixtures
- Updated MaybeFetchAfterSettingsChangeTest to reflect simplified logic

These methods will be provided by PR #8131 (Task 2.1) to avoid duplication.
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.

[RI Recommendations] Task 2.3: Add Settings Change Detection

3 participants