enqueue_generation( $object_id ); } /** * Add or refresh one pending object and return its generation token. * * @param int $object_id WordPress object ID. */ public function enqueue_generation( int $object_id ): string { $object_id = absint( $object_id ); if ( 0 >= $object_id ) { return ''; } $this->migrate_legacy_option(); $generation = $this->queue_state(); if ( ! $this->replace_queue_generation( $object_id, $generation ) ) { return ''; } return $generation; } /** * Add one pending object only when no queued generation already exists. * * Stale-row discovery uses this path so it cannot replace a failed item's * retry state or a newer save/delete generation. * * @param int $object_id WordPress object ID. */ public function enqueue_if_absent( int $object_id ): bool { $object_id = absint( $object_id ); if ( 0 >= $object_id ) { return false; } $this->migrate_legacy_option(); return $this->add_queue_generation_if_absent( $object_id, $this->queue_state() ); } /** * Claim a bounded batch with per-object expiring leases. * * @param int $limit Maximum rows to claim. * @return list */ public function claim( int $limit ): array { $this->migrate_legacy_option(); $limit = max( 1, min( self::MAX_CLAIM_LIMIT, $limit ) ); $claimed = array(); foreach ( $this->pending_object_ids( $limit ) as $object_id ) { $queue_token = $this->read_queue_generation( $object_id ); if ( '' === $queue_token ) { continue; } $state = $this->parse_queue_state( $queue_token ); if ( $state['available_at'] > time() ) { continue; } $lock_token = $this->claim_lock( $object_id ); if ( '' === $lock_token ) { continue; } $queue_token = $this->read_queue_generation( $object_id ); if ( '' === $queue_token ) { $this->release_claim( $object_id, $lock_token ); continue; } $state = $this->parse_queue_state( $queue_token ); if ( $state['available_at'] > time() ) { $this->release_claim( $object_id, $lock_token ); continue; } $claimed[] = array( 'object_id' => $object_id, 'queue_token' => $queue_token, 'lock_token' => $lock_token, 'action' => $state['action'], ); } return $claimed; } /** * Acknowledge one successful generation without deleting a newer enqueue. * * @param int $object_id WordPress object ID. * @param string $queue_token Claimed queue generation. * @param string $lock_token Claimed lease token. */ public function acknowledge( int $object_id, string $queue_token, string $lock_token ): bool { if ( '' === $queue_token ) { return false; } $transition_token = $this->begin_owned_transition( $object_id, $lock_token ); if ( '' === $transition_token ) { return false; } $deleted = $this->clear_generation( $object_id, $queue_token ); $this->delete_option_if_value( $this->lock_key( $object_id ), $transition_token ); return $deleted; } /** * Remove exactly one unclaimed queue generation. * * @param int $object_id WordPress object ID. * @param string $queue_token Expected queue generation. */ public function clear_generation( int $object_id, string $queue_token ): bool { return '' !== $queue_token && $this->delete_option_if_value( $this->queue_key( $object_id ), $queue_token ); } /** * Release a failed item with bounded exponential backoff. * * @param int $object_id WordPress object ID. * @param string $queue_token Claimed queue generation. * @param string $lock_token Claimed lease token. */ public function retry( int $object_id, string $queue_token, string $lock_token ): bool { if ( '' === $queue_token ) { return false; } $transition_token = $this->begin_owned_transition( $object_id, $lock_token ); if ( '' === $transition_token ) { return false; } $state = $this->parse_queue_state( $queue_token ); $attempts = $state['attempts'] + 1; $delay = min( self::MAX_RETRY_DELAY, 30 * ( 2 ** min( 6, $attempts - 1 ) ) ); $new_state = $this->queue_state( $attempts, time() + $delay, $state['action'] ); $queue_key = $this->queue_key( $object_id ); $lock_key = $this->lock_key( $object_id ); $updated = $this->update_option_if_value( $queue_key, $queue_token, $new_state ); $this->delete_option_if_value( $lock_key, $transition_token ); return $updated; } /** * Release an unstarted claim while preserving its queued generation. * * @param int $object_id WordPress object ID. * @param string $lock_token Claimed lease token. */ public function release_claim( int $object_id, string $lock_token ): void { $this->delete_option_if_value( $this->lock_key( $object_id ), $lock_token ); } /** * Atomically replace pending work with a durable deletion tombstone. * * @param int $object_id WordPress object ID. */ public function invalidate_for_delete( int $object_id ): string { $object_id = absint( $object_id ); if ( 0 >= $object_id ) { return ''; } $tombstone = $this->queue_state( 0, 0, 'delete' ); if ( ! $this->replace_queue_generation( $object_id, $tombstone ) ) { return ''; } return $tombstone; } /** * Return the current queue generation and action for one object. * * @param int $object_id WordPress object ID. * @return array{queue_token: string, action: string} */ public function current_generation( int $object_id ): array { $queue_token = $this->read_queue_generation( $object_id ); $state = $this->parse_queue_state( $queue_token ); return array( 'queue_token' => $queue_token, 'action' => $state['action'], ); } /** * Return the durable pending row count. */ public function pending_count(): int { $this->migrate_legacy_option(); if ( $this->uses_test_options() ) { return count( array_filter( $this->test_option_names( self::QUEUE_PREFIX ), static fn ( string $name ): bool => self::LEGACY_OPTION !== $name ) ); } global $wpdb; $like = $wpdb->esc_like( self::QUEUE_PREFIX ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Bounded count over non-autoloaded plugin-owned queue options. return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE %s AND option_name <> %s", $like, self::LEGACY_OPTION ) ); } /** * Delete all queue and lease rows during uninstall. */ public static function delete_all(): void { if ( isset( $GLOBALS['aculect_ai_companion_test_options'] ) && is_array( $GLOBALS['aculect_ai_companion_test_options'] ) ) { foreach ( array_keys( $GLOBALS['aculect_ai_companion_test_options'] ) as $option_name ) { if ( self::is_owned_option_name( (string) $option_name ) ) { unset( $GLOBALS['aculect_ai_companion_test_options'][ $option_name ] ); } } return; } global $wpdb; $queue_like = $wpdb->esc_like( self::QUEUE_PREFIX ) . '%'; $lock_like = $wpdb->esc_like( self::LOCK_PREFIX ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Capture plugin-owned keys so persistent option-cache entries can be invalidated after uninstall. $owned_option_names = (array) $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name IN (%s, %s) OR option_name LIKE %s OR option_name LIKE %s", self::LEGACY_OPTION, self::CURSOR_OPTION, $queue_like, $lock_like ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Uninstall removes only plugin-owned queue options. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name IN (%s, %s) OR option_name LIKE %s OR option_name LIKE %s", self::LEGACY_OPTION, self::CURSOR_OPTION, $queue_like, $lock_like ) ); if ( function_exists( 'wp_cache_delete' ) ) { foreach ( $owned_option_names as $option_name ) { wp_cache_delete( (string) $option_name, 'options' ); } } } /** * Return bounded pending object IDs in stable option order. * * @param int $limit Maximum IDs. * @return list */ private function pending_object_ids( int $limit ): array { $cursor = (string) get_option( self::CURSOR_OPTION, '' ); $names = $this->option_names_after( $cursor, $limit ); if ( count( $names ) < $limit && '' !== $cursor ) { $names = array_values( array_unique( array_merge( $names, $this->option_names_after( '', $limit - count( $names ), $cursor ) ) ) ); } if ( array() !== $names ) { update_option( self::CURSOR_OPTION, (string) end( $names ), false ); } $ids = array_map( static fn ( string $name ): int => absint( substr( $name, strlen( self::QUEUE_PREFIX ) ) ), array_map( 'strval', $names ) ); return array_values( array_filter( $ids ) ); } /** * Return queue option names after one stable cursor. * * @param string $cursor Last visited option name. * @param int $limit Maximum names. * @param string $upper_bound Optional inclusive wrap boundary. * @return list */ private function option_names_after( string $cursor, int $limit, string $upper_bound = '' ): array { if ( $this->uses_test_options() ) { return array_slice( array_values( array_filter( $this->test_option_names( self::QUEUE_PREFIX ), static fn ( string $name ): bool => self::LEGACY_OPTION !== $name && $name > $cursor && ( '' === $upper_bound || $name <= $upper_bound ) ) ), 0, $limit ); } global $wpdb; $like = $wpdb->esc_like( self::QUEUE_PREFIX ) . '%'; if ( '' === $upper_bound ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Core options table is trusted; values are prepared and keyset pagination is bounded. $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND option_name <> %s AND option_name > %s ORDER BY option_name ASC LIMIT %d", $like, self::LEGACY_OPTION, $cursor, $limit ) ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Core options table is trusted; values are prepared and keyset pagination is bounded. $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND option_name <> %s AND option_name > %s AND option_name <= %s ORDER BY option_name ASC LIMIT %d", $like, self::LEGACY_OPTION, $cursor, $upper_bound, $limit ) ); } return array_values( array_map( 'strval', (array) $names ) ); } /** * Acquire or recover one expiring lease. * * @param int $object_id WordPress object ID. */ private function claim_lock( int $object_id ): string { $key = $this->lock_key( $object_id ); $lock_token = $this->token() . ':' . ( time() + self::DEFAULT_LEASE_TTL ); if ( $this->add_lock_option( $key, $lock_token ) ) { return $lock_token; } $current = $this->read_lock_token( $key ); $parts = explode( ':', $current ); $expires = absint( end( $parts ) ); if ( 0 < $expires && $expires >= time() ) { return ''; } if ( $this->is_finalization_lock_token( $current ) ) { return $this->recover_finalization_lock( $object_id, $key, $current, $lock_token ); } return $this->update_option_if_value( $key, $current, $lock_token ) ? $lock_token : ''; } /** * Reserve, rotate, and reclaim one expired finalization lease. * * The recovery reservation is acquired before the queue is rotated. Only * that reservation owner may invalidate the old generation, and a worker * lease is not exposed until the rotation is durable. * * @param int $object_id WordPress object ID. * @param string $lock_key Lease option key. * @param string $expired_token Exact expired finalization token. * @param string $lock_token New worker lease token. */ private function recover_finalization_lock( int $object_id, string $lock_key, string $expired_token, string $lock_token ): string { $queue_token = $this->read_queue_generation( $object_id ); if ( '' === $queue_token ) { $this->delete_option_if_value( $lock_key, $expired_token ); return ''; } $recovery_token = 'recovery:' . $this->token() . ':' . ( time() + self::TRANSITION_TTL ); if ( ! $this->update_option_if_value( $lock_key, $expired_token, $recovery_token ) ) { return ''; } if ( ! $this->rotate_transition_generation( $object_id, $queue_token ) ) { $this->delete_option_if_value( $lock_key, $recovery_token ); return ''; } return $this->update_option_if_value( $lock_key, $recovery_token, $lock_token ) ? $lock_token : ''; } /** * Rotate the queue generation before reclaiming an expired finalizer. * * A paused finalizer remains bound to its original queue token. Rotating * that exact generation before the transition lease can be reclaimed makes * every later acknowledge or retry from the paused owner fail closed. * * @param int $object_id WordPress object ID. * @param string $queue_token Queue generation observed before recovery was reserved. */ private function rotate_transition_generation( int $object_id, string $queue_token ): bool { $state = $this->parse_queue_state( $queue_token ); $replacement = $this->queue_state( $state['attempts'], $state['available_at'], $state['action'] ); return $this->update_option_if_value( $this->queue_key( $object_id ), $queue_token, $replacement ); } /** * Fence a still-active lease owner before changing its queue generation. * * Replacing the worker token with a short-lived transition token is a * database-portable compare-and-swap. It prevents a reclaimed worker from * acknowledging or retrying after another owner wins the same lease, while * preserving a newer queue generation that arrives during finalization. * * @param int $object_id WordPress object ID. * @param string $lock_token Claimed lease token. */ private function begin_owned_transition( int $object_id, string $lock_token ): string { if ( ! $this->is_active_lock_token( $lock_token ) ) { return ''; } $transition_token = 'transition:' . $this->token() . ':' . ( time() + self::TRANSITION_TTL ); if ( ! $this->update_option_if_value( $this->lock_key( $object_id ), $lock_token, $transition_token ) ) { return ''; } return $transition_token; } /** * Add one non-autoloaded lock row if it does not already exist. * * @param string $option_name Lock option name. * @param string $lock_token Unique expiring lock token. */ private function add_lock_option( string $option_name, string $lock_token ): bool { if ( $this->uses_test_options() ) { return add_option( $option_name, $lock_token, '', false ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- INSERT IGNORE is the lease acquisition CAS; Core add_option() can overwrite on a duplicate-key race. $added = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $option_name, $lock_token ) ); $this->invalidate_option_caches( array( $option_name ) ); return 1 === (int) $added; } /** * Read the authoritative lease token without a stale option-cache value. * * @param string $option_name Lock option name. */ private function read_lock_token( string $option_name ): string { if ( $this->uses_test_options() ) { return (string) get_option( $option_name, '' ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Lease reclaim must compare against the current database owner. $value = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $option_name ) ); return is_string( $value ) ? $value : ''; } /** * Delete an option only if its generation value still matches. * * @param string $option_name Option name. * @param string $value Expected stored value. */ private function delete_option_if_value( string $option_name, string $value ): bool { if ( $this->uses_test_options() ) { $current = (string) get_option( $option_name, '' ); if ( ! hash_equals( $value, $current ) ) { return false; } return delete_option( $option_name ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Conditional delete acknowledges only the claimed queue generation. $deleted = $wpdb->delete( $wpdb->options, array( 'option_name' => $option_name, 'option_value' => $value, ), array( '%s', '%s' ) ); if ( function_exists( 'wp_cache_delete' ) ) { wp_cache_delete( $option_name, 'options' ); wp_cache_delete( 'notoptions', 'options' ); } return 1 === (int) $deleted; } /** * Replace an option only if its claimed generation still matches. * * @param string $option_name Option name. * @param string $old_value Expected stored value. * @param string $new_value Replacement value. */ private function update_option_if_value( string $option_name, string $old_value, string $new_value ): bool { if ( $this->uses_test_options() ) { $current = (string) get_option( $option_name, '' ); if ( ! hash_equals( $old_value, $current ) ) { return false; } return update_option( $option_name, $new_value, false ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Conditional update preserves newer queue generations. $updated = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s", $new_value, $option_name, $old_value ) ); if ( function_exists( 'wp_cache_delete' ) ) { wp_cache_delete( $option_name, 'options' ); wp_cache_delete( 'notoptions', 'options' ); } return 1 === (int) $updated; } /** * Check whether a lease token has not expired. * * @param string $lock_token Lease token. */ private function is_active_lock_token( string $lock_token ): bool { if ( '' === $lock_token ) { return false; } $parts = explode( ':', $lock_token ); $expires = absint( end( $parts ) ); return 0 < $expires && $expires >= time(); } /** * Check whether a lease token belongs to finalization or its recovery. * * @param string $lock_token Lease token. */ private function is_finalization_lock_token( string $lock_token ): bool { return str_starts_with( $lock_token, 'transition:' ) || str_starts_with( $lock_token, 'recovery:' ); } /** * Invalidate authoritative option and negative-cache entries. * * @param array $option_names Option names. * @phpstan-param list $option_names */ private function invalidate_option_caches( array $option_names ): void { if ( ! function_exists( 'wp_cache_delete' ) ) { return; } foreach ( $option_names as $option_name ) { wp_cache_delete( $option_name, 'options' ); } wp_cache_delete( 'notoptions', 'options' ); } /** * Migrate the former shared pending-ID list without dropping queued work. */ private function migrate_legacy_option(): void { $legacy = get_option( self::LEGACY_OPTION, array() ); if ( ! is_array( $legacy ) || array() === $legacy ) { return; } $migrated = true; foreach ( array_values( array_unique( array_filter( array_map( 'absint', $legacy ) ) ) ) as $object_id ) { if ( '' !== $this->read_queue_generation( $object_id ) ) { continue; } $added = $this->add_queue_generation_if_absent( $object_id, $this->queue_state() ); if ( ! $added && '' === $this->read_queue_generation( $object_id ) ) { $migrated = false; } } if ( $migrated ) { delete_option( self::LEGACY_OPTION ); } } /** * Check whether the PHPUnit option store is active. */ private function uses_test_options(): bool { return isset( $GLOBALS['aculect_ai_companion_test_options'] ) && is_array( $GLOBALS['aculect_ai_companion_test_options'] ); } /** * Read the authoritative generation without allowing a stale cache republish. * * @param int $object_id WordPress object ID. */ private function read_queue_generation( int $object_id ): string { $option_name = $this->queue_key( $object_id ); if ( $this->uses_test_options() ) { return (string) get_option( $option_name, '' ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Queue correctness requires the current database generation; claims are bounded to five rows per sweep. $value = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $option_name ) ); return is_string( $value ) ? $value : ''; } /** * Atomically add one queue generation without replacing existing work. * * @param int $object_id Object ID. * @param string $generation Queue generation. */ private function add_queue_generation_if_absent( int $object_id, string $generation ): bool { $option_name = $this->queue_key( $object_id ); if ( $this->uses_test_options() ) { return add_option( $option_name, $generation, '', false ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Atomic insert preserves an existing retry, save generation, or deletion tombstone. $added = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $option_name, $generation ) ); if ( function_exists( 'wp_cache_delete' ) ) { wp_cache_delete( $option_name, 'options' ); wp_cache_delete( 'notoptions', 'options' ); } return 1 === (int) $added; } /** * Atomically replace one generation without publishing a stale cache value. * * @param int $object_id WordPress object ID. * @param string $generation New queue generation. */ private function replace_queue_generation( int $object_id, string $generation ): bool { $option_name = $this->queue_key( $object_id ); if ( $this->uses_test_options() ) { return update_option( $option_name, $generation, false ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- One atomic upsert makes the last queue generation authoritative; caches are invalidated below. $replaced = $wpdb->query( $wpdb->prepare( "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no') ON DUPLICATE KEY UPDATE option_value = VALUES(option_value), autoload = VALUES(autoload)", $option_name, $generation ) ); if ( false === $replaced ) { return false; } if ( function_exists( 'wp_cache_delete' ) ) { wp_cache_delete( $option_name, 'options' ); wp_cache_delete( 'notoptions', 'options' ); } return true; } /** * Return sorted test option names with one prefix. * * @param string $prefix Option prefix. * @return list */ private function test_option_names( string $prefix ): array { $names = array_values( array_filter( array_map( 'strval', array_keys( $GLOBALS['aculect_ai_companion_test_options'] ?? array() ) ), static fn ( string $name ): bool => str_starts_with( $name, $prefix ) ) ); sort( $names ); return $names; } /** * Return a queue option key for one object. * * @param int $object_id WordPress object ID. */ private function queue_key( int $object_id ): string { return self::QUEUE_PREFIX . absint( $object_id ); } /** * Return a lease option key for one object. * * @param int $object_id WordPress object ID. */ private function lock_key( int $object_id ): string { return self::LOCK_PREFIX . absint( $object_id ); } /** * Return a unique generation token. */ private function token(): string { return bin2hex( random_bytes( 16 ) ); } /** * Build one client-invisible queue state value. * * @param int $attempts Consecutive failures. * @param int $available_at Earliest retry timestamp. * @param string $action Queue action: index or delete. */ private function queue_state( int $attempts = 0, int $available_at = 0, string $action = 'index' ): string { $state = wp_json_encode( array( 'token' => $this->token(), 'attempts' => max( 0, $attempts ), 'available_at' => max( 0, $available_at ), 'action' => 'delete' === $action ? 'delete' : 'index', ) ); return false === $state ? $this->token() : $state; } /** * Parse one queue state, including legacy raw tokens. * * @param string $value Stored queue value. * @return array{attempts: int, available_at: int, action: string} */ private function parse_queue_state( string $value ): array { $state = json_decode( $value, true ); return array( 'attempts' => is_array( $state ) ? absint( $state['attempts'] ?? 0 ) : 0, 'available_at' => is_array( $state ) ? absint( $state['available_at'] ?? 0 ) : 0, 'action' => is_array( $state ) && 'delete' === ( $state['action'] ?? '' ) ? 'delete' : 'index', ); } /** * Check whether an option belongs to the queue. * * @param string $option_name Option name. */ private static function is_owned_option_name( string $option_name ): bool { return self::LEGACY_OPTION === $option_name || self::CURSOR_OPTION === $option_name || str_starts_with( $option_name, self::QUEUE_PREFIX ) || str_starts_with( $option_name, self::LOCK_PREFIX ); } }