table = $wpdb->prefix . 'aipt_job_products'; } /** * Schedule the daily cleanup cron job (activation hook entry). * * @return bool Whether scheduling succeeded. */ public function schedule(): bool { try { if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { return false !== wp_schedule_event( time(), 'daily', self::CRON_HOOK ); } return true; } catch ( \Exception $e ) { Logger::warn( 'cron', 'Cleanup schedule failed', array( 'cleaner' => 'JobResultCleaner', 'error' => $e->getMessage() ) ); return false; } } /** * Re-arm the cleanup schedule if it has been lost (admin_init self-heal). * * Returns nothing because it is an action callback, so a schedule that * could not be made is logged here; the next admin page load tries again. * * @return void */ public static function ensure_scheduled(): void { try { if ( wp_next_scheduled( self::CRON_HOOK ) ) { return; } $scheduled = wp_schedule_event( time() + MINUTE_IN_SECONDS, 'daily', self::CRON_HOOK ); if ( false === $scheduled || is_wp_error( $scheduled ) ) { Logger::warn( 'cron', 'Cleanup schedule failed', array( 'cleaner' => 'JobResultCleaner' ) ); } } catch ( \Exception $e ) { Logger::warn( 'cron', 'Cleanup schedule failed', array( 'cleaner' => 'JobResultCleaner', 'error' => $e->getMessage() ) ); } } /** * Resolve the active retention threshold in days. * * @return int At least 1; a filter value below 1 clamps to 1. */ private function retention_days(): int { $value = (int) apply_filters( 'aipt_job_results_retention_days', self::RETENTION_DAYS ); return max( 1, $value ); } /** * Reduce a stored result to what the job screens read. * * Readers of `aipt_job_products.result`, all through json_decode: * - JobReadTrait::get_job_products() (line 651) feeds * blueprintItemSummary() (720) and isWaitingInReviewMarker() (732) for * each listed product: the needs review pill, the blueprint name, the * held back message and the "Already in To review" pill. * - JobReadTrait::countJobResultSummaries() (843) runs the * same two helpers over the whole job for needsReviewCount and * waitingInReviewCount. * - GetJobStatusTool::skippedAlreadyInReview() (line 113) reads only that * waitingInReviewCount from the products route. * - BlueprintIntegration::heldBackMessage() (line 542) takes the first * non-empty eligibility.blockers[].message, then falls back on * eligibility.requiresReview. * * Kept, and nothing else: executionPath ("blueprint" only), * eligibility.requiresReview, eligibility.canApply (only when present, as a * missing key and a false value read differently), the first non-empty * blocker message as the single blocker, blueprint.id, .name and .revision * (when set), and the skip marker (skipped true with reason * waiting_in_review). Any change to what those readers decode must change * this method too; JobResultCleanerTest compares both forms through the * readers' own code. * * @param string $raw Stored result JSON. * @return string|null The compacted JSON, or null when the result is not a * JSON array and no reader can use it. */ public static function compact( string $raw ): ?string { $decoded = json_decode( $raw, true ); if ( ! is_array( $decoded ) ) { return null; } $compacted = array( 'compacted' => true ); if ( true === ( $decoded['skipped'] ?? null ) && 'waiting_in_review' === ( $decoded['reason'] ?? null ) ) { $compacted['skipped'] = true; $compacted['reason'] = 'waiting_in_review'; } if ( 'blueprint' === (string) ( $decoded['executionPath'] ?? '' ) ) { $compacted['executionPath'] = 'blueprint'; $source = is_array( $decoded['eligibility'] ?? null ) ? $decoded['eligibility'] : array(); $eligibility = array( 'requiresReview' => ! empty( $source['requiresReview'] ) ); if ( array_key_exists( 'canApply', $source ) ) { $eligibility['canApply'] = ! empty( $source['canApply'] ); } $blockers = isset( $source['blockers'] ) && is_array( $source['blockers'] ) ? $source['blockers'] : array(); foreach ( $blockers as $blocker ) { if ( is_array( $blocker ) && '' !== (string) ( $blocker['message'] ?? '' ) ) { $eligibility['blockers'] = array( array( 'message' => (string) $blocker['message'] ) ); break; } } $compacted['eligibility'] = $eligibility; $source = is_array( $decoded['blueprint'] ?? null ) ? $decoded['blueprint'] : array(); $blueprint = array(); foreach ( array( 'id', 'name', 'revision' ) as $key ) { if ( isset( $source[ $key ] ) ) { $blueprint[ $key ] = $source[ $key ]; } } $compacted['blueprint'] = $blueprint; } $json = wp_json_encode( $compacted ); return is_string( $json ) ? $json : null; } /** * Compact the stored result of processed rows older than the retention window. * * @return int|false Number of rows examined (across chunks) or false on a * database-level error. */ public function clean_old_results() { global $wpdb; if ( get_transient( self::LOCK_TRANSIENT ) ) { return 0; } if ( ! set_transient( self::LOCK_TRANSIENT, time(), self::LOCK_TTL_SECONDS ) ) { Logger::error( 'cron', 'Cleanup lock could not be taken', array( 'cleaner' => 'JobResultCleaner' ) ); return 0; } $examined = 0; $last_id = 0; try { $cutoff_date = gmdate( 'Y-m-d H:i:s', strtotime( '-' . $this->retention_days() . ' days' ) ); $not_marked = $wpdb->esc_like( self::COMPACTED_PREFIX ) . '%'; while ( $examined < self::MAX_ROWS_PER_RUN ) { $select = $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "SELECT id, result FROM {$this->table} WHERE id > %d AND status IN ('completed', 'failed', 'applied', 'rejected') AND processed_at < %s AND result IS NOT NULL AND CHAR_LENGTH(result) > %d AND result NOT LIKE %s ORDER BY id ASC LIMIT %d", $last_id, $cutoff_date, self::MIN_COMPACTABLE_LENGTH, $not_marked, self::CHUNK_SIZE ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( $select, ARRAY_A ); if ( ! is_array( $rows ) || '' !== (string) $wpdb->last_error ) { Logger::error( 'cron', 'Cleanup read failed', array( 'cleaner' => 'JobResultCleaner', 'error' => $wpdb->last_error ) ); return false; } if ( array() === $rows ) { break; } foreach ( $rows as $row ) { $last_id = (int) $row['id']; ++$examined; $compacted = self::compact( (string) $row['result'] ); if ( null === $compacted ) { $update = $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "UPDATE {$this->table} SET result = NULL WHERE id = %d AND status IN ('completed', 'failed', 'applied', 'rejected') AND processed_at < %s", $last_id, $cutoff_date ); } else { $update = $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "UPDATE {$this->table} SET result = %s WHERE id = %d AND status IN ('completed', 'failed', 'applied', 'rejected') AND processed_at < %s", $compacted, $last_id, $cutoff_date ); } // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching if ( false === $wpdb->query( $update ) ) { Logger::error( 'cron', 'Cleanup update failed', array( 'cleaner' => 'JobResultCleaner', 'error' => $wpdb->last_error ) ); return false; } } } if ( $examined >= self::MAX_ROWS_PER_RUN ) { Logger::debug( 'cron', 'Cleanup row cap reached, backlog continues next tick', array( 'cleaner' => 'JobResultCleaner', 'count' => self::MAX_ROWS_PER_RUN ) ); } return $examined; } catch ( \Exception $e ) { Logger::error( 'cron', 'Cleanup threw', array( 'cleaner' => 'JobResultCleaner', 'error' => $e->getMessage() ) ); return false; } finally { delete_transient( self::LOCK_TRANSIENT ); } } /** * Static cron callback. */ public static function cron_callback(): void { try { $cleaner = new self(); $cleaner->clean_old_results(); } catch ( \Throwable $e ) { Logger::error( 'cron', 'Job result cleanup failed', array( 'error' => $e->getMessage() ) ); } } }