*/ private $lock_tokens = []; /** * Why the current product's provider work lost the job: 'lock_lost' when * another run took the job lock, 'claim_lost' when the product left this * tick's claim, null while the tick holds both. Set by the heartbeat * listener before a provider attempt (confirmHeldBeforeAttempt()), reset * for each product (generateWhileHeld()). * @var string|null */ private $heldWorkLost = null; const MIN_WINDOW_SIZE = AutomationConstants::MIN_WINDOW_SIZE; const MAX_WINDOW_SIZE = AutomationConstants::MAX_WINDOW_SIZE; const PROGRESS_FLUSH_EVERY = AutomationConstants::PROGRESS_FLUSH_EVERY; private const RETIRED_STANDARD_TOOL_MESSAGE = 'The Standard generator has been merged into the Advanced generator; recreate this job.'; /** * Constructor * * @param AutomationJobManager $job_manager Job manager instance * @param JobLoggerInterface $logger Logger instance */ public function __construct(AutomationJobManager $job_manager, JobLoggerInterface $logger) { $this->job_manager = $job_manager; $this->logger = $logger; global $wpdb; $this->wpdb = $wpdb; $this->job_products_table = $wpdb->prefix . 'aipt_job_products'; $this->queue = new \AIPT\Api\AutomationJobs\ClaimBasedQueue(); $this->progress_tracker = new \AIPT\Api\AutomationJobs\IncrementalProgressTracker(); $this->options_translator = new OptionsTranslator(); $this->result_processor = new ResultProcessor($logger); $this->item_retry_tracker = new ItemRetryTracker(); $this->stall_tracker = new StallTracker(); $this->answer_store = new InterruptedAnswerStore(); } /** * Execute a job * * @param int $job_id Job ID to execute * @return bool Success status * @throws \Exception On execution failure */ public function executeJob($job_id) { $job = $this->job_manager->getJob($job_id); if (!$job) { Logger::debug('automation', 'Job tick skipped: the job could not be read', ['job_id' => (int) $job_id]); return false; } if ($this->isCancelledJob($job)) { return true; } if ('standard' === (string) $job->tool_type) { if (in_array((string) $job->status, ['completed', 'failed'], true)) { return false; } return $this->failRetiredStandardJob($job); } if ($job->status === 'paused') { $this->logger->info($job_id, 'Job is paused, skipping execution'); return true; } $validation_errors = $this->validateJobForExecution($job); if (!empty($validation_errors)) { $this->logger->error($job_id, 'Job validation failed', [ 'errors' => $validation_errors, 'type' => 'VALIDATION' ]); throw new \Exception('Job validation failed: ' . wp_json_encode($validation_errors)); } if (JobScheduler::isWaitingForRecurringCycle($job, $this->job_manager)) { return true; } if (SpendLimit::isReached()) { $this->waitForSpendLimit((int) $job_id); return true; } try { $this->logger->info($job_id, 'Starting job execution (time-sliced)', [ 'tool_type' => $job->tool_type, 'job_name' => $job->name, 'timestamp' => current_time('mysql', true) ]); if (!$this->acquireLock((int) $job_id)) { $this->logger->info($job_id, 'Another executor is already running for this job (lock held)'); return false; } $this->liftTimeLimit(); try { if ($this->isCancelledJob($this->job_manager->getJob($job_id))) { return true; } $stallTickCounted = 'running' === (string) $job->status; if ($stallTickCounted && $this->stall_tracker->tickStarted((int) $job_id) > StallTracker::MAX_TICKS_WITHOUT_PROGRESS) { $this->pauseForStall((int) $job_id); return true; } $released = $this->queue->forceReleaseAllProcessing((int) $job_id); $releaseContext = ['released_count' => (int) $released]; if ($released > 0 && $this->shouldLogDebugSnapshot((int) $job_id, 'released_processing', $releaseContext)) { $this->logger->debug($job_id, 'Released processing items before tick', $releaseContext); } $tickStartTs = microtime(true); $startState = $this->describeJobProductState((int) $job_id); $startContext = array_merge($startState, [ 'job_status' => $job->status, 'progress_percent' => (int) $job->progress, 'processed_products' => (int) $job->processed_products, 'failed_products' => (int) $job->failed_products, 'total_products' => (int) $job->total_products, ]); if ($this->shouldLogDebugSnapshot((int) $job_id, 'tick_start', $startContext)) { $this->logger->debug($job_id, 'Tick starting', $startContext); } if (in_array($job->status, ['ready', 'completed'], true) && JobScheduler::isRecurringCycleDue($job)) { if (!$this->startRecurringCycle($job)) { return true; } $job = $this->job_manager->getJob($job_id); if (!$job) { return false; } } if ($job->status === 'preparing') { try { $pool_builder = new \AIPT\Api\AutomationJobs\PoolBuilder(); $filter = is_array($job->product_filter) ? $job->product_filter : []; $pool_options = AutomationJob::getPoolBuildOptions( (string) $job->tool_type, is_array($job->settings) ? $job->settings : [] ); $pool_result = $pool_builder->buildPool( (int)$job_id, $filter, AutomationConstants::POOL_BUILD_CHUNK_SIZE, AutomationConstants::MAX_POOL_BUILD_CHUNKS, $pool_options['skip_processed'], $pool_options['targeted_types'] ); if (!empty($pool_result['blocked'])) { if (!$this->job_manager->pauseForEntitlement((int) $job_id, (string) $pool_result['blocked']['message'], true, ['preparing'])) { $this->logger->info($job_id, 'Pool build stopped: the job changed meanwhile, its status was left as it is'); return true; } $this->logger->warning($job_id, 'Pool build paused: saved product filter cannot be honored', [ 'reason' => $pool_result['blocked']['reason'], 'feature' => $pool_result['blocked']['feature'], 'filters' => $pool_result['blocked']['keys'], ]); return true; } $target_total = isset($pool_result['total']) ? (int)$pool_result['total'] : (int)$job->total_products; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $current_total = (int) $this->wpdb->get_var( $this->wpdb->prepare( "SELECT COUNT(*) FROM {$this->job_products_table} WHERE job_id = %d", (int)$job_id ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared $jobs_table = $this->wpdb->prefix . 'aipt_automation_jobs'; if ($target_total !== (int)$job->total_products) { $this->wpdb->update( $jobs_table, ['total_products' => $target_total, 'updated_at' => JobTime::now()], ['id' => (int)$job_id], ['%d','%s'], ['%d'] ); } else { $this->wpdb->update( $jobs_table, ['updated_at' => JobTime::now()], ['id' => (int)$job_id], ['%s'], ['%d'] ); } $pool_full = $current_total >= $target_total; if ($pool_full && $target_total === 0) { $status_write = $this->job_manager->transitionJobStatus((int) $job_id, 'completed', ['preparing']); if (AutomationJobManager::TRANSITION_APPLIED === $status_write) { $this->logger->info($job_id, 'Job completed immediately; no products matched'); (new JobScheduler($this->job_manager, $this->logger))->rearmRecurringJob((int) $job_id); return true; } } else { $status_write = $this->job_manager->transitionJobStatus((int) $job_id, $pool_full ? 'ready' : 'preparing', ['preparing']); } if (AutomationJobManager::TRANSITION_LOST === $status_write && $this->stoppedMeanwhile((int) $job_id)) { $this->logger->info($job_id, 'Pool build tick ended: the job was paused, cancelled or finished meanwhile'); return true; } if (AutomationJobManager::TRANSITION_ERROR === $status_write) { $this->logger->warning($job_id, 'Pool build status could not be saved; the next tick tries again', [ 'pool_current' => $current_total, 'pool_target' => $target_total, ]); } elseif (AutomationJobManager::TRANSITION_LOST === $status_write) { $this->logger->info($job_id, 'Pool build status left as another tick set it'); } elseif ($pool_full && $target_total > 0) { $this->logger->info($job_id, 'Product pool fully built; job set to ready', ['total' => $target_total]); } elseif (!$pool_full) { $this->logger->info($job->id, 'Continuing pool build in background', [ 'inserted_so_far' => $current_total, 'target_total' => $target_total ]); } $hook = JobRunHook::HOOK; $scheduleTimestamp = time() + AutomationConstants::rescheduleDelay(); $scheduled = JobRunHook::schedule((int)$job_id, $scheduleTimestamp); $nextScheduled = JobRunHook::next_run((int)$job_id); $poolContext = array_merge($this->describeJobProductState((int)$job_id), [ 'remaining_items' => max(0, (int)$target_total - $current_total), 'next_tick_due_at' => $nextScheduled ? gmdate('c', $nextScheduled) : null, 'schedule_result' => $scheduled === false ? 'failed' : 'scheduled', 'pool_target' => $target_total, 'pool_current' => $current_total, ]); if ($this->shouldLogDebugSnapshot((int)$job_id, 'pool_rescheduled', $poolContext)) { $this->logger->debug($job_id, 'Pool build tick rescheduled', $poolContext); } if ($scheduled === false) { $this->logger->warning($job_id, 'Failed to schedule next pool build tick', [ 'hook' => $hook, 'pool_target' => $target_total, 'pool_current' => $current_total, ]); } $pool_moved = $pool_full || (int) ($pool_result['inserted'] ?? 0) > 0; if ($scheduled !== false && $pool_moved && in_array($status_write, [AutomationJobManager::TRANSITION_APPLIED, AutomationJobManager::TRANSITION_ALREADY], true)) { CronContinuationKick::afterThisRun($hook, [(int) $job_id]); } return true; } catch (\Throwable $t) { $this->logger->error($job_id, 'Pool build step failed', ['error' => $t->getMessage(), 'type' => 'DB']); return false; } } $processedThisTick = 0; $failedThisTick = 0; $claimAttempts = 0; $exitReason = 'loop_completed'; $options = $this->options_translator->translate($job->settings, $job->tool_type); $assessment = JobEntitlementGuard::assessRun($job, is_array($options) ? $options : []); if (null !== $assessment['block']) { $this->pauseForEntitlement((int) $job_id, $assessment['block'], [(string) $job->status]); return true; } $reviewGuaranteed = JobEntitlementGuard::reviewGuaranteed($job); $skipStager = $this->resolveSkipStager((int) $job->id, $reviewGuaranteed); $skipContentTypes = []; $skipOverwrite = 'replace'; if (null !== $skipStager) { $skipContentTypes = 'advanced' === $job->tool_type ? $this->extractContentTypes($options) : []; $skipOverwrite = OptionsTranslator::overwriteMode(is_array($job->settings) ? $job->settings : []); } $settledCheckFailureLogged = false; $skippedThisTick = 0; $skippedWaitingThisTick = 0; $skippedKeptThisTick = 0; $loggedStoreSectionNotices = []; if ($job->status !== 'running') { $start = $this->job_manager->startJobWithinConcurrentCap((int) $job_id, [(string) $job->status]); if (AutomationJobManager::START_LOST === $start && $this->stoppedMeanwhile((int) $job_id)) { $this->logger->info($job_id, 'Job start skipped: the job was paused, cancelled or finished meanwhile'); return true; } if (AutomationJobManager::START_ADMITTED !== $start) { $this->logDeferredStart((int) $job_id, $start); $hook = JobRunHook::HOOK; $scheduled = JobRunHook::schedule((int) $job_id, time() + AutomationConstants::rescheduleDelay()); if ($scheduled === false) { $this->logger->warning($job_id, 'Failed to schedule deferred job start retry', ['hook' => $hook]); } return true; } $this->logger->info($job_id, 'Job status set to running'); $this->stall_tracker->resetTicks((int) $job_id); $this->logRunClamps((int) $job_id, $assessment['clamps']); } $this->logger->info($job_id, 'Initializing AI service', ['tool_type' => $job->tool_type]); $service = $this->getAIService($job->tool_type); $this->logger->info($job_id, 'AI service initialized', ['service_class' => get_class($service)]); $leftState = $this->describeJobProductState((int) $job_id); $itemsLeft = $leftState['pending'] + $leftState['processing']; $budgetEndsAt = time() + AutomationConstants::tickTimeBudget(); $processed_inc = 0; $failed_inc = 0; $last_flush = time(); $itemCounter = 0; $memoryBudget = $this->tickMemoryBudget(function_exists('memory_get_usage') ? memory_get_usage(true) : 0); $exitReason = 'tick_completed'; $progressNoted = false; while (time() < $budgetEndsAt) { $freshJob = $this->job_manager->getJob($job_id); if ($this->isCancelledJob($freshJob)) { $exitReason = 'cancelled_mid_tick'; break; } if ($freshJob && $freshJob->status === 'paused') { $exitReason = 'paused_mid_tick'; $this->logger->info($job_id, 'Job paused mid-execution, stopping tick'); break; } if (SpendLimit::isReached()) { $exitReason = 'spend_limit_reached'; break; } $claimAttempts++; $adaptiveWindowSize = $this->getAdaptiveWindowSize((int) $job_id, $memoryBudget); $claim = $this->queue->claimBatch((int) $job_id, $adaptiveWindowSize); $currentClaimToken = $claim['token'] ?? null; if (empty($claim['product_ids'])) { if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); } $exitReason = 'no_claimable_items'; break; } foreach ($claim['product_ids'] as $productIndex => $product_id) { $attemptStarted = false; $answerMayBeKept = false; $productFinished = false; if (time() >= $budgetEndsAt) { if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } $exitReason = 'time_budget_exhausted'; break 1; } $freshJob = $this->job_manager->getJob($job_id); if ($this->isCancelledJob($freshJob)) { $exitReason = 'cancelled_mid_tick'; if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } if ($freshJob && $freshJob->status === 'paused') { $exitReason = 'paused_mid_tick'; $this->logger->info($job_id, 'Job paused, stopping item loop'); if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 1; } try { if (!$currentClaimToken || !$this->queue->ownsClaim((int)$job->id, (int)$product_id, (string)$currentClaimToken)) { $exitReason = 'claim_lost'; $currentClaimToken = null; break 2; } if (!$this->renewLock((int) $job->id)) { $exitReason = 'lock_lost'; if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } $settled = $this->settledAnswer($skipStager, (int) $job->id, (int) $product_id, (string) $job->tool_type, $options, $skipContentTypes, $skipOverwrite, $settledCheckFailureLogged); if (ReviewQueueStager::SETTLED_PROCEED !== $settled['outcome']) { if (ReviewQueueStager::SETTLED_NO_TARGET === $settled['outcome']) { $noTargetMessage = $this->result_processor->noReviewTargetMessage($settled['refusals']); if (!$this->queue->markFailed((int) $job->id, (int) $product_id, (string) $currentClaimToken, $noTargetMessage)) { $exitReason = 'claim_lost'; $currentClaimToken = null; break 2; } $failed_inc += 1; $this->result_processor->logReviewRefusals((int) $job->id, (int) $product_id, $settled['refusals']); Logger::error('automation', 'Job item failed', ['job_id' => (int) $job->id, 'product_id' => (int) $product_id, 'reason' => 'no_review_target']); } else { $skipMarker = ['skipped' => true, 'reason' => $settled['outcome']]; if (!$this->persistTerminalSuccess($job->id, $product_id, $skipMarker, $currentClaimToken)) { $exitReason = 'claim_lost'; $currentClaimToken = null; break 2; } $processed_inc += 1; if (ReviewQueueStager::SETTLED_WAITING === $settled['outcome']) { $skippedWaitingThisTick += 1; if ($settled['in_progress']) { $this->logger->info($job_id, __('Skipped the product: a proposal for it is being approved, or is stuck, in To review. Approve or reject it there, and if it stays, delete it there.', 'ai-product-tools'), [ 'product_id' => (int) $product_id, ]); } } else { $skippedKeptThisTick += 1; } } $this->stall_tracker->attemptEnded((int) $job->id, (int) $product_id); $this->answer_store->forget((int) $job->id, (int) $product_id); $this->item_retry_tracker->clear((int) $job->id, (int) $product_id); $skippedThisTick += 1; $productFinished = true; } else { $interrupted = $this->stall_tracker->interruptedAttempts((int) $job->id, (int) $product_id); if ($interrupted >= StallTracker::MAX_INTERRUPTED_ATTEMPTS) { if (!$this->queue->markFailed((int) $job->id, (int) $product_id, (string) $currentClaimToken, self::interruptedProductMessage())) { $exitReason = 'claim_lost'; $currentClaimToken = null; break 2; } $this->stall_tracker->attemptEnded((int) $job->id, (int) $product_id); $this->answer_store->forget((int) $job->id, (int) $product_id); $this->item_retry_tracker->clear((int) $job->id, (int) $product_id); $failed_inc += 1; $failedThisTick += 1; $this->logger->warning($job_id, 'Product skipped: its generation was interrupted every time it was tried', [ 'product_id' => (int) $product_id, 'interrupted_attempts' => $interrupted, ]); Logger::error('automation', 'Job item failed', ['job_id' => (int) $job->id, 'product_id' => (int) $product_id, 'reason' => 'interrupted']); $this->progress_tracker->increment((int) $job->id, (int) $processed_inc, (int) $failed_inc); $processed_inc = 0; $failed_inc = 0; $last_flush = time(); continue; } if ($interrupted > 0) { $this->logger->info($job_id, 'Trying a product again: its last generation was interrupted', [ 'product_id' => (int) $product_id, 'interrupted_attempts' => $interrupted, ]); Logger::warn('automation', 'Job item interrupted, trying it again', ['job_id' => (int) $job->id, 'product_id' => (int) $product_id, 'attempts' => $interrupted]); } $this->stall_tracker->attemptStarted((int) $job->id, (int) $product_id, $interrupted); $attemptStarted = true; $keptAnswer = null; if ($interrupted > 0) { $answerMayBeKept = true; $keptAnswer = $this->answer_store->take((int) $job->id, (int) $product_id, (string) $job->tool_type); if (null !== $keptAnswer) { $this->logger->info($job_id, 'Applied the answer an interrupted attempt already received, without a new provider call', [ 'product_id' => (int) $product_id, ]); } } $results = null !== $keptAnswer ? $keptAnswer : $this->generateWhileHeld( (int) $job->id, (int) $product_id, (string) $currentClaimToken, fn() => PromptCacheScope::forRunOf( max(0, $itemsLeft - $skippedThisTick), fn() => $this->generateForAutomationProduct($service, (int) $product_id, $options, (int) $job->created_by, $reviewGuaranteed) ) ); if (null === $results) { $jobAfterStop = $this->job_manager->getJob($job_id); if (null !== $jobAfterStop && $this->isCancelledJob($jobAfterStop)) { $exitReason = 'cancelled_mid_tick'; if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } $exitReason = (string) $this->heldWorkLost; $attemptStarted = false; $this->logger->warning($job_id, 'Stopped this tick before its next provider call: it no longer held the job lock or the product\'s claim', [ 'product_id' => (int) $product_id, 'reason' => $exitReason, ]); if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } $this->logStoreSectionClampNotices((int) $job_id, $results, $loggedStoreSectionNotices); if ($this->isCancelledJob($this->job_manager->getJob($job_id))) { $exitReason = 'cancelled_mid_tick'; if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } if (!$this->queue->ownsClaim((int)$job->id, (int)$product_id, (string)$currentClaimToken)) { $exitReason = 'claim_lost'; $attemptStarted = false; $currentClaimToken = null; break 2; } if (null === $keptAnswer) { $answerMayBeKept = true; $this->answer_store->save((int) $job->id, (int) $product_id, (string) $job->tool_type, $results); } $counts = $this->processResults($job->id, $results, (string)$currentClaimToken); $completedCount = (int) ($counts['completed'] ?? 0); $failedCount = (int) ($counts['failed'] ?? 0); $hasCompleted = $completedCount > 0; $hasFailed = $failedCount > 0; if (!empty($counts['claim_lost'])) { $exitReason = 'claim_lost'; $attemptStarted = false; $currentClaimToken = null; break 2; } if (!empty($counts['cancelled']) && !$hasCompleted && !$hasFailed) { $exitReason = 'cancelled_mid_tick'; if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } if ($hasCompleted && !$hasFailed) { $this->item_retry_tracker->clear((int)$job->id, (int)$product_id); $processed_inc += 1; $processedThisTick += 1; } elseif ($hasFailed) { $failed_inc += 1; $failedThisTick += 1; } else { if (!$this->queue->markFailed((int)$job->id, (int)$product_id, (string)$currentClaimToken, 'No products were processed')) { $exitReason = 'claim_lost'; $attemptStarted = false; $currentClaimToken = null; break 2; } $failed_inc += 1; $failedThisTick += 1; } $productFinished = true; } } catch (\Throwable $t) { if ($this->isCancelledJob($this->job_manager->getJob($job_id))) { $exitReason = 'cancelled_mid_tick'; if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } $providerId = (string) ($options['provider'] ?? ''); $merchantMessage = $this->providerFailureMessage($t, $providerId, (string) ($options['model'] ?? '')); $itemContext = ['job_id' => (int) $job->id, 'product_id' => (int) $product_id]; if ($t instanceof ProviderCallException) { $itemContext['reason'] = $t->reason(); } else { $itemContext['error'] = $t->getMessage(); } if ($t instanceof ProviderCallException && $t->isRunWide()) { $reason = $t->reason(); if (ProviderCallException::SPEND_LIMIT_REACHED === $reason) { $this->item_retry_tracker->clear((int)$job->id, (int)$product_id); if (!$this->queue->requeueItem((int)$job->id, (int)$product_id, (string)$currentClaimToken)) { $attemptStarted = false; } if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } $exitReason = 'spend_limit_reached'; break 2; } if (ProviderCallException::QUOTA_EXHAUSTED === $reason || ProviderCallException::RATE_LIMITED === $reason) { do_action('aipt_automation_ai_call_failed', (int) $job->id, 'PROVIDER_QUOTA_LIMIT'); } if (!$t->isRetryable()) { $this->item_retry_tracker->clear((int)$job->id, (int)$product_id); if (!$this->queue->requeueItem((int)$job->id, (int)$product_id, (string)$currentClaimToken)) { $attemptStarted = false; } if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } $this->pauseForProviderFailure((int)$job->id, $t, $providerId, $merchantMessage, $freshJob ? [(string) $freshJob->status] : []); $exitReason = 'provider_run_wide_failure'; break 2; } $attempts = $this->item_retry_tracker->recordAttempt((int)$job->id, (int)$product_id); if ($attempts >= ItemRetryTracker::MAX_ATTEMPTS && ProviderCallException::RATE_LIMITED === $t->reason()) { $this->item_retry_tracker->clear((int)$job->id, (int)$product_id); if (!$this->queue->requeueItem((int)$job->id, (int)$product_id, (string)$currentClaimToken)) { $attemptStarted = false; } if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } $this->pauseForProviderFailure( (int)$job->id, $t, $providerId, $merchantMessage . ' ' . __('The job was paused so the remaining products wait instead of failing; resume it once the limit resets.', 'ai-product-tools'), $freshJob ? [(string) $freshJob->status] : [] ); $exitReason = 'provider_rate_limit_persisted'; break 2; } if ($attempts >= ItemRetryTracker::MAX_ATTEMPTS) { $this->item_retry_tracker->clear((int)$job->id, (int)$product_id); if (!$this->queue->markFailed((int)$job->id, (int)$product_id, (string)$currentClaimToken, $merchantMessage)) { $exitReason = 'claim_lost'; $attemptStarted = false; $currentClaimToken = null; break 2; } $failed_inc += 1; $failedThisTick += 1; $productFinished = true; Logger::error('automation', 'Job item failed', $itemContext); } else { if (!$this->queue->requeueItem((int)$job->id, (int)$product_id, (string)$currentClaimToken)) { $attemptStarted = false; } Logger::warn('automation', 'Job item requeued after a provider failure', $itemContext); } if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } $this->recordErrorForThrottling((int)$job->id); $exitReason = 'provider_transient_failure'; break 2; } if (!$this->queue->markFailed((int)$job->id, (int)$product_id, (string)$currentClaimToken, $merchantMessage)) { $exitReason = 'claim_lost'; $attemptStarted = false; $currentClaimToken = null; break 2; } $failed_inc += 1; $failedThisTick += 1; $productFinished = true; Logger::error('automation', 'Job item failed', $itemContext); $this->recordErrorForThrottling((int)$job->id); } finally { if ($attemptStarted) { $this->stall_tracker->attemptEnded((int) $job->id, (int) $product_id); if ($answerMayBeKept) { $this->answer_store->forget((int) $job->id, (int) $product_id); } } if ($productFinished && !$progressNoted) { $this->stall_tracker->resetTicks((int) $job->id); $progressNoted = true; } } $itemCounter++; unset($results); if (($itemCounter % AutomationConstants::GC_COLLECT_CYCLES_INTERVAL) === 0 && function_exists('gc_collect_cycles')) { gc_collect_cycles(); } if (function_exists('memory_get_usage')) { $mem = memory_get_usage(true); if ($mem > $memoryBudget['ceiling']) { $exitReason = 'memory_soft_limit'; $this->logger->warning((int)$job->id, 'Soft memory limit reached, stopping tick early', [ 'type' => 'SYSTEM', 'memory_usage_bytes' => (int) $mem, 'soft_limit_bytes' => (int) $memoryBudget['ceiling'], ]); if ($currentClaimToken) { $this->queue->releaseClaimByToken((int)$job->id, (string)$currentClaimToken); $currentClaimToken = null; } break 2; } } if (($processed_inc + $failed_inc) >= self::PROGRESS_FLUSH_EVERY || (time() - $last_flush) >= 5) { $this->progress_tracker->increment((int)$job->id, (int)$processed_inc, (int)$failed_inc); $processed_inc = 0; $failed_inc = 0; $last_flush = time(); } } } if ($exitReason === 'tick_completed') { $exitReason = ($processedThisTick > 0 || $failedThisTick > 0 || $skippedThisTick > 0) ? 'work_done' : 'tick_idle'; } if ($exitReason === 'spend_limit_reached' && $stallTickCounted && !$progressNoted) { $this->stall_tracker->tickNotCounted((int) $job_id); } if ($processed_inc > 0 || $failed_inc > 0) { $this->progress_tracker->increment((int)$job->id, (int)$processed_inc, (int)$failed_inc); } $this->logSkippedProducts((int) $job->id, $skippedWaitingThisTick, $skippedKeptThisTick); if ($processedThisTick > 0 && $failedThisTick === 0) { $this->resetErrorThrottling((int) $job->id); } $endState = $this->describeJobProductState((int) $job->id); $tickDurationMs = (int) round((microtime(true) - $tickStartTs) * 1000); $logContext = array_merge($endState, [ 'exit_reason' => $exitReason, 'processed_this_tick' => $processedThisTick, 'failed_this_tick' => $failedThisTick, 'skipped_this_tick' => $skippedThisTick, 'claim_batches' => $claimAttempts, 'tick_duration_ms' => $tickDurationMs, ]); if ($this->shouldLogDebugSnapshot((int) $job->id, 'tick_finished', $logContext)) { $this->logger->debug($job_id, 'Tick finished', $logContext); } $freshJob = $this->job_manager->getJob($job_id); if ($this->isCancelledJob($freshJob) || ($freshJob && $freshJob->status === 'paused')) { return true; } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $jobs_table = $this->wpdb->prefix . 'aipt_automation_jobs'; $now = JobTime::now(); $completed = $this->wpdb->query( $this->wpdb->prepare( "UPDATE {$jobs_table} SET status = 'completed', completed_at = %s, updated_at = %s, progress = 100 WHERE id = %d AND status = 'running' AND NOT EXISTS ( SELECT 1 FROM {$this->job_products_table} WHERE job_id = %d AND status IN ('pending', 'processing') )", $now, $now, (int)$job->id, (int)$job->id ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared if ($completed > 0) { $this->logger->info($job_id, 'Job completed successfully', $logContext); (new JobScheduler($this->job_manager, $this->logger))->rearmRecurringJob((int) $job_id); } else { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared $remaining = (int) $this->wpdb->get_var( $this->wpdb->prepare( "SELECT COUNT(*) FROM {$this->job_products_table} WHERE job_id = %d AND status IN ('pending','processing')", (int)$job->id ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared if ($remaining > 0) { $hook = JobRunHook::HOOK; $scheduleTimestamp = time() + AutomationConstants::rescheduleDelay(); $scheduled = JobRunHook::schedule((int)$job->id, $scheduleTimestamp); $nextScheduled = JobRunHook::next_run((int)$job->id); $scheduleContext = array_merge($logContext, [ 'remaining_items' => $remaining, 'next_tick_due_at' => $nextScheduled ? gmdate('c', $nextScheduled) : null, 'schedule_result' => $scheduled === false ? 'failed' : 'scheduled', ]); if ($this->shouldLogDebugSnapshot((int)$job->id, 'tick_rescheduled', $scheduleContext)) { $this->logger->debug($job_id, 'Tick rescheduled', $scheduleContext); } if ($scheduled === false) { $this->logger->warning($job_id, 'Failed to schedule next tick', array_merge($scheduleContext, [ 'hook' => $hook, ])); } if ($scheduled !== false && self::mayStartNextRunAtOnce($exitReason, $processedThisTick + $failedThisTick + $skippedThisTick)) { CronContinuationKick::afterThisRun($hook, [(int) $job->id]); } } } return true; } finally { $this->releaseLock((int) $job_id); } } catch (\Exception $e) { $this->logger->error($job_id, 'Job execution failed', [ 'error' => $e->getMessage(), 'type' => 'SYSTEM' ]); $this->job_manager->updateJobStatus($job_id, 'failed', $e->getMessage(), AutomationJob::TICK_STATUSES); throw $e; } } /** * Pause a running job * * @param int $job_id Job ID to pause * @return bool Success status * @throws \Exception On pause failure */ public function pauseJob($job_id) { $job = $this->job_manager->getJob($job_id); if (!$job) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message, not user-facing output throw new \Exception("Job not found: {$job_id}"); } if (!$job->canBePaused()) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Translated sentence shown to the merchant, not output throw new JobActionRefusedException(self::statusRefusalMessage('paused')); } if (!$this->job_manager->updateJobStatus($job_id, 'paused', null, [(string) $job->status])) { $current = $this->job_manager->getJob($job_id); if (!$current || 'paused' !== $current->status) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Translated sentence shown to the merchant, not output throw new JobActionRefusedException($current && $current->status !== $job->status ? self::statusRefusalMessage('paused') : __('The job could not be paused. Please try again.', 'ai-product-tools')); } } $this->logger->info($job_id, 'Job paused by user'); if (function_exists('delete_transient')) { delete_transient('aipt_job_monitor_' . (int) $job_id); } JobRunHook::clear((int) $job_id); return true; } /** * Resume a paused job * * @param int $job_id Job ID to resume * @return bool Success status * @throws \Exception On resume failure */ public function resumeJob($job_id) { $job_id = (int) $job_id; $job = $this->job_manager->getJob($job_id); if (!$job) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message, not user-facing output throw new \Exception("Job not found: {$job_id}"); } if (!$job->canBeResumed()) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Translated sentence shown to the merchant, not output throw new JobActionRefusedException(self::statusRefusalMessage('resumed')); } $this->stall_tracker->resetTicks($job_id); if (JobScheduler::isRecurringCycleDue($job)) { $resume_status = 'ready'; } else { $resume_status = $this->hasPoolRows((int) $job_id) ? 'running' : 'preparing'; } $from = [(string) $job->status]; if ('running' === $resume_status) { $start = $this->job_manager->startJobWithinConcurrentCap((int) $job_id, $from); $moved_on = AutomationJobManager::START_LOST === $start && !$this->stoppedMeanwhile($job_id); if (AutomationJobManager::START_ADMITTED !== $start && !$moved_on) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Translated sentence shown to the merchant, not output; resume_job() wraps it as a REST error. throw new JobActionRefusedException(self::refusedResumeMessage($start)); } } else { $transition = $this->job_manager->transitionJobStatus($job_id, $resume_status, $from); if (AutomationJobManager::TRANSITION_ERROR === $transition) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Translated sentence shown to the merchant, not output; resume_job() wraps it as a REST error. throw new JobActionRefusedException(self::refusedResumeMessage(AutomationJobManager::START_WRITE_FAILED)); } if (AutomationJobManager::TRANSITION_LOST === $transition && $this->stoppedMeanwhile($job_id)) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Translated sentence shown to the merchant, not output; resume_job() wraps it as a REST error. throw new JobActionRefusedException(self::refusedResumeMessage(AutomationJobManager::START_LOST)); } } $this->logger->info($job_id, 'Job resumed by user'); if ('running' === $resume_status) { $options = $this->options_translator->translate(is_array($job->settings) ? $job->settings : [], (string) $job->tool_type); $this->logRunClamps((int) $job_id, JobEntitlementGuard::assessRun($job, is_array($options) ? $options : [])['clamps']); } if (function_exists('delete_transient')) { delete_transient('aipt_job_monitor_' . (int) $job_id); } $hook = JobRunHook::HOOK; $scheduled = JobRunHook::schedule($job_id, time() + AutomationConstants::IMMEDIATE_EXECUTION_DELAY); if ($scheduled === false) { $this->logger->error($job_id, 'Failed to schedule job resume'); Logger::error('automation', 'Job resume could not be scheduled', ['job_id' => (int) $job_id, 'hook' => $hook]); } else { $this->logger->info($job_id, 'Job resume scheduled successfully'); } return true; } /** * Why a resume into 'running' was refused, for the REST error. * * @param string $start A refused AutomationJobManager::START_* result. * @return string */ private static function refusedResumeMessage(string $start): string { switch ($start) { case AutomationJobManager::START_BUSY: return __('Another automation job is starting right now. Please try again in a moment.', 'ai-product-tools'); case AutomationJobManager::START_WRITE_FAILED: return __('The job could not be resumed. Please try again.', 'ai-product-tools'); case AutomationJobManager::START_LOST: return __('The job was paused, cancelled or finished while it was being resumed.', 'ai-product-tools'); default: /* translators: %d: maximum number of automation jobs that may run at once. */ return sprintf(__('%d automation jobs are already running, the maximum allowed at once. Please try again in a few minutes.', 'ai-product-tools'), AutomationConstants::MAX_CONCURRENT_JOBS); } } /** * The sentence for a pause or resume the job's current status rules out. * The status itself is not named: the job list already shows it, and its * internal slug means nothing to a merchant. * * @param string $action 'paused' or 'resumed'. * @return string */ private static function statusRefusalMessage(string $action): string { if ('paused' === $action) { return __('This job cannot be paused in its current state.', 'ai-product-tools'); } return __('This job cannot be resumed in its current state.', 'ai-product-tools'); } /** * After a status write that lost its race: whether the merchant or a * final outcome stopped the job meanwhile (paused, failed or cancelled, * completed, or gone). Such a job gets no follow-up tick. A job another * tick moved on (ready, preparing, running) keeps its follow-up tick. * * @param int $job_id Job ID. * @return bool */ private function stoppedMeanwhile(int $job_id): bool { $job = $this->job_manager->getJob($job_id); return !$job || in_array((string) $job->status, ['paused', 'failed', 'completed'], true); } /** * Log why a tick did not start its job running; a later tick retries. * * @param int $job_id Job ID. * @param string $start A refused AutomationJobManager::START_* result. * @return void */ private function logDeferredStart(int $job_id, string $start): void { $context = ['max_concurrent_jobs' => AutomationConstants::MAX_CONCURRENT_JOBS]; if (AutomationJobManager::START_WRITE_FAILED === $start) { $this->logger->warning($job_id, 'Deferring job start: the running status could not be saved', $context); } elseif (AutomationJobManager::START_LOST === $start) { $this->logger->info($job_id, 'Deferring job start: the job changed status meanwhile', $context); } elseif (AutomationJobManager::START_BUSY === $start) { $this->logger->info($job_id, 'Deferring job start: another automation job was starting at the same moment', $context); } else { $this->logger->info($job_id, 'Deferring job start: maximum concurrent automation jobs already running', $context); } } /** * Cancel a job * * @param int $job_id Job ID to cancel * @return bool Success status * @throws \Exception On cancel failure */ public function cancelJob($job_id) { $job_id = (int) $job_id; $job = $this->job_manager->getJob($job_id); if (!$job) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message, not user-facing output throw new \Exception("Job not found: {$job_id}"); } if ($job->isCompleted()) { throw JobFinishedBeforeCancelException::create(); } $this->writeCancellation($job_id, (string) $job->status); try { $this->queue->forceReleaseAllProcessing((int) $job_id); } catch (\Throwable $release_error) { $this->logger->error($job_id, 'Failed to release claims on cancel', [ 'error' => $release_error->getMessage(), ]); } JobRunHook::clear((int) $job_id); $this->logger->info($job_id, 'Job cancelled by user'); return true; } /** * Store the cancellation of a job read in status $read_status. The write * holds only while the job is still in that status, so a tick that * completed the job meanwhile is never reported as cancelled. A job that * moved (a pause, another tick) is tried once more from the status it * moved to; a job the user cancelled meanwhile counts as cancelled. * * @param int $job_id Job ID. * @param string $read_status Status the cancel read. * @return void * @throws JobFinishedBeforeCancelException When a tick finished the job after the cancel read it. * @throws \Exception When the job kept changing or the write failed. */ private function writeCancellation(int $job_id, string $read_status): void { $from = $read_status; for ($attempt = 1; $attempt <= 2; $attempt++) { $result = $this->job_manager->transitionJobStatus( $job_id, 'failed', [$from], AutomationJobManager::CANCELLED_BY_USER_ERROR_MESSAGE ); if (in_array($result, [AutomationJobManager::TRANSITION_APPLIED, AutomationJobManager::TRANSITION_ALREADY], true)) { return; } if (AutomationJobManager::TRANSITION_ERROR === $result) { throw new JobActionRefusedException(esc_html__('The job could not be cancelled. Try again.', 'ai-product-tools')); } $current = $this->job_manager->getJob($job_id); if (!$current) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message, not user-facing output throw new \Exception("Job not found: {$job_id}"); } if ($this->isCancelledJob($current)) { return; } if ($current->isCompleted()) { throw JobFinishedBeforeCancelException::create(); } $from = (string) $current->status; } throw new JobActionRefusedException(esc_html__('The job changed while it was being cancelled. Try again.', 'ai-product-tools')); } /** * Get job execution progress * * @param int $job_id Job ID * @return array Progress information */ public function getJobProgress($job_id) { $job = $this->job_manager->getJob($job_id); if (!$job) { return []; } $estimated_seconds = $this->estimateRemainingSeconds($job); $max_seconds = AutomationConstants::MAX_COMPLETION_ESTIMATE_DAYS * DAY_IN_SECONDS; return [ 'progress' => $job->progress, 'total_products' => $job->total_products, 'processed_products' => $job->processed_products, 'failed_products' => $job->failed_products, 'status' => $job->status, 'started_at' => $job->started_at, 'estimated_completion' => $this->completionFromSeconds($estimated_seconds), 'estimated_completion_capped' => null !== $estimated_seconds && $estimated_seconds > $max_seconds, ]; } /** * Check if executor can handle specific tool type * * @param string $tool_type Tool type to check * @return bool Whether tool type is supported */ public function supportsToolType($tool_type) { return in_array($tool_type, ['advanced', 'title', 'faq', 'seo_meta', 'image_alt']); } /** * Validate job before execution * * @param AutomationJob $job Job to validate * @return array Validation errors (empty if valid) */ public function validateJobForExecution(AutomationJob $job) { $errors = []; if (!$this->supportsToolType($job->tool_type)) { $errors[] = "Unsupported tool type: {$job->tool_type}"; } $runnable_statuses = ['ready', 'preparing', 'running']; if (JobEntitlementGuard::isRecurring($job->schedule_config)) { $runnable_statuses[] = 'completed'; } if (!in_array($job->status, $runnable_statuses, true)) { $errors[] = "Job cannot be executed in current status: {$job->status}"; } if (empty($job->settings['provider'])) { $errors[] = "AI provider not specified in job settings"; } if (empty($job->settings['model'])) { $errors[] = "AI model not specified in job settings"; } return $errors; } /** * Get AI service for tool type * * @param string $tool_type Tool type * @return object AI service instance * @throws \Exception If tool type is not supported */ private function getAIService($tool_type) { switch ($tool_type) { case 'advanced': return new ContentGenerator(); case 'title': return new TitleGeneratorService(); case 'faq': return new FAQGeneratorService(); case 'seo_meta': return new SeoMetaGeneratorService(); case 'image_alt': return new ImageAltService(); default: // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message, not user-facing output throw new \Exception("Unsupported tool type: {$tool_type}"); } } /** * Update products status * * @param int $job_id Job ID * @param array $product_ids Product IDs * @param string $status New status * @param string|null $error_message Error message */ private function updateProductsStatus($job_id, $product_ids, $status, $error_message = null) { $job_id = (int) $job_id; if (empty($product_ids)) { return; } $ids = array_map('intval', (array) $product_ids); if (empty($ids)) { return; } $placeholders = implode(',', array_fill(0, count($ids), '%d')); $set_parts = ['status = %s']; $params = [$status]; if ($status === 'completed') { $set_parts[] = 'processed_at = %s'; $params[] = JobTime::now(); } if ($error_message !== null && $error_message !== '') { $set_parts[] = 'error_message = %s'; $params[] = $error_message; } else { $set_parts[] = 'error_message = NULL'; } $params_with_ids = $params; $params_with_ids[] = $job_id; $params_with_ids = array_merge($params_with_ids, $ids); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix, dynamic SET and IN() placeholders $sql = $this->wpdb->prepare( "UPDATE {$this->job_products_table} SET " . implode(', ', $set_parts) . " WHERE job_id = %d AND product_id IN ($placeholders)", $params_with_ids ); $this->wpdb->query($sql); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared } /** * Fail legacy Standard-generator jobs without instantiating the retired class. * * @param AutomationJob $job Legacy job row. * @return bool Always false because the job cannot continue. */ private function failRetiredStandardJob(AutomationJob $job): bool { $job_id = (int) $job->id; $message = self::RETIRED_STANDARD_TOOL_MESSAGE; $this->logger->error($job_id, $message, [ 'type' => 'VALIDATION', 'tool_type' => $job->tool_type, ]); $product_ids = $this->getPendingJobProductIds($job_id); if (!empty($product_ids)) { $this->updateProductsStatus($job_id, $product_ids, 'failed', $message); } $this->updateJobProgress($job_id); if (!$this->job_manager->updateJobStatus($job_id, 'failed', $message)) { $this->logger->warning($job_id, 'Could not persist retired Standard job transition to failed', [ 'type' => 'VALIDATION', ]); } return false; } /** * Return the non-terminal (pending/processing) product rows for a job. * * Terminal rows (completed/applied/rejected) are intentionally excluded so * a partially-processed legacy job keeps its already-earned progress. * * @param int $job_id Job ID. * @return int[] Product IDs still awaiting processing. */ private function getPendingJobProductIds(int $job_id): array { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $product_ids = $this->wpdb->get_col( $this->wpdb->prepare( "SELECT product_id FROM {$this->job_products_table} WHERE job_id = %d AND status IN ('pending', 'processing')", $job_id ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared return array_values(array_map('intval', is_array($product_ids) ? $product_ids : [])); } /** * The content settings ResultProcessor::applyResult() runs a job's results * with, built from the job row: the routing status ('draft' is the stored * value of "Stage for Review"), the FAQ write mode, the job owner and the * "only fill empty fields" choice. Public so a test builds the settings * exactly as a real run does instead of writing the keys by hand. * * @param object $job Job row (settings, created_by). * @return array */ public static function contentSettingsForJob($job): array { $content_settings = []; if (!empty($job->settings['contentSettings'])) { $content_settings = $job->settings['contentSettings']; } elseif (!empty($job->settings['content_settings'])) { $content_settings = $job->settings['content_settings']; } $content_status = $content_settings['status'] ?? 'draft'; $normalized = strtolower(is_string($content_status) ? $content_status : 'draft'); $content_settings['status'] = ($normalized === 'draft') ? 'draft' : 'published'; if (isset($job->settings['writeMode'])) { $content_settings['writeMode'] = ('replace' === $job->settings['writeMode'] && apply_filters('aipt_faq_replace_enabled', false)) ? 'replace' : 'append'; } $content_settings['created_by'] = (int) $job->created_by; $content_settings['overwrite'] = OptionsTranslator::overwriteMode(is_array($job->settings) ? $job->settings : []); return $content_settings; } /** * Process generation results * * @param int $job_id Job ID * @param array $results Generation results * @param string|null $claim_token Current claim token, or null for legacy unclaimed callers */ private function processResults($job_id, $results, $claim_token = null) { $job = $this->job_manager->getJob($job_id); if (!$job) { $this->logger->error($job_id, 'Job not found when processing results'); return ['completed' => 0, 'failed' => 0, 'failure_messages' => []]; } if ($this->isCancelledJob($job)) { return ['completed' => 0, 'failed' => 0, 'failure_messages' => [], 'cancelled' => true]; } $this->logger->debug($job_id, 'Raw job settings for content parsing', [ 'all_settings' => $job->settings, 'contentSettings_key' => $job->settings['contentSettings'] ?? 'not_found', 'content_settings_key' => $job->settings['content_settings'] ?? 'not_found' ]); $content_settings = self::contentSettingsForJob($job); $this->logger->debug($job_id, 'Processing results with content status: ' . $content_settings['status'], [ 'results_count' => count($results), 'content_settings' => $content_settings, 'raw_results_sample' => array_slice($results, 0, 2) ]); $content_items = []; $error_items = []; if (is_array($results)) { foreach ($results as $rawItem) { if (!is_array($rawItem)) { continue; } if (!empty($rawItem['api_error'])) { $providerName = isset($rawItem['provider']) ? (string)$rawItem['provider'] : 'API'; $productId = isset($rawItem['product_id']) ? (int)$rawItem['product_id'] : null; $apiError = (string) $rawItem['api_error']; $truncated = $this->truncateErrorMessage($apiError, AutomationConstants::MAX_ERROR_MESSAGE_LENGTH); if ($productId) { $this->logger->error($job_id, $apiError, [ 'type' => 'AI_PROVIDER', 'product_id' => $productId, 'provider' => $providerName, ]); if (!isset($error_items[$productId])) { $error_items[$productId] = $truncated; } } else { $this->logger->warning($job_id, 'API error without product context: ' . $apiError, [ 'type' => 'AI_PROVIDER', 'provider' => $providerName, 'api_error' => $apiError, ]); } continue; } $isAttachmentLevelImageError = !empty($rawItem['error']) && isset($rawItem['attachment_id'], $rawItem['status']) && (int) $rawItem['attachment_id'] > 0 && in_array(sanitize_text_field((string)$rawItem['status']), ['error', 'rejected'], true); if (!empty($rawItem['error']) && empty($rawItem['type']) && !$isAttachmentLevelImageError) { $productId = isset($rawItem['product_id']) ? (int)$rawItem['product_id'] : null; if ($productId && !isset($error_items[$productId])) { $error_items[$productId] = $this->truncateErrorMessage((string)$rawItem['error'], AutomationConstants::MAX_ERROR_MESSAGE_LENGTH); } continue; } $content_items[] = $rawItem; } } $unified_results = []; if (!empty($content_items)) { $unified_results = $this->result_processor->transformToUnifiedFormat($job_id, $content_items); } $completed_count = 0; $failed_count = 0; $failure_messages = []; $processed_product_ids = []; foreach ($error_items as $productId => $errorMsg) { if (!isset($processed_product_ids[$productId])) { if (!$this->persistTerminalFailure($job_id, $productId, $errorMsg, $claim_token)) { return ['completed' => $completed_count, 'failed' => $failed_count, 'failure_messages' => $failure_messages, 'claim_lost' => true]; } $processed_product_ids[$productId] = true; $failure_messages[$productId] = $errorMsg; $failed_count++; } } foreach ($unified_results as $result) { if (!isset($result['product_id']) || !is_numeric($result['product_id'])) { $this->logger->warning($job_id, 'Skipping result without valid product_id', [ 'product_id' => $result['product_id'] ?? null, 'fields' => array_keys($result), ]); continue; } $productId = (int)$result['product_id']; $result['created_by'] = (int) $job->created_by; if (isset($processed_product_ids[$productId])) { continue; } $item_content_settings = $content_settings; $heldBack = $this->blueprintHeldBackRouting($result, $content_settings); if (null !== $heldBack) { if (!$heldBack['routeToDraft']) { if (!$this->persistTerminalFailure($job_id, $productId, $heldBack['message'], $claim_token, $result)) { return ['completed' => $completed_count, 'failed' => $failed_count, 'failure_messages' => $failure_messages, 'claim_lost' => true]; } $processed_product_ids[$productId] = true; $failure_messages[$productId] = $heldBack['message']; $failed_count++; continue; } $item_content_settings = array_merge($content_settings, ['status' => 'draft']); } if (!$this->result_processor->hasApplicableContent($result)) { $no_content_message = $this->isBlockedByTheEngine($result) ? BlueprintIntegration::heldBackMessage($result) : ResultProcessor::NO_APPLICABLE_CONTENT_MESSAGE; $this->logger->warning($job_id, $no_content_message, [ 'product_id' => $productId, 'type' => 'AI_RESPONSE', ]); if (!$this->persistTerminalFailure($job_id, $productId, $no_content_message, $claim_token)) { return ['completed' => $completed_count, 'failed' => $failed_count, 'failure_messages' => $failure_messages, 'claim_lost' => true]; } $processed_product_ids[$productId] = true; $failure_messages[$productId] = $no_content_message; $failed_count++; continue; } if (null !== $heldBack) { $this->logger->info($job_id, sprintf( /* translators: %s: why the result needs review. */ __('The result needs review, so it is not applied: %s', 'ai-product-tools'), $heldBack['message'] ), [ 'product_id' => $productId, ]); } try { if ($this->isCancelledJob($this->job_manager->getJob($job_id))) { return ['completed' => $completed_count, 'failed' => $failed_count, 'failure_messages' => $failure_messages, 'cancelled' => true]; } $outcome = $this->result_processor->applyResult($result, $item_content_settings); $success_line = $this->successLogMessage($outcome); if ('waiting' === $outcome) { $outcome = 'unchanged'; } if (!$this->persistTerminalSuccess($job_id, $productId, $result, $claim_token)) { return ['completed' => $completed_count, 'failed' => $failed_count, 'failure_messages' => $failure_messages, 'claim_lost' => true]; } $this->logger->info( $job_id, $success_line, [ 'product_id' => $productId, 'destination' => $outcome, ] ); do_action('aipt_automation_result_succeeded', (int) $job_id, (int) $productId); $processed_product_ids[$productId] = true; $completed_count++; } catch (\Exception $e) { $this->logger->error($job_id, 'Failed to save result', [ 'product_id' => $productId, 'error' => $e->getMessage() ]); $error_message = 'Save failed: ' . $e->getMessage(); if (!$this->persistTerminalFailure($job_id, $productId, $error_message, $claim_token)) { return ['completed' => $completed_count, 'failed' => $failed_count, 'failure_messages' => $failure_messages, 'claim_lost' => true]; } $processed_product_ids[$productId] = true; $failure_messages[$productId] = $error_message; $failed_count++; } } return ['completed' => $completed_count, 'failed' => $failed_count, 'failure_messages' => $failure_messages]; } private function persistTerminalSuccess($job_id, $product_id, array $result, $claim_token = null) { if (is_string($claim_token) && $claim_token !== '') { return $this->queue->markCompleted((int)$job_id, (int)$product_id, $claim_token, $result); } $this->result_processor->recordSuccess((int)$job_id, (int)$product_id, $result); return true; } private function persistTerminalFailure($job_id, $product_id, $message, $claim_token = null, array $result_payload = []) { if (is_string($claim_token) && $claim_token !== '') { return $this->queue->markFailed((int)$job_id, (int)$product_id, $claim_token, (string)$message, $result_payload ?: null); } $this->result_processor->recordFailure((int)$job_id, (int)$product_id, (string)$message, $result_payload); return true; } /** * Whether a content structure unified result must not go through the * normal apply/review routing as-is, and if so what to do about it. * * A legacy/advanced result (no executionPath key, or 'advanced') is * never held back here: BlueprintIntegration only attaches eligibility * to Blueprint-path results, so this returns null for every job that * does not run the Blueprint path — legacy automation behavior stays * byte-identical. * * @param array $result Unified per-product result (ResultProcessor::transformToUnifiedFormat()). * @param array $content_settings Job content settings (status: 'draft'|'published'). * @return array{routeToDraft:bool,message:string}|null */ private function blueprintHeldBackRouting(array $result, array $content_settings): ?array { if ('blueprint' !== ($result['executionPath'] ?? null)) { return null; } $status = strtolower((string) ($content_settings['status'] ?? 'published')); $destination = 'draft' === $status ? BlueprintIntegration::DESTINATION_REVIEW : BlueprintIntegration::DESTINATION_APPLY; if (!BlueprintIntegration::isHeldBack($result, $destination)) { return null; } $can_route_to_draft = BlueprintIntegration::DESTINATION_APPLY === $destination && (bool) apply_filters('aipt_content_review_enabled', false); return [ 'routeToDraft' => $can_route_to_draft, 'message' => BlueprintIntegration::heldBackMessage($result), ]; } /** * Whether a unified result is a Blueprint run the engine itself blocked * (`eligibility.canApply` false - every AI unit the run asked for * failed). A legacy/advanced result (no `executionPath`, or one whose * canApply is true or absent) is never "blocked by the engine" here. * * @param array $result Unified per-product result. * @return bool */ private function isBlockedByTheEngine(array $result): bool { if ('blueprint' !== ($result['executionPath'] ?? null)) { return false; } $eligibility = $result['eligibility'] ?? null; return is_array($eligibility) && array_key_exists('canApply', $eligibility) && empty($eligibility['canApply']); } /** * Pause a job whose run cannot honor its paid behavior, before any * provider call, storing the user-visible reason. * * @param int $job_id Job ID. * @param array $block JobEntitlementGuard denial descriptor. * @param string[] $from The status the tick read; a pause or a cancel since then is kept. * @return void */ private function pauseForEntitlement(int $job_id, array $block, array $from): void { if (!$this->job_manager->updateJobStatus($job_id, 'paused', (string) $block['message'], $from)) { $this->logger->info($job_id, 'Entitlement pause skipped: the job changed meanwhile, its status was left as it is'); return; } $this->logger->warning($job_id, 'Job paused before generation: paid behavior cannot be honored', [ 'reason' => $block['reason'], 'feature' => $block['feature'], 'keys' => $block['keys'], ]); JobRunHook::clear((int) $job_id); } /** * A tick that found the merchant's monthly spend limit reached: keep one * future tick so the job looks again in SPEND_LIMIT_WAIT_SECONDS (a * running job without one would be re-armed by the monitor with a warning * every five minutes), and say why in the job's log once a day, not on * every tick. * * @param int $job_id Job ID. * @return void */ private function waitForSpendLimit(int $job_id): void { if (false === JobRunHook::next_run($job_id) && false === JobRunHook::schedule($job_id, time() + AutomationConstants::SPEND_LIMIT_WAIT_SECONDS)) { $this->logger->warning($job_id, 'Failed to schedule the next look at the monthly spend limit', ['hook' => JobRunHook::HOOK]); } $context = ['month' => gmdate('Y_m'), 'limit_micros' => SpendLimit::limitMicros()]; if ($this->shouldLogDebugSnapshot($job_id, 'spend_limit_wait', $context, DAY_IN_SECONDS)) { $this->logger->info($job_id, 'Waiting: the monthly AI spend limit is reached. The job goes on by itself when the month changes or the limit is raised.', $context); } } /** * Pause the job after a permanent, run-wide provider failure (a bad or * revoked key, no access to the model, an unknown model, an exhausted * quota, a missing key, AI turned off, or an unsupported provider), or * after a rate limit that outlasted an item's retries (the account's own * ceiling, Help Scout #921): * every further call this run would fail the identical way, so the job * stops instead of burning through its remaining products one doomed * call at a time. Mirrors pauseForEntitlement()'s pause-with-reason * shape; unlike a pool reset, the already-queued rows are left exactly * as they are (the caller already requeued the current item) so a * resume continues where the job left off. * * @param int $job_id Job ID. * @param ProviderCallException $failure The permanent run-wide failure. * @param string $provider_id AIPT provider id this call used. * @param string $merchant_message The merchant-facing sentence to store as the job's error. * @param string[] $from The status read before this item; a pause or a cancel since then is kept. * @return void */ private function pauseForProviderFailure(int $job_id, ProviderCallException $failure, string $provider_id, string $merchant_message, array $from): void { if (!$this->job_manager->updateJobStatus($job_id, 'paused', $merchant_message, $from)) { $this->logger->info($job_id, 'Provider failure pause skipped: the job changed meanwhile, its status was left as it is', [ 'reason' => $failure->reason(), ]); return; } $this->logger->warning($job_id, $merchant_message, [ 'reason' => $failure->reason(), 'provider' => $provider_id, 'type' => 'PROVIDER', ]); $pauseContext = ['job_id' => $job_id, 'provider' => $provider_id, 'reason' => $failure->reason()]; if (ProviderCallException::isSetupReason($failure->reason())) { Logger::debug('automation', 'Job paused, provider setup incomplete', $pauseContext); } else { Logger::error('automation', 'Job paused after a provider failure', $pauseContext); } JobRunHook::clear((int) $job_id); } /** * The sentence the merchant sees for a failed call: the provider failure's own * message, except for an unknown model that is a custom model the owner added. * That one is named, with the two ways out: a paused job cannot be edited, so * the merchant duplicates it with another model, or checks the model again in * Settings when the provider brought it back. * * @param \Throwable $failure What the call threw. * @param string $provider_id AIPT provider id the call used. * @param string $model Model id the call used (the job's translated option). * @return string */ private function providerFailureMessage(\Throwable $failure, string $provider_id, string $model): string { if ( $failure instanceof ProviderCallException && ProviderCallException::MODEL_NOT_FOUND === $failure->reason() && '' !== $model && null !== CustomModelStore::find($provider_id, $model) ) { return sprintf( /* translators: %s: the model id the job uses */ __('The model %s is no longer available from the provider. Duplicate this job with another model, or check the model again in Settings.', 'ai-product-tools'), $model ); } return ProviderCallException::displayMessage($failure, $provider_id); } /** * Pause a job whose last ticks finished no product (StallTracker), with * the reason the merchant sees. Its rows are left as they are, so a * resume continues where the job stopped. * * @param int $job_id Job ID. * @return void */ private function pauseForStall(int $job_id): void { $this->stall_tracker->resetTicks($job_id); $message = sprintf( /* translators: %d: number of attempts in a row */ __('The job tried %d times in a row and could not finish a product, so it was paused. Resume it to try again. If it pauses again, the server may be ending long requests; the job log has the details.', 'ai-product-tools'), StallTracker::MAX_TICKS_WITHOUT_PROGRESS ); if (!$this->job_manager->updateJobStatus($job_id, 'paused', $message, ['running'])) { $this->logger->info($job_id, 'Stall pause skipped: the job changed meanwhile, its status was left as it is'); return; } $this->logger->warning($job_id, 'Job paused: its last ticks finished no product', [ 'ticks' => StallTracker::MAX_TICKS_WITHOUT_PROGRESS, ]); Logger::error('automation', 'Job paused after ticks that finished no product', [ 'job_id' => $job_id, 'ticks' => StallTracker::MAX_TICKS_WITHOUT_PROGRESS, ]); JobRunHook::clear((int) $job_id); } /** * Why a product failed after its generation was interrupted every time, * stored on the product's row. * * @return string */ private static function interruptedProductMessage(): string { return sprintf( /* translators: %d: number of interrupted attempts */ __('Generating this product was interrupted %d times before it could finish, so it was skipped. Retry the failed products to try it again.', 'ai-product-tools'), StallTracker::MAX_INTERRUPTED_ATTEMPTS ); } /** * Let the tick finish the product it is on. PHP's own time limit (30 * seconds by default, counted in wall-clock time on some hosts) would end * the request inside a provider call that is still running, losing an * answer that was paid for, and a browser runner that stops waiting must * not end it either. The tick's own budget still decides when it stops * starting products; a host's hard limit can still end the request, which * StallTracker counts. * * @return void */ private function liftTimeLimit(): void { $disabled = (string) ini_get('disable_functions'); if (function_exists('ignore_user_abort') && false === strpos($disabled, 'ignore_user_abort')) { ignore_user_abort(true); } if (function_exists('set_time_limit') && false === strpos($disabled, 'set_time_limit')) { set_time_limit(0); } } /** * Report the definitive denials a run falls back to Free behavior for. * * @param int $job_id Job ID. * @param array $clamps JobEntitlementGuard::assessRun() clamps. * @return void */ private function logRunClamps(int $job_id, array $clamps): void { foreach ($clamps as $clamp) { $this->logger->warning($job_id, $clamp['message'], [ 'reason' => $clamp['reason'], 'feature' => $clamp['feature'], 'keys' => $clamp['keys'], ]); } } /** * Surface Description's "sections from your store" skip notices * ("What customers say", "Compare with similar products") to this * job's own Logs modal, each the first time it actually fires for a * real product this tick — whichever of StoreSectionsPolicy's clamp * reasons applies: not entitled at all (e.g. * 'description:customerReviews'), or entitled but this run publishes * without review ('description:customerReviewsAutomation'). A * reviewGuaranteed=true run's not-entitled clamp is ALSO staged into * Content Review (see Premium\ContentReview\ReviewStager and * ContentReviewStore's section_notices), so that case is reported * twice, truthfully; a reviewGuaranteed=false run has no other channel * at all, since nothing is staged into review for it. * * EntitlementPolicy::apply()'s appliedFreeDefaults rides on every row * generateForAutomationProduct() returns via * BlueprintIntegration::responseFields() (merged into each row by * transformContentGeneratorResult()); this is the only place those * notices are read and logged — without it, the clamp still correctly * withholds the section, but nothing ever tells the merchant why. * * @param int $job_id Job id. * @param array $results generateForAutomationProduct()'s rows for one product. * @param array &$logged_keys Notice keys already logged this tick, updated in place. * @return void */ private function logStoreSectionClampNotices(int $job_id, array $results, array &$logged_keys): void { $notice_types = StoreSectionsPolicy::noticeTypesByKey(); foreach ($results as $row) { if (!is_array($row) || empty($row['appliedFreeDefaults']) || !is_array($row['appliedFreeDefaults'])) { continue; } foreach ($row['appliedFreeDefaults'] as $applied) { $key = is_array($applied) ? (string) ($applied['key'] ?? '') : ''; if (!isset($notice_types[$key]) || isset($logged_keys[$key])) { continue; } $this->logger->warning($job_id, (string) ($applied['reason'] ?? ''), [ 'key' => $key, ]); $logged_keys[$key] = true; } } } /** * Start the due cycle of a waiting recurring job. Without the recurring * entitlement the cycle is refused: next_run stays due and the stored job * says why. An entitled cycle is started by the Premium build * (`aipt_automation_start_recurring_cycle`): it moves next_run to the * following cycle, re-pins the saved structure choice and resets the pool * so it is rebuilt from the saved filter. * * @param AutomationJob $job Ready or completed recurring job whose cycle is due. * @return bool True when the cycle started (job is now preparing). */ private function startRecurringCycle(AutomationJob $job): bool { $job_id = (int) $job->id; $block = JobEntitlementGuard::recurringBlock(JobEntitlementGuard::CONTEXT_REARM); if (null !== $block) { $this->job_manager->updateJobStatus( $job_id, PlanDenial::isVerificationUnavailable($block['reason']) ? 'paused' : 'completed', $block['message'] ); $this->logger->warning($job_id, 'Recurring cycle not started: recurring schedule cannot be honored', [ 'reason' => $block['reason'], 'feature' => $block['feature'], ]); JobRunHook::clear((int) $job_id); return false; } /** * Start the due cycle of a recurring job the plan can run. * * The Premium RecurringCycleService is the sole registrant; without it * no cycle starts. * * @since 2.8.0 * * @param bool $started Whether the cycle started (the job is now preparing). Default false. * @param AutomationJob $job The job whose cycle is due. * @param AutomationJobManager $job_manager Job manager. * @param JobLoggerInterface $logger Job logger. */ return (bool) apply_filters('aipt_automation_start_recurring_cycle', false, $job, $this->job_manager, $this->logger); } /** * Whether the job has any pool rows. * * @param int $job_id Job ID. * @return bool */ private function hasPoolRows(int $job_id): bool { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix return (int) $this->wpdb->get_var( $this->wpdb->prepare( "SELECT COUNT(*) FROM {$this->job_products_table} WHERE job_id = %d", $job_id ) ) > 0; // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared } private function isCancelledJob(?AutomationJob $job): bool { return null === $job || 'cancelled' === $job->status || ('failed' === $job->status && AutomationJobManager::CANCELLED_BY_USER_ERROR_MESSAGE === $job->error_message); } /** * Truncate error message to specified length with ellipsis. * * @param string $message Message to truncate * @param int $maxLength Maximum length * @return string Truncated message */ private function truncateErrorMessage(string $message, int $maxLength): string { if ($maxLength <= 3) { return $maxLength > 0 ? str_repeat('.', $maxLength) : ''; } $len = function_exists('mb_strlen') ? mb_strlen($message) : strlen($message); if ($len > $maxLength) { $truncateAt = $maxLength - 3; return (function_exists('mb_substr') ? mb_substr($message, 0, $truncateAt) : substr($message, 0, $truncateAt)) . '...'; } return $message; } /** * Update job progress * * @param int $job_id Job ID */ private function updateJobProgress($job_id) { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $stats = $this->wpdb->get_row( $this->wpdb->prepare( "SELECT COUNT(*) as total, SUM(CASE WHEN status IN ('completed', 'applied') THEN 1 ELSE 0 END) as completed, SUM(CASE WHEN status IN ('failed', 'rejected') THEN 1 ELSE 0 END) as failed FROM {$this->job_products_table} WHERE job_id = %d", $job_id ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared if ($stats) { $this->job_manager->updateJobProgress( $job_id, (int) $stats['completed'], (int) $stats['failed'] ); } } /** * Describe current job product queue state for logging/diagnostics. * * @param int $job_id * @return array */ private function describeJobProductState(int $job_id): array { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $row = $this->wpdb->get_row( $this->wpdb->prepare( "SELECT SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending, SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END) AS processing, SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed, SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed, MIN(CASE WHEN status = 'processing' THEN processing_started_at END) AS oldest_processing_started_at, MAX(CASE WHEN status = 'processing' THEN processing_started_at END) AS newest_processing_started_at, MIN(CASE WHEN status = 'pending' THEN created_at END) AS oldest_pending_created_at FROM {$this->job_products_table} WHERE job_id = %d", $job_id ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared $state = [ 'pending' => 0, 'processing' => 0, 'completed' => 0, 'failed' => 0, ]; if (is_array($row)) { $state['pending'] = (int) ($row['pending'] ?? 0); $state['processing'] = (int) ($row['processing'] ?? 0); $state['completed'] = (int) ($row['completed'] ?? 0); $state['failed'] = (int) ($row['failed'] ?? 0); $totalRows = array_sum([$state['pending'], $state['processing'], $state['completed'], $state['failed']]); $state['total_rows'] = $totalRows; $now = time(); if (!empty($row['oldest_processing_started_at'])) { $ts = JobTime::toTimestamp($row['oldest_processing_started_at']); if ($ts !== false) { $state['oldest_processing_started_at'] = UtcTimestamp::fromStored($row['oldest_processing_started_at'], false); $state['oldest_processing_age_sec'] = max(0, $now - $ts); } } if (!empty($row['newest_processing_started_at'])) { $ts = JobTime::toTimestamp($row['newest_processing_started_at']); if ($ts !== false) { $state['newest_processing_started_at'] = UtcTimestamp::fromStored($row['newest_processing_started_at'], false); $state['newest_processing_age_sec'] = max(0, $now - $ts); } } if (!empty($row['oldest_pending_created_at'])) { $ts = JobTime::toTimestamp($row['oldest_pending_created_at']); if ($ts !== false) { $state['oldest_pending_created_at'] = UtcTimestamp::fromStored($row['oldest_pending_created_at'], false); $state['oldest_pending_age_sec'] = max(0, $now - $ts); } } } else { $state['total_rows'] = 0; } return $state; } /** * The memory one tick may use: past `ceiling` the tick stops early, and * memory pressure, which shrinks the claim window, is the share of the * span from `floor` to `ceiling` in use. * * With a readable memory_limit the ceiling is 70% of it, leaving headroom * below PHP's fatal error, and the floor is zero. WP_MEMORY_LIMIT is not * read: WordPress only raises memory_limit to it when the limit is lower, * so memory_limit is already the real ceiling, while WP_MEMORY_LIMIT (40M * by default) is below what a WooCommerce request uses, and as a cap it * stopped every tick after one product. * * An unlimited memory_limit (-1, as cron often runs under WP-CLI) or one * that cannot be read leaves PHP no point to fail at, so the tick may grow * AutomationConstants::DEFAULT_MEMORY_LIMIT_MB over the memory it started * with. A fixed ceiling there stopped every tick after one product on a * store whose memory use was above it before the tick began. * * @param int $startUsage memory_get_usage(true) when the tick starts. * @return array{floor: int, ceiling: int} */ private function tickMemoryBudget(int $startUsage): array { $unlimited = [ 'floor' => $startUsage, 'ceiling' => $startUsage + AutomationConstants::DEFAULT_MEMORY_LIMIT_MB * 1024 * 1024, ]; if (!\function_exists('wp_convert_hr_to_bytes')) { return $unlimited; } $iniLimit = \ini_get('memory_limit'); if (!$iniLimit || '-1' === $iniLimit) { return $unlimited; } $bytes = \wp_convert_hr_to_bytes($iniLimit); return $bytes > 0 ? ['floor' => 0, 'ceiling' => (int) floor($bytes * 0.7)] : $unlimited; } /** * Get adaptive window size based on server capacity and recent performance * * Adjusts batch size dynamically: * - Reduces if memory pressure is high * - Reduces if recent errors detected * - Increases if system is healthy and fast * * @param int $job_id Job ID for error rate lookup * @param array{floor: int, ceiling: int} $memoryBudget The tick's memory budget (tickMemoryBudget()). * @return int Optimal window size for current conditions */ private function getAdaptiveWindowSize(int $job_id, array $memoryBudget): int { $base = AutomationConstants::windowSize(); if (function_exists('memory_get_usage')) { $currentMem = memory_get_usage(true); $room = $memoryBudget['ceiling'] - $memoryBudget['floor']; $memRatio = $room > 0 ? (($currentMem - $memoryBudget['floor']) / $room) : 0; if ($memRatio > 0.8) { $base = (int) floor($base * 0.5); } elseif ($memRatio > 0.6) { $base = (int) floor($base * 0.75); } } $errorRateKey = 'aipt_job_error_rate_' . $job_id; $recentErrors = 0; if (function_exists('get_transient')) { $recentErrors = (int) get_transient($errorRateKey); } if ($recentErrors >= AutomationConstants::ERROR_THROTTLE_THRESHOLD) { $base = (int) floor($base * 0.5); } elseif ($recentErrors >= 2) { $base = (int) floor($base * 0.75); } $maxExecTime = (int) ini_get('max_execution_time'); if ($maxExecTime > 0 && $maxExecTime < 30) { $base = (int) floor($base * 0.6); } return max(self::MIN_WINDOW_SIZE, min(self::MAX_WINDOW_SIZE, $base)); } /** * Record error for adaptive throttling * * @param int $job_id Job ID */ private function recordErrorForThrottling(int $job_id): void { if (!function_exists('get_transient') || !function_exists('set_transient')) { return; } $key = 'aipt_job_error_rate_' . $job_id; $current = (int) get_transient($key); set_transient($key, $current + 1, AutomationConstants::ERROR_THROTTLE_WINDOW_SECONDS); } /** * Reset error counter on successful processing * * @param int $job_id Job ID */ private function resetErrorThrottling(int $job_id): void { if (function_exists('delete_transient')) { delete_transient('aipt_job_error_rate_' . $job_id); } } /** * Prevent noisy debug logs by caching snapshot hashes per job/slug. */ private function shouldLogDebugSnapshot(int $job_id, string $slug, array $context, int $ttl = AutomationConstants::DEBUG_SNAPSHOT_TTL): bool { if (!function_exists('get_transient') || !function_exists('set_transient')) { return true; } try { ksort($context); } catch (\Throwable $t) { } $hash = md5(wp_json_encode($context)); $key = 'aipt_jobdbg_' . $slug . '_' . $job_id; $stored = get_transient($key); if ($stored === $hash) { return false; } set_transient($key, $hash, $ttl); return true; } /** * Acquire per-job execution lock using atomic add_option() * * Uses add_option() for atomic check-and-set to prevent TOCTOU race conditions. * add_option() returns false if option already exists, providing atomicity. */ private function acquireLock(int $job_id): bool { $key = 'aipt_job_lock_' . $job_id; $token = wp_generate_password(AutomationConstants::LOCK_TOKEN_LENGTH, false, false); $lock_data = wp_json_encode([ 'token' => $token, 'expires' => time() + AutomationConstants::lockTtl(), ]); $acquired = add_option($key, $lock_data, '', 'no'); if ($acquired) { $this->lock_tokens[$job_id] = $token; return true; } $existing = get_option($key); if ($existing) { $data = json_decode($existing, true); if (is_array($data) && isset($data['expires']) && time() > (int) $data['expires']) { wp_cache_delete($key, 'options'); $fresh_existing = get_option($key); $fresh_data = json_decode($fresh_existing, true); if (is_array($fresh_data) && isset($fresh_data['expires']) && time() > (int) $fresh_data['expires']) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- A guarded UPDATE on wp_options is the point: update_option() offers no compare-and-swap, and the cache is invalidated right after. $swapped = $wpdb->update( $wpdb->options, ['option_value' => $lock_data], ['option_name' => $key, 'option_value' => $fresh_existing], ['%s'], ['%s', '%s'] ); wp_cache_delete($key, 'options'); $acquired = 1 === (int) $swapped; } else { $acquired = false; } if ($acquired) { $this->lock_tokens[$job_id] = $token; return true; } } } return false; } /** * Release per-job execution lock (only if we own it) * * Only releases the lock if our stored token matches the one in the option, * preventing accidental release of another process's lock. */ private function releaseLock(int $job_id): void { $key = 'aipt_job_lock_' . $job_id; $myToken = $this->lock_tokens[$job_id] ?? null; if ($myToken) { $existing = get_option($key); if ($existing) { $data = json_decode($existing, true); if (is_array($data) && isset($data['token']) && $data['token'] === $myToken) { delete_option($key); } } } unset($this->lock_tokens[$job_id]); } /** * Renew a currently-held per-job execution lock's TTL. * * acquireLock() sets a fixed one-shot "expires" that a long-running tick * can outlive while still legitimately in flight (one product's provider * work can make several calls, each with a retry). This refreshes the * option's "expires", before each product and before each provider * attempt, so a slow-but-alive tick is never mistaken for an * abandoned one and stolen mid-flight. It only extends a lock we can * prove (via our own stored token) that we still hold; it never blindly * overwrites, so it cannot revive a lock another executor has already * taken over. * * @param int $job_id Job ID. * @return bool True if the lock is confirmed ours and was renewed. */ private function renewLock(int $job_id): bool { $myToken = $this->lock_tokens[$job_id] ?? null; if (!$myToken) { return false; } $key = 'aipt_job_lock_' . $job_id; wp_cache_delete($key, 'options'); $existing = get_option($key); if (!$existing) { return false; } $data = json_decode($existing, true); if (!is_array($data) || !isset($data['token']) || $data['token'] !== $myToken) { return false; } $lock_data = wp_json_encode([ 'token' => $myToken, 'expires' => time() + AutomationConstants::lockTtl(), ]); global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- A guarded UPDATE on wp_options is the point: update_option() offers no compare-and-swap, and the cache is explicitly invalidated on both sides of this write. $renewed = $wpdb->update( $wpdb->options, ['option_value' => $lock_data], ['option_name' => $key, 'option_value' => $existing], ['%s'], ['%s', '%s'] ); wp_cache_delete($key, 'options'); if (false === $renewed) { return false; } if (0 === (int) $renewed) { $after = get_option($key); $after_data = is_string($after) ? json_decode($after, true) : null; return is_array($after_data) && isset($after_data['token']) && $after_data['token'] === $myToken; } return true; } /** * One product's provider work, with the job lock renewed and the * product's claim checked right before each provider attempt it makes * (ProviderCallHeartbeat). A product can make several calls, each with a * retry, and outlast the lock; another tick would then take the job and * pay the provider for the same product again. * * Once the lock or the claim is gone, that attempt is refused and so is * every later one. What the work does with the refusal does not matter: * a generator may let it through, turn it into an error row or return * what an earlier call produced. The record of the loss decides, and the * work's result is dropped. * * @param int $job_id Job ID. * @param int $product_id Product ID. * @param string $claim_token This tick's claim token for the product. * @param callable $work fn(): array, the product's provider work. * @return array|null The work's results, or null when the tick lost the lock or the claim during the work (heldWorkLost says which). * @throws \Throwable What the work threw while the tick still held the job and the product. */ private function generateWhileHeld(int $job_id, int $product_id, string $claim_token, callable $work): ?array { $this->heldWorkLost = null; try { $results = ProviderCallHeartbeat::run( function () use ($job_id, $product_id, $claim_token): void { $this->confirmHeldBeforeAttempt($job_id, $product_id, $claim_token); }, $work ); } catch (\Throwable $t) { if (null === $this->heldWorkLost) { throw $t; } return null; } return null === $this->heldWorkLost ? $results : null; } /** * Heartbeat listener of one product's provider work: renew the job lock, * then check the product's claim, right before a provider attempt. * * @param int $job_id Job ID. * @param int $product_id Product ID. * @param string $claim_token This tick's claim token for the product. * @return void * @throws JobLockLostException When the lock or the claim is gone; after that, at every later attempt without another query. */ private function confirmHeldBeforeAttempt(int $job_id, int $product_id, string $claim_token): void { if (null === $this->heldWorkLost) { if (!$this->renewLock($job_id)) { $this->heldWorkLost = 'lock_lost'; } elseif (!$this->queue->ownsClaim($job_id, $product_id, $claim_token)) { $this->heldWorkLost = 'claim_lost'; } } if (null !== $this->heldWorkLost) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception with a fixed message; the tick drops whatever the work makes of it. throw JobLockLostException::forReason($this->heldWorkLost); } } /** * Job log line for one product's apply outcome. * * @param string $outcome 'draft' (sent to To review), 'published', 'waiting' or 'unchanged' from ResultProcessor::applyResult(). */ private function successLogMessage(string $outcome): string { if ('draft' === $outcome) { return __('Sent the result to To review', 'ai-product-tools'); } if ('waiting' === $outcome) { return __('Left the product unchanged: its proposals already wait in To review', 'ai-product-tools'); } if ('unchanged' === $outcome) { return __('Left the product unchanged: nothing needed to be written', 'ai-product-tools'); } return __('Updated the product', 'ai-product-tools'); } /** * Estimate job completion time using actual processing times * * Uses moving average of real processing durations from job_products table * to provide accurate ETA that excludes cron idle time between ticks. * * @param AutomationJob $job Job instance * @return float|null Estimated seconds until the job finishes, before the clamp; null when unknown */ private function estimateRemainingSeconds(AutomationJob $job) { if ($job->status !== 'running' || $job->processed_products == 0) { return null; } $remaining_products = max(0, $job->total_products - ($job->processed_products + $job->failed_products)); if ($remaining_products <= 0) { return null; } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $sample_size = min(AutomationConstants::MAX_SAMPLE_SIZE, max(AutomationConstants::MIN_SAMPLE_SIZE, $job->processed_products)); $avg_seconds = $this->wpdb->get_var( $this->wpdb->prepare( "SELECT AVG(TIMESTAMPDIFF(SECOND, processing_started_at, processed_at)) FROM ( SELECT processing_started_at, processed_at FROM {$this->job_products_table} WHERE job_id = %d AND status = 'completed' AND processing_started_at IS NOT NULL AND processed_at IS NOT NULL AND processed_at > processing_started_at ORDER BY processed_at DESC LIMIT %d ) AS recent_products", (int) $job->id, $sample_size ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if (!$avg_seconds || $avg_seconds <= 0) { $started_ts = JobTime::toTimestamp($job->started_at); $elapsed_time = false !== $started_ts ? time() - $started_ts : 0; if ($elapsed_time > 0 && $job->processed_products > 0) { $avg_seconds = $elapsed_time / $job->processed_products; } else { return null; } } $cron_overhead_per_item = AutomationConstants::rescheduleDelay() / AutomationConstants::windowSize(); $effective_avg = (float) $avg_seconds + $cron_overhead_per_item; return $remaining_products * $effective_avg; } /** * @param float|null $estimated_seconds From estimateRemainingSeconds(). * @return string|null Completion time in UTC 'Y-m-d H:i:s', clamped to MAX_COMPLETION_ESTIMATE_DAYS */ private function completionFromSeconds($estimated_seconds) { if (null === $estimated_seconds) { return null; } $max_seconds = AutomationConstants::MAX_COMPLETION_ESTIMATE_DAYS * DAY_IN_SECONDS; return gmdate('Y-m-d H:i:s', time() + (int) min($estimated_seconds, $max_seconds)); } /** * Call a generator's Blueprint-aware entry point for one Automation * product, keeping the trusted facts scoped to this one call only. * * This job's own "Content structure" choice — already computed into * $options['jobMode']/['legacyPrompts'] by OptionsTranslator from the * job's DB-stored settings, never from a live REST request — is set as * BlueprintIntegration's ambient trusted facts for the duration of this * one call only, then cleared (finally), so each generator's own * Blueprint fork reads the job's real choice instead of silently * falling through to the generator's site-wide mode. Because the * channel is ambient rather than threaded through $options itself, a * REST-shaped options array (bulk generate, Product Editor, the * metabox) has no way to reach it: those callers never run through * this method, so the channel stays empty for them and their execution * path is unaffected. * * Every automation generator catches its own provider failures internally * and returns a failed row - carrying api_error/error plus a providerError * (ProviderCallException::toResponseArray()) shape - instead of throwing. * Before returning, this inspects the row(s) and rebuilds + throws a * ProviderCallException when one is run-wide, so the tick loop's * catch(\Throwable) block (executeJob()) still classifies it: see * throwForRunWideProviderFailure(). * * @param object $service One of TitleGeneratorService|FAQGeneratorService|SeoMetaGeneratorService|ImageAltService|ContentGenerator. * @param int $product_id Product id for this call. * @param array $options This job's translated options (OptionsTranslator::translate()). * @param int $created_by This job's creator, set as BlueprintIntegration's * ambient acting user for the same call window as the * trusted facts above: WP-Cron runs with no logged-in * user, so the engine's object-permission check * (ExecutionContextBuilder::checkObjectPermission(), via * BlueprintIntegration::run()) must check THIS user's * capability instead of the absent current one. * @param bool $reviewGuaranteed This job's job-uniform * JobEntitlementGuard::reviewGuaranteed(), set as * BlueprintIntegration's ambient trusted fact for the * same call window, so EntitlementPolicy::apply() can * clamp Description's "What customers say" section * when an Automation run will publish without review. * @return array Results in each service's own existing shape. * @throws \Exception Unknown service type. * @throws ProviderCallException When a returned row's providerError says the failure is run-wide. */ private function generateForAutomationProduct($service, int $product_id, array $options, int $created_by = 0, bool $reviewGuaranteed = false): array { BlueprintIntegration::setJobTrustedFacts([ 'jobMode' => isset($options['jobMode']) ? (string) $options['jobMode'] : '', 'legacyPrompts' => !empty($options['legacyPrompts']), ]); BlueprintIntegration::setJobActorUserId($created_by); BlueprintIntegration::setJobReviewGuaranteed($reviewGuaranteed); try { if ($service instanceof TitleGeneratorService || $service instanceof FAQGeneratorService || $service instanceof SeoMetaGeneratorService || $service instanceof ImageAltService) { $results = $service->bulk_generate([$product_id], $options); } elseif ($service instanceof ContentGenerator) { $contentTypes = $this->extractContentTypes($options); $productResult = $service->generateForProduct($product_id, $contentTypes, $options); $results = $this->transformContentGeneratorResult($productResult, $product_id); } else { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message, not user-facing output throw new \Exception('Unknown service type: ' . get_class($service)); } $this->throwForRunWideProviderFailure($results, (string) ($options['provider'] ?? '')); return $results; } finally { BlueprintIntegration::setJobTrustedFacts([]); BlueprintIntegration::setJobActorUserId(null); BlueprintIntegration::setJobReviewGuaranteed(null); } } /** * Rebuild and throw a ProviderCallException when a returned row's * providerError says the failure is run-wide (a revoked/missing key, no * model access, an exhausted quota, a rate limit, an outage, a network * failure, AI turned off, or an unsupported provider): every further call * to this provider in this run would fail the same way. This is the real * production path's only source of that exception today - every * generator catches its own ProviderCallException and returns a failed * row instead of throwing - so without this, the tick loop's * catch(\Throwable) run-wide classification (pause-and-requeue for a * permanent reason, a capped retry for a transient one, the * PROVIDER_QUOTA_LIMIT hook) never ran. * * A row whose providerError is absent, null, or not run-wide (content * blocked, truncated output, an unavailable image, a rejected schema, * ...) is left alone: it keeps today's per-item failure path through * processResults(), unaffected by this check. So is a row that carries * a run-wide providerError but no error of its own: a partial content * structure result that still has usable content. * * @param array $results Rows generateForAutomationProduct() is about to return, for the single product this call was for. * @param string $fallback_provider Provider id to use when a row's providerError carries none. * @return void * @throws ProviderCallException When a row's providerError is run-wide. */ private function throwForRunWideProviderFailure(array $results, string $fallback_provider): void { foreach ($results as $row) { if (!is_array($row)) { continue; } $providerError = $row['providerError'] ?? null; if (!is_array($providerError) || empty($providerError['runWide'])) { continue; } $failed = '' !== trim((string) ($row['api_error'] ?? '')) || '' !== trim((string) ($row['error'] ?? '')) || 'error' === ($row['status'] ?? ''); if (!$failed) { continue; } $reason = isset($providerError['reason']) ? (string) $providerError['reason'] : ''; if ('' === $reason) { continue; } $provider = (isset($providerError['provider']) && '' !== (string) $providerError['provider']) ? (string) $providerError['provider'] : $fallback_provider; // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message, not user-facing output; the merchant sentence is rebuilt from $reason by the catch block, not read from here. throw new ProviderCallException( isset($providerError['message']) ? (string) $providerError['message'] : '', $reason, isset($providerError['httpStatus']) ? (int) $providerError['httpStatus'] : null, '', isset($providerError['retryAfter']) ? (int) $providerError['retryAfter'] : null, $provider ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } } /** * The review stager that may answer the pre-call "already settled" check * for this tick, or null when the job is not review-routed or the site has * no review queue. A failure to find it must not fail the job: the check * is an optimization, so the tick generates as before and says so once. * * @param int $job_id Job ID. * @param bool $reviewGuaranteed Whether this job's results are guaranteed to reach To review. * @return ReviewQueueStager|null */ private function resolveSkipStager(int $job_id, bool $reviewGuaranteed): ?ReviewQueueStager { if (!$reviewGuaranteed) { return null; } try { return ReviewQueueStaging::availableStager(); } catch (\Throwable $e) { $this->logger->warning($job_id, 'The check for products already waiting in To review is unavailable; generating as usual', [ 'error' => $e->getMessage(), ]); return null; } } /** * Ask the review stager whether every field this job would generate for a * product is already settled. Anything but a clear answer, a thrown error * included, is "generate": the question may only save a provider call, * never stop a product. * * @param ReviewQueueStager|null $stager The stager, or null when the job is not checked. * @param int $job_id Job ID. * @param int $product_id Product ID. * @param string $tool_type The job's tool type. * @param array $options The job's translated options. * @param string[] $content_types Description fields the job generates, capped to the plan. * @param string $overwrite 'replace' | 'empty_only'. * @param bool $failure_logged Whether this tick already logged a failed check; set when it logs one. * @return array{outcome:string,in_progress:bool,refusals:array} */ private function settledAnswer(?ReviewQueueStager $stager, int $job_id, int $product_id, string $tool_type, array $options, array $content_types, string $overwrite, bool &$failure_logged): array { $generate = [ 'outcome' => ReviewQueueStager::SETTLED_PROCEED, 'in_progress' => false, 'refusals' => [], ]; if (null === $stager) { return $generate; } try { $answer = $stager->settledAutomationTargets($product_id, $tool_type, $options, $content_types, $overwrite); } catch (\Throwable $e) { if (!$failure_logged) { $failure_logged = true; $this->logger->warning($job_id, 'Could not check whether a product already waits in To review; generating it as usual. Only the first product with this problem in each batch is logged.', [ 'product_id' => $product_id, 'error' => $e->getMessage(), ]); } return $generate; } $outcome = isset($answer['outcome']) ? (string) $answer['outcome'] : ''; if (!in_array($outcome, [ReviewQueueStager::SETTLED_WAITING, ReviewQueueStager::SETTLED_KEPT, ReviewQueueStager::SETTLED_NO_TARGET], true)) { return $generate; } $refusals = []; foreach ((array) ($answer['refusals'] ?? []) as $refusal) { if (is_array($refusal) && isset($refusal['field'], $refusal['reason'])) { $refusals[] = ['field' => (string) $refusal['field'], 'reason' => (string) $refusal['reason']]; } } if (ReviewQueueStager::SETTLED_NO_TARGET === $outcome && [] === $refusals) { return $generate; } return [ 'outcome' => $outcome, 'in_progress' => !empty($answer['in_progress']), 'refusals' => $refusals, ]; } /** * One log line per kind of product this tick skipped before the provider * call, so the job's log answers "why did this run make so few calls?". * * @param int $job_id Job ID. * @param int $waiting Products skipped because their proposals wait in To review. * @param int $kept Products skipped because "only fill empty" keeps every field. * @return void */ private function logSkippedProducts(int $job_id, int $waiting, int $kept): void { if ($waiting > 0) { $this->logger->info($job_id, sprintf( /* translators: %d: number of products. */ _n('%d product skipped: its proposals wait in To review', '%d products skipped: their proposals wait in To review', $waiting, 'ai-product-tools'), $waiting ), ['skipped_waiting_in_review' => $waiting]); } if ($kept > 0) { $this->logger->info($job_id, sprintf( /* translators: %d: number of products. */ _n('%d product skipped: every field this job fills already has content', '%d products skipped: every field this job fills already has content', $kept, 'ai-product-tools'), $kept ), ['skipped_kept' => $kept]); } } /** * Extract content types from options for ContentGenerator * * Converts boolean flags (generateDescription, generateShortDescription, generateTags) * to an array of content type strings that ContentGenerator expects. * * @param array $options Job options containing boolean content type flags * @return array Array of content type strings (e.g., ['description', 'short_description', 'tags']) */ private function extractContentTypes(array $options): array { $types = []; if (!empty($options['generateDescription'])) { $types[] = 'description'; } if (!empty($options['generateShortDescription'])) { $types[] = 'short_description'; } if (!empty($options['generateTags'])) { $types[] = 'tags'; } if (empty($types)) { $types[] = 'description'; } $max = (int) apply_filters('aipt_max_job_content_types', 1); if ($max > 0) { $types = array_slice($types, 0, $max); } return $types; } /** * Transform ContentGenerator ProductResult to expected array format * * ContentGenerator returns ProductResult objects with a different structure. * This method transforms them to the array format expected by the automation pipeline. * * Every row also carries the ProductResult's own blueprintInfo (executionPath/ * blueprint/findings/eligibility/providerError), exactly like Title/SeoMeta/FAQ/ * ImageAlt's own raw items already do (`array_merge($item, $blueprint_fields)`). * Without this, ResultProcessor::transformToUnifiedFormat() never sees an * executionPath for a Description result, so JobExecutor::blueprintHeldBackRouting()/ * isBlockedByTheEngine() silently treat every Description automation item as a * legacy/advanced one - a Blueprint result the engine held back for review * (hard_limit_exceeded, say) could reach a live apply with no held-back check at * all. For the Advanced (custom-prompts) path $result->blueprintInfo is the * ProductResult class default (an empty array), so this merge is a no-op there. * * @param ProductResult $result The ProductResult from ContentGenerator * @param int $productId The product ID * @return array Array of result items compatible with automation pipeline */ private function transformContentGeneratorResult($result, int $productId): array { $output = []; if (is_object($result)) { $content = $result->content ?? []; $success = $result->success ?? false; $blueprintInfo = is_array($result->blueprintInfo ?? null) ? $result->blueprintInfo : []; $providerError = $blueprintInfo['providerError'] ?? ($result->providerError ?? null); if (!$success && !empty($result->errors)) { return [ array_merge( [ 'product_id' => $productId, 'error' => implode(', ', $result->errors), ], $blueprintInfo, ['providerError' => $providerError] ), ]; } foreach ($content as $type => $text) { if (empty($text)) { continue; } $typeMap = [ 'short_description' => 'short', 'description' => 'full', 'tags' => 'tags', ]; $dbType = $typeMap[$type] ?? $type; $output[] = array_merge( [ 'product_id' => $productId, 'type' => $dbType, 'text' => $text, ], $blueprintInfo, ['providerError' => $providerError] ); } if (empty($output) && !$success) { $errorMsg = !empty($result->errors) ? implode(', ', $result->errors) : 'AI provider returned no content'; $output[] = array_merge( [ 'product_id' => $productId, 'error' => $errorMsg, ], $blueprintInfo, ['providerError' => $providerError] ); } } elseif (is_array($result)) { foreach ($result as $item) { if (is_array($item)) { $item['product_id'] = $item['product_id'] ?? $productId; $output[] = $item; } } } return $output; } /** * Whether a tick that leaves products for later may start the next cron run * at once: it finished products and stopped on its time budget, at the end * of its loop or at its memory limit. * * @param string $exitReason Why the tick stopped. * @param int $finished Products the tick completed or failed. * @return bool */ private static function mayStartNextRunAtOnce(string $exitReason, int $finished): bool { return $finished > 0 && in_array($exitReason, ['work_done', 'time_budget_exhausted', 'memory_soft_limit'], true); } }