Skip to content

Commit 93eb525

Browse files
Alexia-Soareclaude
andauthored
fix: recover the database refresh chain a killed run ends (#1385)
* fix: keep the DB refresh scheduled when Action Scheduler creation fails as_schedule_recurring_action() returns 0 instead of throwing when it cannot store an action. The activation path ignored that return, cleared the WP-Cron fallback anyway, and left the refresh hook with no trigger at all. Nothing recovered it: the recovery hook stood down whenever Action Scheduler was usable, and the migration was gated on the WP-Cron event that had just been deleted, so even a reactivation could fail the same way. Clear the fallback only after re-querying Action Scheduler for the action. Turn the recovery hook into a plain "is anything going to fire this hook" check, which also covers the legacy WP-Cron migration, so the duplicate scheduling code in Visualizer_Module_Upgrade is no longer needed. Two consequences of running that check on every request: - Re-arm WP-Cron only when the event is missing or its interval changed. Re-arming unconditionally pinned it to a past timestamp on every request, so the refresh became due on every cron spawn. - Schedule the action as unique. Action Scheduler creates the next recurrence only after the current one completes, so a concurrent request can arrive while nothing is pending and add a duplicate. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: clear a WP-Cron event left beside the Action Scheduler action Both schedulers fire visualizer_schedule_refresh_db, so a site holding an action and an event refreshes twice per interval. The recovery check counted the action alone as settled and left the event in place. Treat the refresh as settled only when Action Scheduler holds the action and no event fires the same hook beside it. Also from review: reuse the first lookup instead of querying Action Scheduler again when the action already exists, and name the hook and the group once instead of repeating the literals. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test: skip instead of fatal when Action Scheduler is not loaded index.php loads Action Scheduler only when visualizer_can_use_action_scheduler() passes, so a host without wpdb::db_server_info() has none. set_up() called the library unconditionally, which ended the whole suite with a fatal before any test could report. Skip the file instead. Also corrects the WP-Cron comment: the check is missing or different interval, not a stale timestamp. A timestamp criterion would pin the event to the past again, which is what the check exists to prevent. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: recover the refresh chain a killed run ends, and throttle the check Hands-on investigation on the reporting site corrected the premise of #1384. Reactivation did restore the action; the customer was reading WP Crontrol, where the hook correctly no longer appears after the Action Scheduler migration. The real defect is that a run killed mid flight ends the recurring chain for good: Action Scheduler creates the next occurrence inside schedule_next_instance(), which a host kill, fatal or timeout never reaches, and the queue cleaner then marks the action failed with no successor. The per-request check already recovers this. Add the two pieces it was missing: - Hook action_scheduler_ensure_recurring_actions, Action Scheduler's own daily assurance hook, as a floor under the per-request check for sites that serve few requests. - Throttle the per-request check to one run per 300s, recorded in an autoloaded option so a settled site spends no query on it. Action Scheduler needs the same 300s to mark a killed run failed, so a shorter window cannot recover one any sooner. The daily hook ignores the window. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: start a recovered run now, and stop rewriting an autoloaded option Two findings from review. The start time is local midnight derived from gmt_offset. West of UTC that midnight has not arrived yet, so a recovered run was parked up to twelve hours ahead and the charts stayed stale for the rest of the day. Fall back to the previous midnight when the computed one is still in the future. The throttle recorded its timestamp in an autoloaded option, so every window rewrote the alloptions blob and invalidated it for every process. A transient with the window as its expiry is not autoloaded, expires on its own, and keeps the read cached. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test: prove the filter argument order instead of assuming it Review has now questioned the pre_as_schedule_recurring_action argument order twice. The racer records the two arguments it receives and the test asserts their types, so a swap fails loudly instead of silently forwarding the wrong value. Types separate them whatever value the code under test passes. Also from review: guard set_up() on the ActionScheduler classes the tests call statics on, not only the functions, and scope the gmt_offset change to a filter the framework restores. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test: do not depend on plugin_basename() for the lifecycle hook name plugin_basename() resolves differently depending on where the plugin directory is loaded from, so the hook name register_activation_hook() used is not stable across environments. Loading the plugin from outside WP_PLUGIN_DIR registers the full path as the hook name while the test computes the short one, and the activation test then fires a hook nothing listens to and passes vacuously or fails. Call the callback the hook points at instead. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test: say why the Action Scheduler precondition fails instead of skipping A red build on this assertion needs to point somewhere. Absent is skipped in set_up() because some hosts cannot run Action Scheduler; loaded but not initialized means the load order broke, and every other test in the class would then assert nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: do not drop the refresh on an unknown interval or a fractional offset Two findings from review, both on the WP-Cron fallback. wp_schedule_event() refuses a schedule WP-Cron does not know, and the fallback cleared the existing event before asking, so a visualizer_chart_schedule_interval filter returning an unregistered key left the refresh with nothing and the throttle then held the retry off. Fall back to the plugin's own schedule when the filtered key is not registered, which is what get_schedule_interval_seconds() already does for the interval itself. gmt_offset is a number rather than an integer, so the start time could carry a fraction. WP-Cron keys its array by that value, and PHP reports losing precision from wp-includes/cron.php. Cast the start time to an integer. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs: note that tear_down restores hooks, so test filters need no removal Reviewers have read the missing remove_filter() calls as a leak four times across this PR and its pro counterpart. WP_UnitTestCase_Base backs up $wp_filter in set_up() and restores it wholesale in tear_down(). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: record the check window only when a trigger exists The window skips work that is already done, so recording it after an attempt that established no trigger left the site without one until the window expired, with the daily assurance hook a day away. ensure_refresh_db_action() now reports whether the refresh ended up scheduled, and the caller caches only that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: treat a live WP-Cron fallback as scheduled for the check window Where Action Scheduler is present but refuses, the fallback is the trigger, and the previous commit reported that as unscheduled. The window was then never recorded, so every request repeated the whole check and the refused insert. Split the two questions: settled means the refresh sits on the scheduler this site should use, which is what decides whether to act; having a trigger means something will fire the hook at all, which is what decides whether to cache. ensure_refresh_db_action() goes back to returning nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor: read the cron schedules once when scheduling the refresh The key check and the interval lookup each called wp_get_schedules(). Read it once and derive both from the same array, which also makes the one-line helper that did the second lookup unnecessary. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: keep the old WP-Cron event until its replacement is scheduled Changing interval cleared the old event and then scheduled the new one, so a refused schedule left the refresh with nothing. That is the bug this PR fixes on the Action Scheduler path, repeated on the WP-Cron one. Schedule first and remove the old event by its own timestamp afterwards. wp_clear_scheduled_hook() would remove the new event too, since WP-Cron does not dedupe recurring events for a hook. A matching timestamp means the write already replaced the old entry in place, so nothing is removed in that case. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: unschedule the old refresh event without passing its arguments The refresh is scheduled without arguments, so the old event has none to match. Keeps this in step with the Pro plugin, where PHPStan objected to passing the typed-as-array field where a list is expected. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: trim the comments Requested in review: keep the one line that says why, drop the paragraphs. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: type the pending action IDs as numeric strings Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 256bc23 commit 93eb525

4 files changed

Lines changed: 496 additions & 77 deletions

File tree

‎classes/Visualizer/Module/Setup.php‎

Lines changed: 117 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,26 @@ class Visualizer_Module_Setup extends Visualizer_Module {
3131

3232
const NAME = __CLASS__;
3333

34+
/**
35+
* Hook that refreshes database charts.
36+
*/
37+
const REFRESH_DB_HOOK = 'visualizer_schedule_refresh_db';
38+
39+
/**
40+
* Action Scheduler group that owns the refresh.
41+
*/
42+
const REFRESH_DB_GROUP = 'visualizer';
43+
44+
/**
45+
* Marks the refresh trigger as checked recently.
46+
*/
47+
const REFRESH_DB_CHECK_TRANSIENT = 'visualizer-refresh-db-checked';
48+
49+
/**
50+
* Seconds a check stays valid; matches Action Scheduler's timeout for a killed run.
51+
*/
52+
const REFRESH_DB_CHECK_WINDOW = 300;
53+
3454
/**
3555
* Constructor.
3656
*
@@ -44,8 +64,9 @@ public function __construct( Visualizer_Plugin $plugin ) {
4464

4565
register_activation_hook( VISUALIZER_BASEFILE, array( $this, 'activate' ) );
4666
register_deactivation_hook( VISUALIZER_BASEFILE, array( $this, 'deactivate' ) );
47-
$this->_addAction( 'visualizer_schedule_refresh_db', 'refreshDbChart' );
67+
$this->_addAction( self::REFRESH_DB_HOOK, 'refreshDbChart' );
4868
$this->_addAction( 'init', 'maybe_reschedule_refresh_db' );
69+
$this->_addAction( 'action_scheduler_ensure_recurring_actions', 'ensure_refresh_db_action' );
4970
$this->_addFilter( 'visualizer_schedule_refresh_chart', 'refresh_db_for_chart', 10, 3 );
5071

5172
$this->_addAction( 'admin_init', 'adminInit' );
@@ -485,11 +506,24 @@ public function custom_cron_schedules( $schedules ) {
485506
* Schedule the recurring DB refresh action.
486507
*/
487508
private function schedule_refresh_db_action(): void {
488-
$hook = 'visualizer_schedule_refresh_db';
489-
$group = 'visualizer';
509+
$hook = self::REFRESH_DB_HOOK;
510+
$group = self::REFRESH_DB_GROUP;
511+
$schedules = wp_get_schedules();
490512
$interval_key = apply_filters( 'visualizer_chart_schedule_interval', 'visualizer_ten_minutes' );
491-
$interval = $this->get_schedule_interval_seconds( $interval_key );
492-
$timestamp = strtotime( 'midnight' ) - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS;
513+
514+
// wp_schedule_event() refuses an unregistered schedule.
515+
if ( ! isset( $schedules[ $interval_key ]['interval'] ) ) {
516+
$interval_key = 'visualizer_ten_minutes';
517+
}
518+
519+
$interval = isset( $schedules[ $interval_key ]['interval'] ) ? (int) $schedules[ $interval_key ]['interval'] : 600;
520+
// gmt_offset can be fractional, and WP-Cron keys its array by this value.
521+
$timestamp = (int) ( strtotime( 'midnight' ) - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
522+
523+
// West of UTC that midnight is still ahead; start from the previous one.
524+
if ( $timestamp > time() ) {
525+
$timestamp -= DAY_IN_SECONDS;
526+
}
493527

494528
if (
495529
visualizer_can_use_action_scheduler()
@@ -498,63 +532,111 @@ private function schedule_refresh_db_action(): void {
498532
) {
499533
$next = as_next_scheduled_action( $hook, array(), $group );
500534
if ( false === $next ) {
501-
as_schedule_recurring_action( $timestamp, $interval, $hook, array(), $group );
535+
// Unique: a concurrent request can arrive while nothing is pending.
536+
as_schedule_recurring_action( $timestamp, $interval, $hook, array(), $group, true );
537+
538+
// Returns 0 on failure, so ask the store.
539+
$next = as_next_scheduled_action( $hook, array(), $group );
540+
}
541+
542+
// Drop the WP-Cron fallback only once the action exists.
543+
if ( false !== $next ) {
544+
wp_clear_scheduled_hook( $hook );
545+
return;
502546
}
503-
wp_clear_scheduled_hook( $hook );
547+
}
548+
549+
// Re-arming a live event would pin it to a past timestamp and keep it due.
550+
$event = wp_get_scheduled_event( $hook );
551+
if ( $event && $event->schedule === $interval_key ) {
504552
return;
505553
}
506554

507-
wp_clear_scheduled_hook( $hook );
508-
wp_schedule_event( $timestamp, $interval_key, $hook );
555+
// Schedule first so a refused replacement keeps the old event, then remove the old one
556+
// by its timestamp: wp_clear_scheduled_hook() would take the new one too.
557+
if ( false === wp_schedule_event( $timestamp, $interval_key, $hook ) ) {
558+
return;
559+
}
560+
561+
// A matching timestamp was already overwritten in place.
562+
if ( $event && $event->timestamp !== $timestamp ) {
563+
wp_unschedule_event( $event->timestamp, $hook );
564+
}
509565
}
510566

511567
/**
512-
* Keep the DB refresh scheduled when Action Scheduler is not available.
513-
*
514-
* The migration to Action Scheduler clears the WP-Cron event, so a site that
515-
* already migrated and then lost the library would have nothing left running
516-
* the refresh. Re-arms WP-Cron in that case; no-op whenever the library is up.
568+
* Check once per window, on init, that something still fires the refresh.
517569
*/
518570
public function maybe_reschedule_refresh_db(): void {
571+
if ( get_transient( self::REFRESH_DB_CHECK_TRANSIENT ) ) {
572+
return;
573+
}
574+
575+
$this->ensure_refresh_db_action();
576+
577+
// Cache only a check that left a trigger; a failed one retries next request.
578+
if ( $this->has_refresh_db_trigger() ) {
579+
set_transient( self::REFRESH_DB_CHECK_TRANSIENT, 1, self::REFRESH_DB_CHECK_WINDOW );
580+
}
581+
}
582+
583+
/**
584+
* Keep the DB refresh scheduled.
585+
*
586+
* A killed run never reaches schedule_next_instance(), so Action Scheduler's chain ends there.
587+
*/
588+
public function ensure_refresh_db_action(): void {
589+
if ( ! $this->refresh_db_is_settled() ) {
590+
$this->schedule_refresh_db_action();
591+
}
592+
}
593+
594+
/**
595+
* Whether the refresh is on Action Scheduler with no WP-Cron event beside it.
596+
*
597+
* @return bool
598+
*/
599+
private function refresh_db_is_settled(): bool {
600+
$hook = self::REFRESH_DB_HOOK;
601+
519602
if (
520603
visualizer_can_use_action_scheduler()
521604
&& function_exists( 'as_next_scheduled_action' )
522605
&& function_exists( 'as_schedule_recurring_action' )
523606
) {
524-
return;
607+
return false !== as_next_scheduled_action( $hook, array(), self::REFRESH_DB_GROUP )
608+
&& ! wp_next_scheduled( $hook );
525609
}
526610

527-
if ( wp_next_scheduled( 'visualizer_schedule_refresh_db' ) ) {
528-
return;
611+
return (bool) wp_next_scheduled( $hook );
612+
}
613+
614+
/**
615+
* Whether anything will fire the refresh hook again.
616+
*
617+
* @return bool
618+
*/
619+
private function has_refresh_db_trigger(): bool {
620+
$hook = self::REFRESH_DB_HOOK;
621+
622+
if ( visualizer_can_use_action_scheduler() && function_exists( 'as_next_scheduled_action' ) ) {
623+
if ( false !== as_next_scheduled_action( $hook, array(), self::REFRESH_DB_GROUP ) ) {
624+
return true;
625+
}
529626
}
530627

531-
$this->schedule_refresh_db_action();
628+
return (bool) wp_next_scheduled( $hook );
532629
}
533630

534631
/**
535632
* Unschedule the recurring DB refresh action.
536633
*/
537634
private function unschedule_refresh_db_action(): void {
538-
$hook = 'visualizer_schedule_refresh_db';
539-
$group = 'visualizer';
635+
$hook = self::REFRESH_DB_HOOK;
636+
$group = self::REFRESH_DB_GROUP;
540637
if ( function_exists( 'as_unschedule_all_actions' ) ) {
541638
as_unschedule_all_actions( $hook, array(), $group );
542639
}
543640
wp_clear_scheduled_hook( $hook );
544641
}
545-
546-
/**
547-
* Resolve a cron schedule key to seconds.
548-
*
549-
* @param string $interval_key Cron schedule key.
550-
* @return int Interval in seconds.
551-
*/
552-
private function get_schedule_interval_seconds( $interval_key ) {
553-
$schedules = wp_get_schedules();
554-
if ( isset( $schedules[ $interval_key ]['interval'] ) ) {
555-
return (int) $schedules[ $interval_key ]['interval'];
556-
}
557-
558-
return 600;
559-
}
560642
}

‎classes/Visualizer/Module/Upgrade.php‎

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,6 @@ public static function upgrade() {
2424
$upgraded = true;
2525
}
2626

27-
if ( wp_next_scheduled( 'visualizer_schedule_refresh_db' ) ) {
28-
self::migrate_action_scheduler();
29-
$upgraded = true;
30-
}
31-
3227
if ( ! $upgraded ) {
3328
return;
3429
}
@@ -79,41 +74,4 @@ private static function makeAllTableChartsTabular() {
7974
);
8075
// phpcs:enable WordPress.DB.PreparedSQL.NotPrepared
8176
}
82-
83-
/**
84-
* Migrate recurring WP-Cron jobs to Action Scheduler.
85-
*/
86-
private static function migrate_action_scheduler(): void {
87-
if ( ! function_exists( 'as_schedule_recurring_action' ) || ! function_exists( 'as_next_scheduled_action' ) ) {
88-
return;
89-
}
90-
91-
$hook = 'visualizer_schedule_refresh_db';
92-
$group = 'visualizer';
93-
$interval_key = apply_filters( 'visualizer_chart_schedule_interval', 'visualizer_ten_minutes' );
94-
$interval = self::get_schedule_interval_seconds( $interval_key );
95-
$timestamp = strtotime( 'midnight' ) - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS;
96-
97-
$next = as_next_scheduled_action( $hook, array(), $group );
98-
if ( false === $next ) {
99-
as_schedule_recurring_action( $timestamp, $interval, $hook, array(), $group );
100-
}
101-
102-
wp_clear_scheduled_hook( $hook );
103-
}
104-
105-
/**
106-
* Resolve a cron schedule key to seconds.
107-
*
108-
* @param string $interval_key Cron schedule key.
109-
* @return int Interval in seconds.
110-
*/
111-
private static function get_schedule_interval_seconds( $interval_key ) {
112-
$schedules = wp_get_schedules();
113-
if ( isset( $schedules[ $interval_key ]['interval'] ) ) {
114-
return (int) $schedules[ $interval_key ]['interval'];
115-
}
116-
117-
return 600;
118-
}
11977
}

0 commit comments

Comments
 (0)