From d50d791626fb694b3daaa2018482209e07077c51 Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Tue, 1 Dec 2026 00:00:00 -0500 Subject: [PATCH] refactor(jobs)!: delete job-status normalization and legacy AI-concurrency reconciler --- .../docs/admin-interface/jobs-management.md | 11 - .../docs/core-system/database-schema.md | 3 +- .../docs/development/1-0-baseline.md | 2 +- .../Abilities/Job/RecoverStuckJobsAbility.php | 11 +- .../inc/Cli/Commands/JobsCommand.php | 255 +----------------- .../Cli/Commands/ProcessedItemsCommand.php | 31 +-- .../Core/Database/Jobs/JobStatusMigration.php | 224 --------------- .../inc/Core/Database/Jobs/Jobs.php | 93 ++----- .../Jobs/LegacyAIConcurrencyReconciler.php | 130 --------- .../JobsStatusNormalizationMigration.php | 49 ---- .../Database/Migrations/MigrationRunner.php | 1 - plugins/data-machine/inc/Core/JobStatus.php | 16 +- .../inc/Engine/AI/conversation-loop.php | 4 +- .../ProcessedItemsSourceRejectedTest.php | 9 +- .../Database/JobLifecycleTransitionTest.php | 101 +------ .../Core/Database/JobStatusStorageTest.php | 25 -- .../tests/ai-step-backpressure-smoke.php | 3 +- .../tests/job-status-accounting-smoke.php | 3 - .../tests/job-status-normalization-smoke.php | 178 ------------ .../jobs-cleanup-status-variants-smoke.php | 41 ++- .../jobs-command-reconciliation-smoke.php | 55 ++-- .../tests/jobs-trim-runtime-queues-smoke.php | 43 --- ...cessed-items-source-rejected-cli-smoke.php | 13 +- .../runtime-tool-contract-store-smoke.php | 1 - .../tests/worker-status-job-counts-smoke.php | 11 +- 25 files changed, 118 insertions(+), 1195 deletions(-) delete mode 100644 plugins/data-machine/inc/Core/Database/Jobs/JobStatusMigration.php delete mode 100644 plugins/data-machine/inc/Core/Database/Jobs/LegacyAIConcurrencyReconciler.php delete mode 100644 plugins/data-machine/inc/Core/Database/Migrations/JobsStatusNormalizationMigration.php delete mode 100644 plugins/data-machine/tests/job-status-normalization-smoke.php delete mode 100644 plugins/data-machine/tests/jobs-trim-runtime-queues-smoke.php diff --git a/plugins/data-machine/docs/admin-interface/jobs-management.md b/plugins/data-machine/docs/admin-interface/jobs-management.md index 5232a57631..546bf02633 100644 --- a/plugins/data-machine/docs/admin-interface/jobs-management.md +++ b/plugins/data-machine/docs/admin-interface/jobs-management.md @@ -51,17 +51,6 @@ The Jobs interface is a React-based admin dashboard that lists recent job execut The indexed `datamachine_jobs.status` column stores only Data Machine's bounded base-state vocabulary. Human-readable detail is stored as nullable `status_reason` (and mirrored into `engine_data.job_status_reason` until that blob is shed) and composed into `status_display` by job abilities, so list/detail output stays scannable without increasing status-index cardinality. -### Legacy Status Migration - -Existing compound rows are normalized only through the operator command; plugin bootstrap never scans or rewrites the jobs table. - -1. Inspect without mutation: `wp datamachine jobs normalize-status --format=json`. -2. Apply one bounded batch: `wp datamachine jobs normalize-status --apply --limit=250`. -3. Repeat apply until `status` is `complete` and `remaining` is `0`. -4. Verify queue summaries and `SELECT status, COUNT(*) ... GROUP BY status` before considering the migration complete operationally. - -Progress is durable and per-site, so interrupted runs resume from the last candidate job ID. Candidate batches use the existing `status` index to skip canonical rows, then lock each selected row and write its reason metadata and base status in one transaction. Unknown noncanonical states are counted but not rewritten; inspect and resolve their owning code before continuing. Final verification covers the whole table. If it finds a late legacy insert at or behind the cursor, the cursor resets to zero so the next invocation can select that residue; late inserts ahead of the cursor are selected normally. Existing v1 migration state remains compatible. During rollout, Data Machine readers match exact base states plus bounded legacy delimiters. Once completion is recorded, readers use exact status predicates and direct grouping. Rollback is code rollback only: the normalized base states remain valid to older code, while reason detail remains available in `engine_data`. - **State Synchronization**: Leveraging TanStack Query for: - Automatic background refetching of job statuses. - Real-time progression tracking through pipeline steps. diff --git a/plugins/data-machine/docs/core-system/database-schema.md b/plugins/data-machine/docs/core-system/database-schema.md index 5d845a14fc..ed92a4a4fa 100644 --- a/plugins/data-machine/docs/core-system/database-schema.md +++ b/plugins/data-machine/docs/core-system/database-schema.md @@ -119,7 +119,8 @@ CREATE TABLE wp_datamachine_jobs ( - `source` - Execution source: `'pipeline'` (standard), `'system'` (system tasks), or `'direct'` (ephemeral) - `label` - Human-readable label for the job (used by system tasks) - `parent_job_id` - Reference to parent job for batch execution (child jobs link back to parent) -- `status` - Current execution status (varchar(255) supports compound statuses like `agent_skipped - reason`) +- `status` - Canonical base execution status (`pending`, `processing`, `waiting`, `completed`, `completed_no_items`, `agent_skipped`, `failed`, `cancelled`) +- `status_reason` - Nullable human-readable detail for the status - `engine_data` - Engine parameters (source_url, image_url, effects for undo) stored by handlers for downstream use - `created_at` - Job creation timestamp - `completed_at` - Completion timestamp diff --git a/plugins/data-machine/docs/development/1-0-baseline.md b/plugins/data-machine/docs/development/1-0-baseline.md index 30b38869e1..180bbd4310 100644 --- a/plugins/data-machine/docs/development/1-0-baseline.md +++ b/plugins/data-machine/docs/development/1-0-baseline.md @@ -24,7 +24,7 @@ Compatibility is retained only for a named current external or persisted contrac The following grep-visible paths are intentionally retained and are not pre-1.0 API compatibility promises: - **Current schema/bootstrap:** repository `create_table()` methods create missing tables via `dbDelta`. They must not `ALTER` existing tables, `SELECT`/`UPDATE` existing rows, or run chat-network convergence on web `init`. Operator repairs live in `MigrationRunner` (`wp datamachine migrate`) and named CLI commands. -- **Concrete persisted production data:** compound job statuses, generation-less recurring actions, descriptor-less in-flight claims, pending-action numeric owner columns, installed bundle artifact config mirrors (including the concrete singular `handler_config` runtime overlay consumed by `AgentBundleRuntimeDrift` and `AgentBundleArtifactPayloads`), plaintext OAuth secrets awaiting opportunistic encryption, and existing memory directories remain readable so current queued work and operator data survive the production upgrade. +- **Concrete persisted production data:** generation-less recurring actions, descriptor-less in-flight claims, pending-action numeric owner columns, installed bundle artifact config mirrors (including the concrete singular `handler_config` runtime overlay consumed by `AgentBundleRuntimeDrift` and `AgentBundleArtifactPayloads`), plaintext OAuth secrets awaiting opportunistic encryption, and existing memory directories remain readable so current queued work and operator data survive the production upgrade. - **Shipped external edges:** stable `datamachine/v1` REST error codes, the `datamachine_tools` and pending-action handler extension filters, OAuth implicit-flow support, and both possible PSR-16 namespaces are presentation, extension, or dependency boundaries rather than alternate internal models. - **Current pipeline delegation edge:** `ToolPolicyResolver` accepts top-level `runtime_tool_declarations` because the current pipeline policy consumer supplies run-scoped client declarations there. The namespaced client-context envelope remains supported for interactive runtime adapters. - **External/dependency edges:** Action Scheduler owns its schema compatibility hooks; WordPress owns the Abilities REST runner; Agents API owns the canonical pending-action ability and approval vocabulary. Data Machine keeps only the required adapters and verified dependency seams. diff --git a/plugins/data-machine/inc/Abilities/Job/RecoverStuckJobsAbility.php b/plugins/data-machine/inc/Abilities/Job/RecoverStuckJobsAbility.php index 52ace291c2..66b0d74689 100644 --- a/plugins/data-machine/inc/Abilities/Job/RecoverStuckJobsAbility.php +++ b/plugins/data-machine/inc/Abilities/Job/RecoverStuckJobsAbility.php @@ -268,18 +268,15 @@ public function execute( array $input ): array|\WP_Error { 'next_retry_at' => (string) ( $throttle['next_retry_at'] ?? '' ), ); $retry_time = strtotime( $ownership['next_retry_at'] ); - $legacy_receipt = empty( $resume ) && 0 === $ownership['generation']; - $modern_receipt = 0 < $ownership['generation'] + $valid_receipt = 0 < $ownership['generation'] && 'scheduled' === (string) ( $resume['status'] ?? '' ) && (int) ( $resume['action_id'] ?? 0 ) === $ownership['action_id'] && (int) ( $resume['generation'] ?? 0 ) === $ownership['generation'] - && (string) ( $resume['flow_step_id'] ?? '' ) === $ownership['flow_step_id']; - $valid_receipt = $ownership['action_id'] > 0 + && (string) ( $resume['flow_step_id'] ?? '' ) === $ownership['flow_step_id'] + && $ownership['action_id'] > 0 && '' !== $ownership['flow_step_id'] && false !== $retry_time - && $retry_time < time() - && ( $modern_receipt || $legacy_receipt ); - $ownership['legacy'] = $legacy_receipt; + && $retry_time < time(); $action_evidence = $valid_receipt ? $this->getRecordedActionEvidence( $ownership['action_id'] ) : array( 'complete' => true, 'exists' => false, diff --git a/plugins/data-machine/inc/Cli/Commands/JobsCommand.php b/plugins/data-machine/inc/Cli/Commands/JobsCommand.php index 76c516af23..bf1778fda4 100644 --- a/plugins/data-machine/inc/Cli/Commands/JobsCommand.php +++ b/plugins/data-machine/inc/Cli/Commands/JobsCommand.php @@ -28,8 +28,6 @@ use DataMachine\Core\Jobs\SchedulerEvidence; use DataMachine\Engine\AI\TranscriptStore; use DataMachine\Core\Database\Jobs\Jobs; -use DataMachine\Core\Database\Jobs\LegacyAIConcurrencyReconciler; -use DataMachine\Core\Database\Jobs\JobStatusMigration; use AgentsAPI\AI\WP_Agent_Message; use DataMachine\Engine\AI\System\Tasks\SystemTask; use DataMachine\Engine\Tasks\TaskRegistry; @@ -38,57 +36,6 @@ class JobsCommand extends BaseCommand { - /** - * Inspect or apply one bounded batch of canonical job-status normalization. - * - * ## OPTIONS - * - * [--apply] - * : Normalize one bounded batch. Without this flag the command is read-only. - * - * [--limit=] - * : Maximum noncanonical candidate rows to inspect in this invocation (1-1000). - * --- - * default: 250 - * --- - * - * [--format=] - * : Output format: table or json. - * --- - * default: table - * --- - * - * ## EXAMPLES - * - * wp datamachine jobs normalize-status - * wp datamachine jobs normalize-status --apply --limit=250 - * - * @subcommand normalize-status - */ - public function normalize_status( array $args, array $assoc_args ): void { - $apply = isset( $assoc_args['apply'] ); - $limit = max( 1, min( 1000, (int) ( $assoc_args['limit'] ?? 250 ) ) ); - $format = $assoc_args['format'] ?? 'table'; - $migration = new JobStatusMigration(); - $result = $apply ? $migration->apply( $limit ) : $migration->inspect(); - - if ( 'json' === $format ) { - WP_CLI::line( (string) wp_json_encode( $result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); - } else { - foreach ( array( 'status', 'cursor', 'scanned', 'migrated', 'unknown', 'conflicts', 'errors', 'remaining' ) as $field ) { - WP_CLI::log( sprintf( '%-12s %s', ucfirst( $field ) . ':', (string) ( $result[ $field ] ?? 0 ) ) ); - } - } - - if ( $result['complete'] ) { - WP_CLI::success( 'Job status storage is normalized.' ); - } elseif ( $apply ) { - WP_CLI::log( 'Batch complete. Re-run with --apply until status is complete; inspect unknown rows before proceeding if remaining stops decreasing.' ); - } else { - WP_CLI::log( 'Dry run only. Re-run with --apply to process one bounded batch.' ); - } - } - /** * Default fields for job list output. * @@ -706,134 +653,6 @@ public function reaper_status( array $args, array $assoc_args ): void { $this->format_items( $report['runs'], $this->reaper_status_fields, $assoc_args, 'ran_at' ); } - /** - * Trim runtime queue payloads from persisted job engine_data. - * - * Historical batch child jobs may carry copied flow runtime queues in - * engine_data. Those queues are read from the live flow record at execution - * time, so keeping them on each child only inflates Action Scheduler memory. - * - * ## OPTIONS - * - * [--yes] - * : Apply changes. Without this flag the command is a dry run. - * - * [--limit=] - * : Maximum rows to inspect. - * --- - * default: 500 - * --- - * - * [--format=] - * : Output format. - * --- - * default: table - * options: - * - table - * - json - * - yaml - * --- - * - * @subcommand trim-runtime-queues - */ - public function trim_runtime_queues( array $args, array $assoc_args ): void { - global $wpdb; - - $apply = isset( $assoc_args['yes'] ); - $limit = isset( $assoc_args['limit'] ) ? max( 1, min( 5000, (int) $assoc_args['limit'] ) ) : 500; - $format = $assoc_args['format'] ?? 'table'; - - $jobs_table = $wpdb->prefix . 'datamachine_jobs'; - $jobs_db = new Jobs(); - - $rows = $wpdb->get_results( - $wpdb->prepare( - "SELECT job_id, flow_id, pipeline_id, parent_job_id, status, engine_data - FROM %i - WHERE status IN ('pending', 'processing') - AND (engine_data LIKE %s OR engine_data LIKE %s OR engine_data LIKE %s) - ORDER BY job_id ASC - LIMIT %d", - $jobs_table, - '%' . $wpdb->esc_like( '"config_patch_queue"' ) . '%', - '%' . $wpdb->esc_like( '"prompt_queue"' ) . '%', - '%' . $wpdb->esc_like( '"_queue_consume_revision"' ) . '%', - $limit - ), - ARRAY_A - ); - - $items = array(); - $summary = array( - 'inspected' => count( $rows ), - 'trimmed' => 0, - 'updated' => 0, - 'failed' => 0, - ); - - foreach ( $rows as $row ) { - $job_id = (int) ( $row['job_id'] ?? 0 ); - $before = $this->decode_job_engine_data( $row['engine_data'] ?? null ); - $after = $this->strip_runtime_queues_from_engine_data( $before ); - - $before_json = wp_json_encode( $before ); - $after_json = wp_json_encode( $after ); - $before_bytes = strlen( false === $before_json ? '' : $before_json ); - $after_bytes = strlen( false === $after_json ? '' : $after_json ); - $changed = $after !== $before; - - $item = array( - 'job_id' => $job_id, - 'flow_id' => $row['flow_id'] ?? '', - 'pipeline_id' => $row['pipeline_id'] ?? '', - 'parent_job_id' => (int) ( $row['parent_job_id'] ?? 0 ), - 'status' => $row['status'] ?? '', - 'before_bytes' => $before_bytes, - 'after_bytes' => $after_bytes, - 'saved_bytes' => max( 0, $before_bytes - $after_bytes ), - 'action' => $changed ? ( $apply ? 'updated' : 'would_update' ) : 'unchanged', - ); - - if ( $changed ) { - ++$summary['trimmed']; - if ( $apply ) { - if ( $jobs_db->store_engine_data( $job_id, $after ) ) { - ++$summary['updated']; - } else { - ++$summary['failed']; - $item['action'] = 'failed'; - } - } - } - - $items[] = $item; - } - - if ( 'json' === $format || 'yaml' === $format ) { - WP_CLI::print_value( - array( - 'success' => 0 === $summary['failed'], - 'dry_run' => ! $apply, - 'summary' => $summary, - 'jobs' => $items, - ), - array( 'format' => $format ) - ); - return; - } - - if ( empty( $items ) ) { - WP_CLI::success( 'No pending or processing jobs with runtime queue payloads found.' ); - return; - } - - $this->format_items( $items, array( 'job_id', 'flow_id', 'status', 'before_bytes', 'after_bytes', 'saved_bytes', 'action' ), $assoc_args, 'job_id' ); - WP_CLI::log( sprintf( 'Inspected %d jobs; %d need trimming; %d updated; %d failed.', $summary['inspected'], $summary['trimmed'], $summary['updated'], $summary['failed'] ) ); - if ( ! $apply ) { - WP_CLI::log( 'Dry run - pass --yes to apply changes.' ); - } - } - /** * Reconcile jobs whose persisted status disagrees with successful engine artifacts. * @@ -871,24 +690,23 @@ public function reconcile_status( array $args, array $assoc_args ): void { $limit = isset( $assoc_args['limit'] ) ? max( 1, min( 5000, (int) $assoc_args['limit'] ) ) : 500; $format = $assoc_args['format'] ?? 'table'; - $jobs_table = $wpdb->prefix . 'datamachine_jobs'; - $jobs_db = new Jobs(); - $failed_like = $wpdb->esc_like( 'failed' ) . '%'; - $agent_skipped_like = $wpdb->esc_like( 'agent_skipped' ) . '%'; - $historical_contention_status = LegacyAIConcurrencyReconciler::SOURCE_STATUS; + $jobs_table = $wpdb->prefix . 'datamachine_jobs'; + $jobs_db = new Jobs(); + $failed_like = $wpdb->esc_like( 'failed' ) . '%'; + $agent_skipped_like = $wpdb->esc_like( 'agent_skipped' ) . '%'; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT job_id, flow_id, parent_job_id, status, label, engine_data FROM %i - WHERE ((status LIKE %s OR status = 'processing') + WHERE (status LIKE %s OR status = 'processing') AND ( engine_data LIKE %s OR engine_data LIKE %s OR JSON_UNQUOTE(JSON_EXTRACT(engine_data, '$.job_status')) LIKE %s OR JSON_UNQUOTE(JSON_EXTRACT(engine_data, '$.runtime_provenance.status.status')) = 'completed' OR JSON_UNQUOTE(JSON_EXTRACT(engine_data, '$.runtime_provenance.status.completed')) = 'true' - )) OR status = %s + ) ORDER BY COALESCE(completed_at, created_at) DESC LIMIT %d", $jobs_table, @@ -896,7 +714,6 @@ public function reconcile_status( array $args, array $assoc_args ): void { '%Updated wiki article:%', '%Source rejected:%', $agent_skipped_like, - $historical_contention_status, $limit ), ARRAY_A @@ -906,8 +723,7 @@ public function reconcile_status( array $args, array $assoc_args ): void { $updated = 0; foreach ( $rows as $row ) { - $plan = $this->resolve_reconciled_job_plan( $row ); - $target_status = $plan['target_status']; + $target_status = $this->resolve_reconciled_job_status( $row ); if ( '' === $target_status ) { continue; } @@ -917,18 +733,11 @@ public function reconcile_status( array $args, array $assoc_args ): void { 'flow_id' => (int) $row['flow_id'], 'from_status' => (string) $row['status'], 'target_status' => $target_status, - 'reason' => str_contains( $target_status, 'ai_concurrency_stranded' ) ? 'historical_concurrency_contention' : ( str_starts_with( $target_status, 'agent_skipped' ) ? 'source_rejected' : 'successful_handler_artifact' ), + 'reason' => str_starts_with( $target_status, 'agent_skipped' ) ? 'source_rejected' : 'successful_handler_artifact', 'label' => (string) ( $row['label'] ?? '' ), ); - $reconciled = false; - if ( ! $dry_run && 'legacy_ai_concurrency' === $plan['strategy'] ) { - $transition = ( new LegacyAIConcurrencyReconciler() )->reconcile( (int) $row['job_id'] ); - $reconciled = ! empty( $transition['success'] ); - $item['reconciliation'] = $transition['reconciliation'] ?? array(); - } elseif ( ! $dry_run ) { - $reconciled = $jobs_db->complete_job( (int) $row['job_id'], $target_status ); - } + $reconciled = ! $dry_run && $jobs_db->complete_job( (int) $row['job_id'], $target_status ); if ( $reconciled ) { ++$updated; @@ -1100,10 +909,6 @@ public function reconcile_terminal_accounting( array $args, array $assoc_args ): * @return string Corrected status, or empty string when the row is not safe to repair. */ private function resolve_reconciled_job_status( array $row ): string { - if ( LegacyAIConcurrencyReconciler::SOURCE_STATUS === (string) ( $row['status'] ?? '' ) ) { - return LegacyAIConcurrencyReconciler::TARGET_STATUS; - } - $engine_data = $this->decode_job_engine_data( $row['engine_data'] ?? null ); $job_status = isset( $engine_data['job_status'] ) ? (string) $engine_data['job_status'] : ''; @@ -1126,20 +931,6 @@ private function resolve_reconciled_job_status( array $row ): string { return ''; } - /** - * Resolve both the target and the only authorized transition mechanism. - * - * @return array{target_status:string,strategy:string} - */ - private function resolve_reconciled_job_plan( array $row ): array { - $is_legacy_contention = LegacyAIConcurrencyReconciler::SOURCE_STATUS === (string) ( $row['status'] ?? '' ); - - return array( - 'target_status' => $this->resolve_reconciled_job_status( $row ), - 'strategy' => $is_legacy_contention ? 'legacy_ai_concurrency' : 'terminal_transition', - ); - } - /** * Determine whether runtime provenance marks the engine attempt complete. * @@ -1277,34 +1068,6 @@ private function decode_job_engine_data( $engine_data ): array { return is_array( $decoded ) ? $decoded : array(); } - /** - * Strip runtime queue fields from engine_data flow config. - * - * @param array $engine_data Decoded engine data. - * @return array Engine data without copied runtime queue payloads. - */ - private function strip_runtime_queues_from_engine_data( array $engine_data ): array { - $flow_config = is_array( $engine_data['flow_config'] ?? null ) ? $engine_data['flow_config'] : array(); - - foreach ( $flow_config as $flow_step_id => $flow_step_config ) { - if ( ! is_array( $flow_step_config ) ) { - continue; - } - - unset( - $flow_step_config['prompt_queue'], - $flow_step_config['config_patch_queue'], - $flow_step_config['_queue_consume_revision'] - ); - - $flow_config[ $flow_step_id ] = $flow_step_config; - } - - $engine_data['flow_config'] = $flow_config; - - return $engine_data; - } - /** * Count child terminal statuses for a parent job. * diff --git a/plugins/data-machine/inc/Cli/Commands/ProcessedItemsCommand.php b/plugins/data-machine/inc/Cli/Commands/ProcessedItemsCommand.php index def4b04cef..d25f442ea4 100644 --- a/plugins/data-machine/inc/Cli/Commands/ProcessedItemsCommand.php +++ b/plugins/data-machine/inc/Cli/Commands/ProcessedItemsCommand.php @@ -26,11 +26,6 @@ */ class ProcessedItemsCommand extends BaseCommand { - /** - * Legacy job status written before AI rejections finished as completed_no_items. - */ - private const LEGACY_SOURCE_REJECTED_JOB_STATUS = 'agent_skipped - source-rejected'; - /** * Step result value FetchItemDispositionTool records for reject_source. */ @@ -556,8 +551,7 @@ public function cleanup_orphans( array $args, array $assoc_args ): void { /** * List processed items whose owning job rejected its source. * - * Matches persisted rejection evidence by default: legacy - * `agent_skipped - source-rejected` jobs and current reject_source jobs + * Matches persisted rejection evidence by default: reject_source jobs * (typically `completed_no_items`) that recorded a source_rejection_reason. * * ## OPTIONS @@ -579,9 +573,8 @@ public function cleanup_orphans( array $args, array $assoc_args ): void { * * [--job-status=] * : Match owning jobs by this exact status instead of persisted source-rejection - * evidence. By default, jobs match when they carry the legacy - * `agent_skipped - source-rejected` status or a `reject_source` step result - * with a non-empty `source_rejection_reason`, so empty `completed_no_items` + * evidence. By default, jobs match when they carry a `reject_source` step + * result with a non-empty `source_rejection_reason`, so empty `completed_no_items` * runs without rejection evidence are excluded. * * [--reason=] @@ -703,9 +696,8 @@ static function ( array $row ): array { * * [--job-status=] * : Match owning jobs by this exact status instead of persisted source-rejection - * evidence. By default, jobs match when they carry the legacy - * `agent_skipped - source-rejected` status or a `reject_source` step result - * with a non-empty `source_rejection_reason`, so empty `completed_no_items` + * evidence. By default, jobs match when they carry a `reject_source` step + * result with a non-empty `source_rejection_reason`, so empty `completed_no_items` * runs without rejection evidence are excluded. * * [--reason=] @@ -814,8 +806,7 @@ private function build_source_rejected_query_parts( array $assoc_args, string $p // Explicit operator override: match the owning job status only. $parsed_status = JobStatus::fromString( $job_status ); if ( $parsed_status->hasReason() ) { - $where_parts[] = '(j.status = %s OR (j.status = %s AND (j.status_reason = %s OR j.engine_data LIKE %s)))'; - $values[] = $job_status; + $where_parts[] = '(j.status = %s AND (j.status_reason = %s OR j.engine_data LIKE %s))'; $values[] = $parsed_status->getBaseStatus(); $values[] = $parsed_status->getReason(); $values[] = '%' . $wpdb->esc_like( '"job_status_reason":"' . $parsed_status->getReason() . '"' ) . '%'; @@ -825,15 +816,9 @@ private function build_source_rejected_query_parts( array $assoc_args, string $p } } else { // Default: match persisted source-rejection evidence, not a status string. - // Legacy runs finished as `agent_skipped - source-rejected`; current AI - // reject_source runs finish as completed_no_items with the rejection + // AI reject_source runs finish as completed_no_items with the rejection // recorded in engine_data step_results (see FetchItemDispositionTool). - $legacy = JobStatus::fromString( self::LEGACY_SOURCE_REJECTED_JOB_STATUS ); - $where_parts[] = '(j.status = %s OR (j.status = %s AND (j.status_reason = %s OR j.engine_data LIKE %s)) OR j.engine_data LIKE %s OR j.engine_data REGEXP %s)'; - $values[] = self::LEGACY_SOURCE_REJECTED_JOB_STATUS; - $values[] = $legacy->getBaseStatus(); - $values[] = $legacy->getReason(); - $values[] = '%' . $wpdb->esc_like( '"job_status_reason":"' . $legacy->getReason() . '"' ) . '%'; + $where_parts[] = '(j.engine_data LIKE %s OR j.engine_data REGEXP %s)'; $values[] = '%' . $wpdb->esc_like( '"result":"' . self::SOURCE_REJECTED_STEP_RESULT . '"' ) . '%'; $values[] = '"' . self::SOURCE_REJECTION_REASON_KEY . '":"[^"]'; } diff --git a/plugins/data-machine/inc/Core/Database/Jobs/JobStatusMigration.php b/plugins/data-machine/inc/Core/Database/Jobs/JobStatusMigration.php deleted file mode 100644 index 2d1c7f558b..0000000000 --- a/plugins/data-machine/inc/Core/Database/Jobs/JobStatusMigration.php +++ /dev/null @@ -1,224 +0,0 @@ -wpdb = $wpdb; - $this->table = $wpdb->prefix . Jobs::TABLE_NAME; - } - - /** Inspect durable progress without mutating job rows. */ - public function inspect(): array { - $state = $this->state(); - $remaining = $this->countNoncanonicalRows(); - - return array_merge( - $state, - array( - 'success' => true, - 'table' => $this->table, - 'remaining' => $remaining, - 'complete' => 0 === $remaining, - 'status' => 0 === $remaining ? 'complete' : ( (int) $state['cursor'] > 0 ? 'in_progress' : 'migration_required' ), - 'canonical_statuses' => JobStatus::ALL_STATUSES, - ) - ); - } - - /** Process one bounded, resumable batch. */ - public function apply( int $limit = 250 ): array { - $limit = max( 1, min( self::MAX_BATCH, $limit ) ); - $state = $this->state(); - $state['complete'] = false; - $rows = $this->candidateRows( (int) $state['cursor'], $limit ); - - foreach ( $rows as $row ) { - $job_id = (int) $row['job_id']; - $status = (string) $row['status']; - $state['cursor'] = max( (int) $state['cursor'], $job_id ); - $state['scanned'] = (int) $state['scanned'] + 1; - $parsed = JobStatus::fromString( $status ); - - if ( ! $parsed->isCanonical() ) { - $state['unknown'] = (int) $state['unknown'] + 1; - continue; - } - - $result = $this->normalizeRow( $job_id, $status ); - if ( 'migrated' === $result ) { - $state['migrated'] = (int) $state['migrated'] + 1; - } elseif ( 'conflict' === $result ) { - $state['conflicts'] = (int) $state['conflicts'] + 1; - } else { - $state['errors'] = (int) $state['errors'] + 1; - break; - } - } - - $state['updated_at'] = gmdate( 'c' ); - update_option( self::STATE_OPTION, $state, false ); - $result = array_merge( - $state, - array( - 'success' => true, - 'table' => $this->table, - 'batch_size' => count( $rows ), - 'canonical_statuses' => JobStatus::ALL_STATUSES, - ) - ); - if ( count( $rows ) < $limit ) { - $result = $this->inspect(); - } - if ( ! empty( $result['complete'] ) ) { - $state['complete'] = true; - update_option( self::STATE_OPTION, $state, false ); - $result = array_merge( $result, $state ); - } elseif ( count( $rows ) < $limit && (int) ( $result['remaining'] ?? 0 ) > 0 ) { - $state['cursor'] = 0; - update_option( self::STATE_OPTION, $state, false ); - $result['cursor'] = 0; - } - $result['batch_size'] = count( $rows ); - $result['status'] = ! empty( $result['complete'] ) ? 'complete' : 'in_progress'; - return $result; - } - - public static function isComplete(): bool { - $state = get_option( self::STATE_OPTION, array() ); - return is_array( $state ) && ! empty( $state['complete'] ); - } - - private function state(): array { - $stored = get_option( self::STATE_OPTION, array() ); - return array_merge( - array( - 'cursor' => 0, - 'scanned' => 0, - 'migrated' => 0, - 'unknown' => 0, - 'conflicts' => 0, - 'errors' => 0, - 'updated_at' => null, - ), - is_array( $stored ) ? $stored : array() - ); - } - - private function candidateRows( int $cursor, int $limit ): array { - $query = $this->wpdb->prepare( - 'SELECT job_id, status FROM %i WHERE job_id > %d AND status NOT IN (%s, %s, %s, %s, %s, %s, %s, %s) ORDER BY job_id ASC LIMIT %d', - $this->table, - $cursor, - JobStatus::PENDING, - JobStatus::PROCESSING, - JobStatus::WAITING, - JobStatus::COMPLETED, - JobStatus::FAILED, - JobStatus::CANCELLED, - JobStatus::COMPLETED_NO_ITEMS, - JobStatus::AGENT_SKIPPED, - $limit - ); - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- The query is prepared immediately above with typed identifier and scalar placeholders. - $rows = $this->wpdb->get_results( $query, ARRAY_A ); - return is_array( $rows ) ? $rows : array(); - } - - private function countNoncanonicalRows(): int { - $query = $this->wpdb->prepare( - 'SELECT COUNT(*) FROM %i WHERE status NOT IN (%s, %s, %s, %s, %s, %s, %s, %s)', - $this->table, - JobStatus::PENDING, - JobStatus::PROCESSING, - JobStatus::WAITING, - JobStatus::COMPLETED, - JobStatus::FAILED, - JobStatus::CANCELLED, - JobStatus::COMPLETED_NO_ITEMS, - JobStatus::AGENT_SKIPPED - ); - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- The query is prepared immediately above from fixed placeholders and canonical constants. - return (int) $this->wpdb->get_var( $query ); - } - - private function normalizeRow( int $job_id, string $expected_status ): string { - $scope = TransactionScope::begin( $this->wpdb ); - if ( null === $scope ) { - return 'error'; - } - - $query = $this->wpdb->prepare( 'SELECT status, engine_data FROM %i WHERE job_id = %d FOR UPDATE', $this->table, $job_id ); - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- The query is prepared immediately above with typed identifier and integer placeholders. - $row = $this->wpdb->get_row( $query, ARRAY_A ); - if ( ! is_array( $row ) || (string) $row['status'] !== $expected_status ) { - $scope->rollback(); - return 'conflict'; - } - - $parsed = JobStatus::fromString( $expected_status ); - if ( ! $parsed->isCanonical() ) { - $scope->rollback(); - return 'conflict'; - } - - $stored_engine = $row['engine_data'] ?? null; - $engine = null === $stored_engine || '' === $stored_engine ? array() : json_decode( (string) $stored_engine, true ); - if ( ! is_array( $engine ) ) { - $scope->rollback(); - return 'error'; - } - if ( $parsed->hasReason() ) { - $engine['job_status_reason'] = $parsed->getReason(); - } - $encoded = wp_json_encode( $engine ); - if ( ! is_string( $encoded ) ) { - $scope->rollback(); - return 'error'; - } - $storage = $parsed->toStorage(); - $updated = $this->wpdb->update( - $this->table, - array( - 'status' => $storage['status'], - 'status_reason' => $storage['status_reason'], - 'engine_data' => $encoded, - ), - array( - 'job_id' => $job_id, - 'status' => $expected_status, - ), - array( '%s', $parsed->hasReason() ? '%s' : null, '%s' ), - array( '%d', '%s' ) - ); - if ( 1 !== (int) $updated || ! $scope->commit() ) { - $scope->rollback(); - return false === $updated ? 'error' : 'conflict'; - } - wp_cache_delete( $job_id, 'datamachine_engine_data' ); - return 'migrated'; - } -} diff --git a/plugins/data-machine/inc/Core/Database/Jobs/Jobs.php b/plugins/data-machine/inc/Core/Database/Jobs/Jobs.php index 5bf3d9d02d..0f7b09586a 100644 --- a/plugins/data-machine/inc/Core/Database/Jobs/Jobs.php +++ b/plugins/data-machine/inc/Core/Database/Jobs/Jobs.php @@ -596,15 +596,14 @@ public function reopen_failed_job( int $job_id ): bool { return false; } - $failed_status = $this->wpdb->esc_like( 'failed' ) . '%'; - // phpcs:disable WordPress.DB.PreparedSQL -- The nested prepare binds the plugin table identifier, job ID, and escaped LIKE value. + // phpcs:disable WordPress.DB.PreparedSQL -- The nested prepare binds the plugin table identifier, job ID, and status. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $updated = $this->wpdb->query( $this->wpdb->prepare( - "UPDATE %i SET status = 'pending', status_reason = NULL, completed_at = NULL, terminal_accounting_state = NULL, terminal_accounting_owner = NULL, terminal_accounting_claimed_at = NULL, terminal_accounting_processed_count = 0, operation_state = 'preparing', operation_claimed_at = NULL, operation_claim_token = NULL, operation_action_id = NULL WHERE job_id = %d AND status LIKE %s", + "UPDATE %i SET status = 'pending', status_reason = NULL, completed_at = NULL, terminal_accounting_state = NULL, terminal_accounting_owner = NULL, terminal_accounting_claimed_at = NULL, terminal_accounting_processed_count = 0, operation_state = 'preparing', operation_claimed_at = NULL, operation_claim_token = NULL, operation_action_id = NULL WHERE job_id = %d AND status = %s", $this->table_name, $job_id, - $failed_status + JobStatus::FAILED ) ); // phpcs:enable WordPress.DB.PreparedSQL @@ -1106,20 +1105,8 @@ private function build_jobs_summary_where( array $args, string $alias = 'j' ): a */ private function get_status_summary_rows( string $where_sql, array $where_values ): array { // phpcs:disable WordPress.DB.PreparedSQL,WordPress.DB.PreparedSQLPlaceholders -- Dynamic clauses are fixed repository fragments; every value is passed to prepare(). - $status_expression = JobStatusMigration::isComplete() - ? 'j.status' - : "CASE - WHEN j.status LIKE 'agent_skipped - %' OR j.status LIKE 'agent_skipped:%' THEN 'agent_skipped' - WHEN j.status LIKE 'completed_no_items - %' OR j.status LIKE 'completed_no_items:%' THEN 'completed_no_items' - WHEN j.status LIKE 'completed - %' OR j.status LIKE 'completed:%' THEN 'completed' - WHEN j.status LIKE 'failed - %' OR j.status LIKE 'failed:%' THEN 'failed' - WHEN j.status LIKE 'cancelled - %' OR j.status LIKE 'cancelled:%' THEN 'cancelled' - WHEN j.status LIKE 'processing - %' OR j.status LIKE 'processing:%' THEN 'processing' - WHEN j.status LIKE 'waiting - %' OR j.status LIKE 'waiting:%' THEN 'waiting' - WHEN j.status LIKE 'pending - %' OR j.status LIKE 'pending:%' THEN 'pending' - ELSE j.status END"; - $rows = $this->wpdb->get_results( $this->wpdb->prepare( - "SELECT {$status_expression} AS status, + $rows = $this->wpdb->get_results( $this->wpdb->prepare( + "SELECT j.status AS status, COUNT(*) AS count FROM %i j {$where_sql} @@ -1766,63 +1753,39 @@ public function get_latest_jobs_by_flow_ids( array $flow_ids ): array { /** * Resolve a status prefix to known variants for indexed lookups. * - * Once status is a bounded vocabulary, exact IN matching is sufficient. - * Prefix matching remains only while JobStatusMigration is incomplete so - * leftover compound rows (`failed - …`, `failed:…`) still match. + * Status is a bounded vocabulary, so exact IN matching is sufficient. * - * @param string $status_prefix The status prefix (e.g. 'completed', 'failed'). - * @return array{type: 'in', values: string[]} | array{type: 'like', pattern: string} + * @param string $status_prefix The base status (e.g. 'completed', 'failed'). + * @return string[] Exact status values to match. */ private function resolve_status_match( string $status_prefix ): array { - $values = 'completed' === $status_prefix + return 'completed' === $status_prefix ? array( JobStatus::COMPLETED, JobStatus::COMPLETED_NO_ITEMS, JobStatus::AGENT_SKIPPED ) : array( JobStatus::fromString( $status_prefix )->getBaseStatus() ); - return array( - 'type' => JobStatusMigration::isComplete() ? 'in' : 'mixed', - 'values' => $values, - ); } - /** Build a cleanup predicate that covers only recognized legacy delimiters. */ - private function status_match_sql( array $status_match, array &$values ): string { - $placeholders = implode( ',', array_fill( 0, count( $status_match['values'] ), '%s' ) ); - $values = array_merge( $values, $status_match['values'] ); - $sql = "status IN ({$placeholders})"; - if ( 'mixed' !== $status_match['type'] ) { - return $sql; - } - foreach ( $status_match['values'] as $base ) { - $sql .= ' OR status LIKE %s OR status LIKE %s'; - $values[] = $this->wpdb->esc_like( $base . ' - ' ) . '%'; - $values[] = $this->wpdb->esc_like( $base . ':' ) . '%'; - } - return '(' . $sql . ')'; + /** Build an exact status IN predicate. */ + private function status_match_sql( array $status_values, array &$values ): string { + $placeholders = implode( ',', array_fill( 0, count( $status_values ), '%s' ) ); + $values = array_merge( $values, $status_values ); + return "status IN ({$placeholders})"; } - /** Add an exact canonical filter with a bounded legacy transition fallback. */ + /** Add an exact canonical status filter. */ private function append_status_filter( array &$clauses, array &$values, string $column, string $status ): void { - $base = JobStatus::fromString( sanitize_text_field( $status ) )->getBaseStatus(); - if ( JobStatusMigration::isComplete() ) { - $clauses[] = $column . ' = %s'; - $values[] = $base; - return; - } - $clauses[] = '(' . $column . ' = %s OR ' . $column . ' LIKE %s OR ' . $column . ' LIKE %s)'; - $values[] = $base; - $values[] = $this->wpdb->esc_like( $base . ' - ' ) . '%'; - $values[] = $this->wpdb->esc_like( $base . ':' ) . '%'; + $clauses[] = $column . ' = %s'; + $values[] = JobStatus::fromString( sanitize_text_field( $status ) )->getBaseStatus(); } /** * Delete old jobs by status and age. * * Removes jobs matching the given status pattern that are older than - * the specified number of days. Uses LIKE matching to handle compound - * statuses (e.g., "failed - timeout"). + * the specified number of days. * * @since 0.28.0 * - * @param string $status_pattern Base status to match (e.g., 'failed'). Uses LIKE prefix matching. + * @param string $status_pattern Base status to match (e.g., 'failed'). * @param int $older_than_days Delete jobs older than this many days. * @return int|false Number of deleted rows, or false on error. */ @@ -1897,9 +1860,8 @@ public function delete_jobs( array $criteria = array() ): int|false { } if ( ! empty( $criteria['failed'] ) ) { - $failed_pattern = $this->wpdb->esc_like( 'failed' ) . '%'; // phpcs:disable WordPress.DB.PreparedSQL -- Table name is the repository table; value is prepared. - $result = $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM %i WHERE status LIKE %s', $this->table_name, $failed_pattern ) ); + $result = $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM %i WHERE status = %s', $this->table_name, JobStatus::FAILED ) ); // phpcs:enable WordPress.DB.PreparedSQL } else { // phpcs:disable WordPress.DB.PreparedSQL -- Table name is the repository table. @@ -2728,10 +2690,9 @@ public function transition_missing_direct_operation( int $job_id, string $status public function transition_expired_ai_deferral( int $job_id, string $status, array $ownership, string $trigger ): array { $action_id = (int) ( $ownership['action_id'] ?? 0 ); $generation = (int) ( $ownership['generation'] ?? 0 ); - $legacy = ! empty( $ownership['legacy'] ); $flow_step = (string) ( $ownership['flow_step_id'] ?? '' ); $retry_at = (string) ( $ownership['next_retry_at'] ?? '' ); - if ( ! JobStatus::isStatusFinal( $status ) || $action_id <= 0 || ( ! $legacy && $generation <= 0 ) || '' === $flow_step || '' === $retry_at ) { + if ( ! JobStatus::isStatusFinal( $status ) || $action_id <= 0 || $generation <= 0 || '' === $flow_step || '' === $retry_at ) { return $this->status_transition_result( false, false, null, $status ); } @@ -2741,7 +2702,6 @@ public function transition_expired_ai_deferral( int $job_id, string $status, arr array( 'action_id' => $action_id, 'generation' => $generation, - 'legacy' => $legacy, 'flow_step_id' => $flow_step, 'next_retry_at' => $retry_at, 'trigger' => sanitize_key( $trigger ), @@ -3615,22 +3575,17 @@ private function expired_ai_deferral_owner_matches( ?array $job, array $owner ): $resume = is_array( $engine['ai_concurrency_resume_ownership'] ?? null ) ? $engine['ai_concurrency_resume_ownership'] : array(); $action_id = (int) ( $owner['action_id'] ?? 0 ); $generation = (int) ( $owner['generation'] ?? 0 ); - $legacy = ! empty( $owner['legacy'] ); $flow_step = (string) ( $owner['flow_step_id'] ?? '' ); $retry_at = (string) ( $owner['next_retry_at'] ?? '' ); $retry_time = strtotime( $retry_at ); - $throttle_state = (string) ( $throttle['state'] ?? 'deferred' ); - $modern_owner_matches = ! $legacy - && 0 < $generation + $throttle_state = (string) ( $throttle['state'] ?? 'deferred' ); + $owner_matches = 0 < $generation && (int) ( $throttle['resume_generation'] ?? 0 ) === $generation && 'scheduled' === (string) ( $resume['status'] ?? '' ) && (int) ( $resume['action_id'] ?? 0 ) === $action_id && (int) ( $resume['generation'] ?? 0 ) === $generation && (string) ( $resume['flow_step_id'] ?? '' ) === $flow_step; - $legacy_owner_matches = $legacy - && empty( $resume ) - && ! isset( $throttle['resume_generation'] ); if ( 'deferred' !== $throttle_state || 0 >= $action_id @@ -3639,7 +3594,7 @@ private function expired_ai_deferral_owner_matches( ?array $job, array $owner ): || (string) ( $throttle['next_retry_at'] ?? '' ) !== $retry_at || false === $retry_time || $retry_time >= time() - || ( ! $modern_owner_matches && ! $legacy_owner_matches ) + || ! $owner_matches ) { return false; } diff --git a/plugins/data-machine/inc/Core/Database/Jobs/LegacyAIConcurrencyReconciler.php b/plugins/data-machine/inc/Core/Database/Jobs/LegacyAIConcurrencyReconciler.php deleted file mode 100644 index 2c311d952c..0000000000 --- a/plugins/data-machine/inc/Core/Database/Jobs/LegacyAIConcurrencyReconciler.php +++ /dev/null @@ -1,130 +0,0 @@ -} - */ - public function reconcile( int $job_id ): array { - global $wpdb; - - $audit = array( - 'type' => 'legacy_ai_concurrency_failure', - 'source_status' => self::SOURCE_STATUS, - 'target_status' => self::TARGET_STATUS, - ); - $scope = TransactionScope::begin( $wpdb ); - if ( $job_id <= 0 || null === $scope ) { - return $this->result( false, false, null, self::TARGET_STATUS, $audit ); - } - - $table = $wpdb->prefix . 'datamachine_jobs'; - $query = $wpdb->prepare( 'SELECT status, engine_data FROM %i WHERE job_id = %d FOR UPDATE', $table, $job_id ); - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is fully prepared above, including the table identifier. - $job = $wpdb->get_row( $query, ARRAY_A ); - if ( ! is_array( $job ) ) { - $scope->rollback(); - return $this->result( false, false, null, self::TARGET_STATUS, $audit ); - } - - $current_status = is_string( $job['status'] ?? null ) ? $job['status'] : ''; - $engine_data = json_decode( (string) ( $job['engine_data'] ?? '' ), true ); - $engine_data = is_array( $engine_data ) ? $engine_data : array(); - if ( self::TARGET_STATUS === $current_status ) { - $scope->rollback(); - $existing_audit = is_array( $engine_data['status_reconciliation'] ?? null ) ? $engine_data['status_reconciliation'] : $audit; - return $this->result( true, false, $current_status, $current_status, $existing_audit ); - } - if ( self::SOURCE_STATUS !== $current_status ) { - $scope->rollback(); - return $this->result( false, false, $current_status, $current_status, $audit ); - } - - $audit['schema'] = 'datamachine.status_reconciliation.v1'; - $audit['reason'] = 'legacy_contention_misclassified_as_failure'; - $audit['reconciled_at'] = current_time( 'mysql', true ); - $audit['actor'] = defined( 'WP_CLI' ) && WP_CLI ? 'wp_cli' : 'runtime'; - $engine_data['status_reconciliation'] = $audit; - if ( is_array( $engine_data['run_metrics'] ?? null ) ) { - $engine_data['run_metrics']['terminal_status'] = self::TARGET_STATUS; - $engine_data['run_metrics']['counts']['failed'] = 0; - } - $stored_run_result = $engine_data['run_result'] ?? null; - if ( is_array( $stored_run_result ) && WP_Agent_Run_Result_Envelope::SCHEMA === ( $stored_run_result['schema'] ?? null ) ) { - $engine_data['run_result']['status'] = self::TARGET_STATUS; - $engine_data['run_result']['status_detail'] = self::TARGET_STATUS; - - $engine_data['run_result']['outputs']['counts']['failed'] = 0; - - $engine_data['run_result']['metadata']['datamachine']['diagnostics']['reconciliation'] = $audit; - } - - $updated = $wpdb->update( - $table, - array( - 'status' => self::TARGET_STATUS, - 'engine_data' => wp_json_encode( $engine_data ), - ), - array( - 'job_id' => $job_id, - 'status' => self::SOURCE_STATUS, - ), - array( '%s', '%s' ), - array( '%d', '%s' ) - ); - if ( 1 !== $updated || ! $scope->commit() ) { - $scope->rollback(); - wp_cache_delete( $job_id, 'datamachine_engine_data' ); - $winner = ( new Jobs() )->get_job( $job_id ); - $winner_status = is_array( $winner ) && is_string( $winner['status'] ?? null ) ? $winner['status'] : $current_status; - return $this->result( false, false, $winner_status, $winner_status, $audit ); - } - - wp_cache_delete( $job_id, 'datamachine_engine_data' ); - ( new RunLifecycleStore( new Jobs() ) )->mark_job_status( $job_id, self::TARGET_STATUS ); - do_action( 'datamachine_job_status_reconciled', $job_id, $audit ); - do_action( - 'datamachine_log', - 'info', - 'Legacy AI concurrency failure reclassified', - array( - 'job_id' => $job_id, - 'reconciliation' => $audit, - ) - ); - - return $this->result( true, true, $current_status, self::TARGET_STATUS, $audit ); - } - - /** - * @param array $audit Reconciliation audit record. - * @return array{success:bool,changed:bool,current_status:?string,status:string,reconciliation:array} - */ - private function result( bool $success, bool $changed, ?string $current_status, string $status, array $audit ): array { - return array( - 'success' => $success, - 'changed' => $changed, - 'current_status' => $current_status, - 'status' => $status, - 'reconciliation' => $audit, - ); - } -} diff --git a/plugins/data-machine/inc/Core/Database/Migrations/JobsStatusNormalizationMigration.php b/plugins/data-machine/inc/Core/Database/Migrations/JobsStatusNormalizationMigration.php deleted file mode 100644 index 67b78138e5..0000000000 --- a/plugins/data-machine/inc/Core/Database/Migrations/JobsStatusNormalizationMigration.php +++ /dev/null @@ -1,49 +0,0 @@ -withId( ( new JobStatusMigration() )->inspect() ); - } - - public function apply( int $limit ): array { - return $this->withId( ( new JobStatusMigration() )->apply( $limit ) ); - } - - public function isComplete(): bool { - return JobStatusMigration::isComplete(); - } - - /** - * @param array $result Inner migration result. - * @return array - */ - private function withId( array $result ): array { - $result['id'] = $this->id(); - $result['success'] = $result['success'] ?? true; - - return $result; - } -} diff --git a/plugins/data-machine/inc/Core/Database/Migrations/MigrationRunner.php b/plugins/data-machine/inc/Core/Database/Migrations/MigrationRunner.php index 95dabf715b..50b6507aad 100644 --- a/plugins/data-machine/inc/Core/Database/Migrations/MigrationRunner.php +++ b/plugins/data-machine/inc/Core/Database/Migrations/MigrationRunner.php @@ -32,7 +32,6 @@ public static function registered(): array { new JobsStatusReasonBackfill(), new JobsTaskTypeBackfill(), new JobsHandlerSlugBackfill(), - new JobsStatusNormalizationMigration(), ); /** diff --git a/plugins/data-machine/inc/Core/JobStatus.php b/plugins/data-machine/inc/Core/JobStatus.php index 0dc6163732..146e4ad6e5 100644 --- a/plugins/data-machine/inc/Core/JobStatus.php +++ b/plugins/data-machine/inc/Core/JobStatus.php @@ -71,15 +71,12 @@ private function __construct( string $baseStatus, ?string $reason = null ) { } /** - * Create JobStatus from a status string (may be compound). + * Create JobStatus from a status string produced by toString(). * - * Parses strings like "agent_skipped - not a music event" into - * base status and reason components. + * Splits the "base_status - reason" input boundary into base status and + * reason components. */ public static function fromString( string $status ): self { - if ( 'pending_runtime_tool' === $status ) { - return new self( self::WAITING, 'runtime_tool_request' ); - } $baseStatus = self::parseBaseStatus( $status ); $reason = self::parseReason( $status ); @@ -325,7 +322,7 @@ private static function parseBaseStatus( string $status ): string { usort( $base_statuses, static fn( string $a, string $b ): int => strlen( $b ) <=> strlen( $a ) ); foreach ( $base_statuses as $base ) { - if ( $status === $base || str_starts_with( $status, $base . ' - ' ) || str_starts_with( $status, $base . ':' ) ) { + if ( $status === $base || str_starts_with( $status, $base . ' - ' ) ) { return $base; } } @@ -342,11 +339,6 @@ private static function parseReason( string $status ): ?string { $reason = trim( $parts[1] ?? '' ); return '' === $reason ? null : $reason; } - if ( str_contains( $status, ':' ) ) { - $parts = explode( ':', $status, 2 ); - $reason = trim( $parts[1] ?? '' ); - return '' === $reason ? null : $reason; - } return null; } } diff --git a/plugins/data-machine/inc/Engine/AI/conversation-loop.php b/plugins/data-machine/inc/Engine/AI/conversation-loop.php index 6c430f6846..8e9215a08a 100644 --- a/plugins/data-machine/inc/Engine/AI/conversation-loop.php +++ b/plugins/data-machine/inc/Engine/AI/conversation-loop.php @@ -2045,7 +2045,7 @@ function datamachine_continue_runtime_tool_request( array $request, array $canon 'success' => ! empty( $tool_result['success'] ), 'created_at' => gmdate( 'c' ), ); - $metadata['has_pending_tools'] = datamachine_session_has_pending_runtime_tools( $metadata ); + $metadata['has_pending_tools'] = datamachine_session_has_unresolved_runtime_tool_requests( $metadata ); $metadata['status'] = $metadata['has_pending_tools'] ? 'processing' : 'processing'; $metadata['last_activity'] = function_exists( 'current_time' ) ? current_time( 'mysql', true ) : gmdate( 'Y-m-d H:i:s' ); @@ -2169,7 +2169,7 @@ function datamachine_timeout_runtime_tool_request( string $request_id ): void { } /** @param array $metadata Session metadata. */ -function datamachine_session_has_pending_runtime_tools( array $metadata ): bool { +function datamachine_session_has_unresolved_runtime_tool_requests( array $metadata ): bool { foreach ( (array) ( $metadata['runtime_tool_requests'] ?? array() ) as $request ) { if ( is_array( $request ) && 'pending' === (string) ( datamachine_runtime_tool_datamachine_metadata( $request )['persistence_status'] ?? '' ) ) { return true; diff --git a/plugins/data-machine/tests/Unit/Cli/Commands/ProcessedItemsSourceRejectedTest.php b/plugins/data-machine/tests/Unit/Cli/Commands/ProcessedItemsSourceRejectedTest.php index 92b36dfc40..57ebd44241 100644 --- a/plugins/data-machine/tests/Unit/Cli/Commands/ProcessedItemsSourceRejectedTest.php +++ b/plugins/data-machine/tests/Unit/Cli/Commands/ProcessedItemsSourceRejectedTest.php @@ -37,8 +37,7 @@ public function set_up(): void { $this->processed = new ProcessedItems(); $this->jobs = array( - 'legacy_string' => $this->insert_job( 'agent_skipped - source-rejected', null, array() ), - 'legacy_structured' => $this->insert_job( 'agent_skipped', 'source-rejected', array( 'job_status_reason' => 'source-rejected' ) ), + 'structured_skip' => $this->insert_job( 'agent_skipped', 'source-rejected', array( 'job_status_reason' => 'source-rejected' ) ), 'modern_rejected' => $this->insert_job( 'completed_no_items', null, @@ -101,9 +100,9 @@ public function set_up(): void { } } - public function test_default_matches_legacy_and_modern_rejection_evidence_only(): void { + public function test_default_matches_step_result_rejection_evidence_only(): void { $this->assertSame( - array( 'legacy_string', 'legacy_structured', 'modern_other', 'modern_rejected' ), + array( 'modern_other', 'modern_rejected' ), $this->matching_job_names( array( 'flow' => self::FLOW_ID ) ) ); } @@ -123,7 +122,7 @@ public function test_explicit_job_status_overrides_evidence_matching(): void { ); $this->assertSame( - array( 'legacy_string', 'legacy_structured' ), + array( 'structured_skip' ), $this->matching_job_names( array( 'flow' => self::FLOW_ID, 'job-status' => 'agent_skipped - source-rejected' ) ) ); } diff --git a/plugins/data-machine/tests/Unit/Core/Database/JobLifecycleTransitionTest.php b/plugins/data-machine/tests/Unit/Core/Database/JobLifecycleTransitionTest.php index 47f5d5a0fb..bf4cbd6302 100644 --- a/plugins/data-machine/tests/Unit/Core/Database/JobLifecycleTransitionTest.php +++ b/plugins/data-machine/tests/Unit/Core/Database/JobLifecycleTransitionTest.php @@ -8,7 +8,6 @@ namespace DataMachine\Tests\Unit\Core\Database; use DataMachine\Core\Database\Jobs\Jobs; -use DataMachine\Core\Database\Jobs\LegacyAIConcurrencyReconciler; use DataMachine\Core\JobStatus; use DataMachine\Core\RecoveryExecutionFence; use DataMachine\Core\ChildJobRecoveryPolicy; @@ -231,17 +230,15 @@ public function test_expired_pending_ai_deferral_dry_run_and_apply_are_coherent( $this->assertSame( 'scheduler_action_missing', $job['engine_data']['ai_concurrency_history'][0]['reason'] ); } - public function test_legacy_expired_pending_ai_deferral_without_generation_is_recoverable(): void { - $job_id = $this->db_jobs->create_job( array( 'label' => 'Legacy expired pending AI deferral' ) ); - $this->storePendingAIDeferral( $job_id, 900000002, 0, true ); - - $dry_run = ( new RecoverStuckJobsAbility() )->execute( array( 'dry_run' => true, 'job_id' => $job_id, 'limit' => 1 ) ); - $this->assertSame( 1, $dry_run['pending_ai_terminalized'] ); - $this->assertSame( 0, $dry_run['jobs'][0]['generation'] ); + public function test_unfenced_expired_pending_ai_deferral_is_guarded(): void { + $job_id = $this->db_jobs->create_job( array( 'label' => 'Unfenced expired pending AI deferral' ) ); + $this->storePendingAIDeferral( $job_id, 900000002, 0, false ); $applied = ( new RecoverStuckJobsAbility() )->execute( array( 'job_id' => $job_id, 'limit' => 1 ) ); - $this->assertSame( 1, $applied['pending_ai_terminalized'] ); - $this->assertSame( JobStatus::CANCELLED, $this->db_jobs->get_job( $job_id )['status'] ); + $this->assertSame( 0, $applied['pending_ai_terminalized'] ); + $this->assertSame( 1, $applied['pending_ai_guarded'] ); + $this->assertSame( 'incomplete_ai_resume_ownership', $applied['jobs'][0]['reason'] ); + $this->assertSame( JobStatus::PENDING, $this->db_jobs->get_job( $job_id )['status'] ); } public function test_pending_ai_recovery_honors_exact_scope_and_limit(): void { @@ -268,14 +265,14 @@ public function test_pending_ai_recovery_honors_exact_scope_and_limit(): void { $this->assertCount( 1, array_filter( $job_ids, fn( int $id ): bool => JobStatus::PENDING === $this->db_jobs->get_job( $id )['status'] ) ); } - private function storePendingAIDeferral( int $job_id, int $action_id, int $generation, bool $legacy = false ): void { + private function storePendingAIDeferral( int $job_id, int $action_id, int $generation, bool $fenced = true ): void { $engine = datamachine_get_engine_data( $job_id ); $engine['ai_concurrency_throttle'] = array( 'flow_step_id' => 'ai-step', 'next_retry_at' => gmdate( 'c', time() - HOUR_IN_SECONDS ), 'action_id' => $action_id, ); - if ( ! $legacy ) { + if ( $fenced ) { $engine['ai_concurrency_throttle']['state'] = 'deferred'; $engine['ai_concurrency_throttle']['resume_generation'] = $generation; $engine['ai_concurrency_resume_ownership'] = array( @@ -827,86 +824,6 @@ public function test_cancelled_is_generic_terminal_status(): void { $this->assertSame( JobStatus::CANCELLED, $job['status'] ); } - public function test_exact_legacy_ai_contention_failure_can_be_audited_and_reclassified(): void { - $job_id = $this->db_jobs->create_job( array( 'label' => 'Legacy AI contention' ) ); - $this->assertIsInt( $job_id ); - $this->assertTrue( - datamachine_merge_engine_data( - $job_id, - array( - 'run_metrics' => array( - 'terminal_status' => LegacyAIConcurrencyReconciler::SOURCE_STATUS, - 'counts' => array( 'failed' => 1 ), - ), - ) - ) - ); - global $wpdb; - $this->assertSame( - 1, - $wpdb->update( - $wpdb->prefix . 'datamachine_jobs', - array( 'status' => LegacyAIConcurrencyReconciler::SOURCE_STATUS ), - array( 'job_id' => $job_id ), - array( '%s' ), - array( '%d' ) - ) - ); - - $generic_rewrite = $this->db_jobs->transition_job_status_result( $job_id, LegacyAIConcurrencyReconciler::TARGET_STATUS, true ); - $this->assertFalse( $generic_rewrite['success'] ); - - $audits = array(); - $terminal_hooks = array(); - $audit_listener = static function ( int $reconciled_job_id, array $audit ) use ( &$audits ): void { - $audits[] = array( $reconciled_job_id, $audit ); - }; - $terminal_listener = static function ( int $completed_job_id, string $status ) use ( &$terminal_hooks ): void { - $terminal_hooks[] = array( $completed_job_id, $status ); - }; - add_action( 'datamachine_job_status_reconciled', $audit_listener, 10, 2 ); - add_action( 'datamachine_job_complete', $terminal_listener, 10, 2 ); - try { - $reconciled = ( new LegacyAIConcurrencyReconciler() )->reconcile( $job_id ); - } finally { - remove_action( 'datamachine_job_status_reconciled', $audit_listener, 10 ); - remove_action( 'datamachine_job_complete', $terminal_listener, 10 ); - } - $this->assertTrue( $reconciled['success'] ); - $this->assertTrue( $reconciled['changed'] ); - $this->assertSame( LegacyAIConcurrencyReconciler::SOURCE_STATUS, $reconciled['current_status'] ); - $this->assertSame( LegacyAIConcurrencyReconciler::TARGET_STATUS, $reconciled['status'] ); - - $job = $this->db_jobs->get_job( $job_id ); - $this->assertSame( LegacyAIConcurrencyReconciler::TARGET_STATUS, $job['status'] ); - $this->assertSame( 'datamachine.status_reconciliation.v1', $job['engine_data']['status_reconciliation']['schema'] ); - $this->assertSame( LegacyAIConcurrencyReconciler::SOURCE_STATUS, $job['engine_data']['status_reconciliation']['source_status'] ); - $this->assertSame( LegacyAIConcurrencyReconciler::TARGET_STATUS, $job['engine_data']['status_reconciliation']['target_status'] ); - $this->assertSame( 0, $job['engine_data']['run_metrics']['counts']['failed'] ); - $this->assertCount( 1, $audits ); - $this->assertSame( $job_id, $audits[0][0] ); - $this->assertSame( array(), $terminal_hooks ); - - $idempotent = ( new LegacyAIConcurrencyReconciler() )->reconcile( $job_id ); - $this->assertTrue( $idempotent['success'] ); - $this->assertFalse( $idempotent['changed'] ); - } - - public function test_legacy_ai_contention_reconciliation_rejects_every_other_terminal_status(): void { - $job_id = $this->db_jobs->create_job( array( 'label' => 'Unrelated terminal status' ) ); - $this->assertIsInt( $job_id ); - $this->assertTrue( $this->db_jobs->complete_job( $job_id, JobStatus::failed( 'handler_failure' )->toString() ) ); - - $reconciled = ( new LegacyAIConcurrencyReconciler() )->reconcile( $job_id ); - $this->assertFalse( $reconciled['success'] ); - $this->assertFalse( $reconciled['changed'] ); - - $job = $this->db_jobs->get_job( $job_id ); - $this->assertSame( JobStatus::FAILED, $job['status'] ); - $this->assertSame( 'handler_failure', $job['engine_data']['job_status_reason'] ); - $this->assertArrayNotHasKey( 'status_reconciliation', $job['engine_data'] ); - } - public function test_ai_resume_generation_ownership_advances_with_cas(): void { $job_id = $this->db_jobs->create_job( array( 'label' => 'AI resume generation ownership' ) ); $this->assertIsInt( $job_id ); diff --git a/plugins/data-machine/tests/Unit/Core/Database/JobStatusStorageTest.php b/plugins/data-machine/tests/Unit/Core/Database/JobStatusStorageTest.php index 3c48b01fa2..1b2233e500 100644 --- a/plugins/data-machine/tests/Unit/Core/Database/JobStatusStorageTest.php +++ b/plugins/data-machine/tests/Unit/Core/Database/JobStatusStorageTest.php @@ -8,7 +8,6 @@ namespace DataMachine\Tests\Unit\Core\Database; use DataMachine\Core\Database\Jobs\Jobs; -use DataMachine\Core\Database\Jobs\JobStatusMigration; use DataMachine\Core\Database\Migrations\JobsStatusReasonBackfill; use DataMachine\Core\Database\Migrations\MigrationRunner; use DataMachine\Core\JobStatus; @@ -97,30 +96,6 @@ public function test_schema_backfill_splits_compound_status_and_preserves_detail $this->assertSame( 'Exception: timeout - retry exhausted', $row['status_reason'] ); } - public function test_migration_splits_compound_values_including_separator_in_detail(): void { - $job_id = $this->create_pending_job( 'Legacy compound' ); - global $wpdb; - $wpdb->update( - $wpdb->prefix . Jobs::TABLE_NAME, - array( - 'status' => 'failed - provider timeout - retry exhausted', - 'status_reason' => null, - ), - array( 'job_id' => $job_id ), - array( '%s', null ), - array( '%d' ) - ); - - delete_option( JobStatusMigration::STATE_OPTION ); - $migration = new JobStatusMigration(); - $result = $migration->apply( 10 ); - - $this->assertGreaterThanOrEqual( 1, (int) $result['migrated'] ); - $row = $this->raw_job_row( $job_id ); - $this->assertSame( JobStatus::FAILED, $row['status'] ); - $this->assertSame( 'provider timeout - retry exhausted', $row['status_reason'] ); - } - public function test_typeerror_exception_is_not_stored_in_status(): void { $job_id = $this->create_pending_job( 'TypeError path' ); $exception = 'DataMachineCode\\Workspace\\WorktreeContextInjector::has_owner_terminal_disposable_cleanup_signal(): Argument #1 ($metadata) must be of type array, null given, called in /Users/example/wp-content/plugins/data-machine-code/inc/Workspace/WorkspaceWorktreeCleanupEngine.php:376'; diff --git a/plugins/data-machine/tests/ai-step-backpressure-smoke.php b/plugins/data-machine/tests/ai-step-backpressure-smoke.php index 5aef1b2cc9..56b714dc2d 100644 --- a/plugins/data-machine/tests/ai-step-backpressure-smoke.php +++ b/plugins/data-machine/tests/ai-step-backpressure-smoke.php @@ -333,7 +333,6 @@ function sanitize_key( string $key ): string { $retry_src = file_get_contents( __DIR__ . '/../inc/Core/JobRetryPolicy.php' ) ?: ''; $backpressure_src = file_get_contents( __DIR__ . '/../inc/Engine/AI/AIConcurrencyBackpressure.php' ) ?: ''; $schedule_failure_src = file_get_contents( __DIR__ . '/../inc/Engine/AI/AIConcurrencyScheduleFailure.php' ) ?: ''; -$reconciler_src = file_get_contents( __DIR__ . '/../inc/Core/Database/Jobs/LegacyAIConcurrencyReconciler.php' ) ?: ''; $fetch_src = file_get_contents( __DIR__ . '/../inc/Core/Steps/Fetch/FetchStep.php' ) ?: ''; $upsert_files = glob( __DIR__ . '/../inc/Core/Steps/Upsert/*.php' ) ?: array(); $upsert_src = implode( "\n", array_map( static fn( string $path ): string => file_get_contents( $path ) ?: '', $upsert_files ) ); @@ -369,7 +368,7 @@ function sanitize_key( string $key ): string { echo "Case 7: age-bounded stranded work terminates distinctly\n"; $stranded = AIConcurrencyBackpressure::nextState( $state, 'ai-1', $now + DAY_IN_SECONDS + 1, DAY_IN_SECONDS ); assert_ai_backpressure_smoke( 'maximum contention age marks work stranded', 'stranded' === $stranded['state'] ); -assert_ai_backpressure_smoke( 'stranded work is cancelled instead of failed', str_contains( $reconciler_src, 'cancelled - ai_concurrency_stranded' ) && str_contains( $ai_src, 'cancelled - ai_concurrency_stranded' ) ); +assert_ai_backpressure_smoke( 'stranded work is cancelled instead of failed', str_contains( $ai_src, 'cancelled - ai_concurrency_stranded' ) ); assert_ai_backpressure_smoke( 'maximum contention age is filterable', str_contains( $ai_src, 'datamachine_ai_concurrency_max_defer_age' ) ); assert_ai_backpressure_smoke( 'backoff remains capped', 120 === AIConcurrencyBackpressure::delaySeconds( 10, 30, 120 ) ); assert_ai_backpressure_smoke( 'AI step backoff cap defaults to 120 seconds', str_contains( $ai_src, 'AI_CONCURRENCY_MAX_DEFER_DELAY = 120' ) ); diff --git a/plugins/data-machine/tests/job-status-accounting-smoke.php b/plugins/data-machine/tests/job-status-accounting-smoke.php index 268b230f50..a49fb57b03 100644 --- a/plugins/data-machine/tests/job-status-accounting-smoke.php +++ b/plugins/data-machine/tests/job-status-accounting-smoke.php @@ -120,7 +120,6 @@ function wp_json_encode( $value, int $flags = 0, int $depth = 512 ) { echo "\n[4] reconcile-status command exists with repair markers\n"; $jobs_command = file_get_contents( __DIR__ . '/../inc/Cli/Commands/JobsCommand.php' ); $jobs_repository = file_get_contents( __DIR__ . '/../inc/Core/Database/Jobs/Jobs.php' ); -$contention_reconciler = file_get_contents( __DIR__ . '/../inc/Core/Database/Jobs/LegacyAIConcurrencyReconciler.php' ); $assert( 'CLI exposes reconcile-status subcommand', str_contains( $jobs_command, '@subcommand reconcile-status' ) ); $assert( 'CLI detects successful wiki update artifacts', str_contains( $jobs_command, 'Updated wiki article:' ) ); $assert( 'CLI detects source rejection artifacts', str_contains( $jobs_command, 'Source rejected:' ) ); @@ -128,8 +127,6 @@ function wp_json_encode( $value, int $flags = 0, int $depth = 512 ) { $assert( 'CLI requires successful runtime provenance', str_contains( $jobs_command, 'engine_data_has_successful_runtime' ) ); $assert( 'CLI requires successful handler tool summary', str_contains( $jobs_command, 'engine_data_has_successful_handler_tool' ) ); $assert( 'CLI supports dry-run output', str_contains( $jobs_command, "'dry_run' => $" ) || str_contains( $jobs_command, "'dry_run' => \$dry_run" ) ); -$assert( 'historical concurrency failures reconcile without replay', str_contains( $contention_reconciler, 'failed - ai_concurrency_defer_exhausted' ) && str_contains( $contention_reconciler, 'cancelled - ai_concurrency_stranded' ) ); -$assert( 'historical contention uses exact repository reconciliation', str_contains( $jobs_command, 'LegacyAIConcurrencyReconciler' ) ); echo "\n[5] compact job summary avoids heavyweight breakdowns\n"; $summary_ability = file_get_contents( __DIR__ . '/../inc/Abilities/Job/JobsSummaryAbility.php' ); diff --git a/plugins/data-machine/tests/job-status-normalization-smoke.php b/plugins/data-machine/tests/job-status-normalization-smoke.php deleted file mode 100644 index 6e537446b0..0000000000 --- a/plugins/data-machine/tests/job-status-normalization-smoke.php +++ /dev/null @@ -1,178 +0,0 @@ -rows, - static fn( array $row ): bool => $row['job_id'] > $cursor && ! in_array( $row['status'], $canonical, true ) - ); - usort( $rows, static fn( array $a, array $b ): int => $a['job_id'] <=> $b['job_id'] ); - $batch = array_slice( array_values( $rows ), 0, $limit ); - $this->selected_batches[] = array_column( $batch, 'job_id' ); - return $batch; - } - - public function get_var( $query = null, $x = 0, $y = 0 ) { - if ( ! is_array( $query ) ) { - return null; - } - $args = $query[1]; - $canonical = 1 === count( $args ) && is_array( $args[0] ) ? array_slice( $args[0], 1 ) : array_slice( $args, 1 ); - return count( array_filter( $this->rows, static fn( array $row ): bool => ! in_array( $row['status'], $canonical, true ) ) ); - } - - public function get_row( $query = null, $output = OBJECT, $y = 0 ) { - $job_id = (int) end( $query[1] ); - return $this->rows[ $job_id ] ?? null; - } - - public function update( $table, $data, $where, $format = null, $where_format = null ) { - $job_id = (int) $where['job_id']; - if ( ! isset( $this->rows[ $job_id ] ) || $this->rows[ $job_id ]['status'] !== $where['status'] ) { - return 0; - } - $this->rows[ $job_id ] = array_merge( $this->rows[ $job_id ], $data ); - return 1; - } - - public function query( $query ) { - return 1; - } -} - -require_once __DIR__ . '/../inc/Core/Database/TransactionScope.php'; -require_once __DIR__ . '/../inc/Core/JobStatus.php'; - -if ( ! class_exists( 'DataMachine\\Core\\Database\\Jobs\\Jobs' ) ) { - // Keep the fallback aligned with the owner without duplicating its raw slug literal. - eval( 'namespace DataMachine\\Core\\Database\\Jobs; class Jobs { public const TABLE_NAME = "datamachine_" . "jobs"; }' ); -} - -require_once __DIR__ . '/../inc/Core/Database/Jobs/JobStatusMigration.php'; - -use DataMachine\Core\JobStatus; -use DataMachine\Core\Database\Jobs\JobStatusMigration; - -$failures = array(); -$assert = static function ( bool $condition, string $label ) use ( &$failures ): void { - if ( ! $condition ) { - $failures[] = $label; - } -}; - -$compound = JobStatus::fromString( 'failed - provider timeout - retry exhausted' ); -$assert( JobStatus::FAILED === $compound->getBaseStatus(), 'compound base is parsed' ); -$assert( 'provider timeout - retry exhausted' === $compound->getReason(), 'compound reason is lossless' ); -$colon = JobStatus::fromString( 'failed: policy rejected' ); -$assert( 'policy rejected' === $colon->getReason(), 'legacy colon reason is parsed' ); -$assert( ! JobStatus::fromString( 'failedly' )->isCanonical(), 'prefix collisions are rejected' ); -$runtime = JobStatus::fromString( 'pending_runtime_tool' ); -$assert( JobStatus::WAITING === $runtime->getBaseStatus() && 'runtime_tool_request' === $runtime->getReason(), 'legacy runtime-tool state maps explicitly' ); - -$wpdb = new JobStatusMigrationWpdb(); -$wpdb->rows = array( - 1 => array( 'job_id' => 1, 'status' => 'failed - provider timeout', 'engine_data' => '{"retry":{"attempt":2}}' ), - 500000 => array( 'job_id' => 500000, 'status' => 'completed', 'engine_data' => '{}' ), - 1000000 => array( 'job_id' => 1000000, 'status' => 'pending_runtime_tool', 'engine_data' => '{"runtime_tool_request":{"id":"r1"}}' ), -); -$migration = new JobStatusMigration( $wpdb ); -$dry_run = $migration->inspect(); -$assert( 2 === $dry_run['remaining'] && 'migration_required' === $dry_run['status'], 'dry run reports remaining rows' ); -$assert( 'failed - provider timeout' === $wpdb->rows[1]['status'], 'dry run does not mutate rows' ); - -$first = $migration->apply( 1 ); -$engine = json_decode( $wpdb->rows[1]['engine_data'], true ); -$assert( 'failed' === $wpdb->rows[1]['status'], 'first bounded batch stores base status' ); -$assert( 'provider timeout' === $wpdb->rows[1]['status_reason'], 'first batch stores reason in status_reason' ); -$assert( 'provider timeout' === $engine['job_status_reason'], 'first batch preserves reason beside existing metadata' ); -$assert( array( 1 ) === $wpdb->selected_batches[0], 'first batch selects only the sparse noncanonical candidate' ); -$assert( 1 === $first['migrated'] && 'in_progress' === $first['status'], 'first bounded candidate batch exposes resumable progress' ); - -$second = $migration->apply( 1 ); -$runtime_engine = json_decode( $wpdb->rows[1000000]['engine_data'], true ); -$assert( 'waiting' === $wpdb->rows[1000000]['status'], 'second batch normalizes explicit legacy state across a huge ID gap' ); -$assert( 'runtime_tool_request' === $wpdb->rows[1000000]['status_reason'], 'mapped legacy reason is stored in status_reason' ); -$assert( 'runtime_tool_request' === $runtime_engine['job_status_reason'], 'mapped legacy reason is persisted' ); -$assert( array( 1000000 ) === $wpdb->selected_batches[1], 'second batch skips the canonical row across the sparse ID gap' ); -$assert( 2 === $second['scanned'], 'scanned evidence counts candidates rather than canonical rows' ); - -$complete = $migration->apply( 1 ); -$assert( $complete['complete'] && JobStatusMigration::isComplete(), 'completion is durable after final verification' ); - -$wpdb->rows[500000] = array( 'job_id' => 500000, 'status' => 'failed: late legacy insert', 'engine_data' => '{}' ); -$late = $migration->apply( 1 ); -$assert( ! $late['complete'] && 1 === $late['remaining'], 'final verification detects a late candidate behind the cursor' ); -$assert( 0 === $late['cursor'], 'residue behind the cursor rewinds persisted progress' ); -$assert( ! JobStatusMigration::isComplete(), 'late residue clears durable completion' ); - -$resumed = $migration->apply( 1 ); -$assert( 'failed' === $wpdb->rows[500000]['status'], 'rewound cursor migrates the late legacy row' ); -$assert( 3 === $resumed['migrated'] && 3 === $resumed['scanned'], 'resume preserves cumulative v1 migration evidence' ); - -$again = $migration->apply( 1 ); -$assert( 0 === $again['remaining'] && $again['complete'], 'repeated apply remains idempotent' ); -$assert( 3 === count( $GLOBALS['dm_status_cache_deletes'] ), 'each migrated engine snapshot invalidates cache' ); - -$GLOBALS['dm_status_options'] = array(); -$invalid_wpdb = new JobStatusMigrationWpdb(); -$invalid_wpdb->rows = array( - 1 => array( 'job_id' => 1, 'status' => 'failed - reason', 'engine_data' => '{not-json' ), -); -$invalid = ( new JobStatusMigration( $invalid_wpdb ) )->apply( 1 ); -$assert( 'failed - reason' === $invalid_wpdb->rows[1]['status'], 'malformed engine data fails without changing status' ); -$assert( '{not-json' === $invalid_wpdb->rows[1]['engine_data'], 'malformed engine data is never replaced' ); -$assert( 1 === $invalid['errors'], 'malformed engine data exposes a migration error' ); - -$GLOBALS['dm_status_options'] = array(); -$unknown_wpdb = new JobStatusMigrationWpdb(); -$unknown_wpdb->rows = array( - 10 => array( 'job_id' => 10, 'status' => 'mystery_status', 'engine_data' => '{}' ), -); -$unknown = ( new JobStatusMigration( $unknown_wpdb ) )->apply( 2 ); -$assert( 'mystery_status' === $unknown_wpdb->rows[10]['status'], 'unknown status is never rewritten' ); -$assert( 1 === $unknown['unknown'] && 1 === $unknown['remaining'], 'unknown status preserves migration evidence' ); -$assert( 0 === $unknown['cursor'], 'unknown residue rewinds the cursor for operator remediation' ); - -if ( $failures ) { - echo 'FAIL: ' . implode( "\nFAIL: ", $failures ) . "\n"; - exit( 1 ); -} - -echo "Job status normalization smoke complete: all assertions passed.\n"; diff --git a/plugins/data-machine/tests/jobs-cleanup-status-variants-smoke.php b/plugins/data-machine/tests/jobs-cleanup-status-variants-smoke.php index c449114153..4693b54462 100644 --- a/plugins/data-machine/tests/jobs-cleanup-status-variants-smoke.php +++ b/plugins/data-machine/tests/jobs-cleanup-status-variants-smoke.php @@ -2,9 +2,9 @@ /** * Smoke coverage for jobs cleanup status matching (#2858). * - * Verifies that count_old_jobs() / delete_old_jobs() match compound failed - * statuses (`failed - x`, `failed: y`) and bare `failed`, that the completed - * IN-optimization is unchanged, and that the age filter protects recent jobs. + * Verifies that count_old_jobs() / delete_old_jobs() match canonical statuses + * exactly, that the completed IN-optimization is unchanged, and that the age + * filter protects recent jobs. * * Runs via: php tests/jobs-cleanup-status-variants-smoke.php * @@ -31,12 +31,6 @@ function sanitize_text_field( $value ) { } } -if ( ! function_exists( 'get_option' ) ) { - function get_option( string $option, $default = false ) { - return $default; - } -} - require_once __DIR__ . '/bootstrap-unit.php'; use DataMachine\Core\Database\Jobs\Jobs; @@ -221,9 +215,8 @@ function dm_jobs_with( array $rows ): Jobs { echo "=== jobs-cleanup-status-variants-smoke ===\n"; /* - * Build a representative row set mirroring the production evidence in #2858: - * - compound failures (the only real failure shape in production) - * - one bare `failed` row (defensive: must still match) + * Build a representative row set: + * - old failed rows * - completed variants (IN optimization must stay intact) * - a recent failed row that must be protected by the age filter * - a non-terminal status that must never be touched @@ -232,29 +225,28 @@ function dm_jobs_with( array $rows ): Jobs { $recent_ts = gmdate( 'Y-m-d H:i:s', time() - ( 1 * DAY_IN_SECONDS ) ); $base_rows = array( - array( 'status' => 'failed - packet_failure', 'created_at' => $old_ts ), - array( 'status' => 'failed: Daily memory completion policy was not satisfied', 'created_at' => $old_ts ), + array( 'status' => 'failed', 'created_at' => $old_ts ), + array( 'status' => 'failed', 'created_at' => $old_ts ), array( 'status' => 'failed', 'created_at' => $old_ts ), array( 'status' => 'completed', 'created_at' => $old_ts ), array( 'status' => 'completed_no_items', 'created_at' => $old_ts ), array( 'status' => 'agent_skipped', 'created_at' => $old_ts ), - array( 'status' => 'failed - recent', 'created_at' => $recent_ts ), + array( 'status' => 'failed', 'created_at' => $recent_ts ), array( 'status' => 'processing', 'created_at' => $old_ts ), ); -// --- count_old_jobs('failed') must see all 3 old failed rows (compound + bare) --- +// --- count_old_jobs('failed') must see all 3 old failed rows --- $jobs = dm_jobs_with( $base_rows ); $count = $jobs->count_old_jobs( 'failed', 7 ); dm_cleanup_assert( - 'count_old_jobs(failed) matches compound + bare failed (3)', + 'count_old_jobs(failed) matches old failed rows (3)', 3 === $count, "expected 3, got {$count}; query: " . $GLOBALS['wpdb']->last_query ); dm_cleanup_assert( - 'count_old_jobs(failed) uses exact base plus bounded legacy delimiters', + 'count_old_jobs(failed) uses exact status matching', false !== strpos( $GLOBALS['wpdb']->last_query, "status IN ('failed')" ) - && false !== strpos( $GLOBALS['wpdb']->last_query, "status LIKE 'failed - %'" ) - && false !== strpos( $GLOBALS['wpdb']->last_query, "status LIKE 'failed:%'" ) + && false === strpos( $GLOBALS['wpdb']->last_query, 'status LIKE' ) ); dm_cleanup_assert( 'count_old_jobs(failed) applies the age cutoff', @@ -270,15 +262,15 @@ function dm_jobs_with( array $rows ): Jobs { "expected 3, got {$deleted}; query: " . $GLOBALS['wpdb']->last_query ); dm_cleanup_assert( - 'delete_old_jobs(failed) uses bounded legacy delimiters', - false !== strpos( $GLOBALS['wpdb']->last_query, "status LIKE 'failed - %'" ) + 'delete_old_jobs(failed) uses exact status matching', + false === strpos( $GLOBALS['wpdb']->last_query, 'status LIKE' ) ); // Recent failed job survived the age-gated delete. $remaining_statuses = array_column( $GLOBALS['wpdb']->rows, 'status' ); dm_cleanup_assert( 'recent failed job is NOT deleted (age filter protects it)', - in_array( 'failed - recent', $remaining_statuses, true ), + in_array( 'failed', $remaining_statuses, true ), 'remaining: ' . implode( ',', $remaining_statuses ) ); @@ -318,8 +310,7 @@ function dm_jobs_with( array $rows ): Jobs { $remaining_statuses = array_column( $GLOBALS['wpdb']->rows, 'status' ); dm_cleanup_assert( 'delete_old_jobs(completed) leaves failed rows untouched', - in_array( 'failed', $remaining_statuses, true ) - && in_array( 'failed - packet_failure', $remaining_statuses, true ) + 4 === count( array_keys( $remaining_statuses, 'failed', true ) ) ); // --- empty/invalid inputs are rejected without touching rows --- diff --git a/plugins/data-machine/tests/jobs-command-reconciliation-smoke.php b/plugins/data-machine/tests/jobs-command-reconciliation-smoke.php index 1c42d9a74d..2214769a19 100644 --- a/plugins/data-machine/tests/jobs-command-reconciliation-smoke.php +++ b/plugins/data-machine/tests/jobs-command-reconciliation-smoke.php @@ -1,5 +1,5 @@ newInstanceWithoutConstructor(); $resolver = $reflection->getMethod( 'resolve_reconciled_job_status' ); - $planner = $reflection->getMethod( 'resolve_reconciled_job_plan' ); - - $source_rejected = array( - 'status' => LegacyAIConcurrencyReconciler::SOURCE_STATUS, - 'engine_data' => json_encode( array( 'job_status' => 'agent_skipped - source-rejected' ) ), - ); - $runtime_success = array( - 'status' => LegacyAIConcurrencyReconciler::SOURCE_STATUS, - 'engine_data' => json_encode( - array( - 'runtime_provenance' => array( 'status' => array( 'completed' => true ) ), - 'tool_execution_summary' => array( array( 'tool_name' => 'wiki_upsert', 'success' => true ) ), - ) - ), - ); echo "=== jobs-command-reconciliation-smoke ===\n"; - foreach ( array( 'source-rejected evidence' => $source_rejected, 'runtime-success evidence' => $runtime_success ) as $label => $row ) { - $target = $resolver->invoke( $command, $row ); - $plan = $planner->invoke( $command, $row ); - $assert( "exact legacy status wins over {$label}", LegacyAIConcurrencyReconciler::TARGET_STATUS === $target ); - $assert( "{$label} cannot select generic complete_job path", 'legacy_ai_concurrency' === $plan['strategy'] ); - } - $generic = $planner->invoke( + $skipped = $resolver->invoke( $command, array( - 'status' => 'failed - handler_failure', + 'status' => 'failed', 'engine_data' => json_encode( array( 'job_status' => 'agent_skipped - source-rejected' ) ), ) ); - $assert( 'non-legacy evidence retains generic transition strategy', 'terminal_transition' === $generic['strategy'] ); - $assert( 'non-legacy evidence retains derived target status', 'agent_skipped - source-rejected' === $generic['target_status'] ); + $assert( 'engine skip status is the reconciled target', 'agent_skipped - source-rejected' === $skipped ); + + $runtime_success = $resolver->invoke( + $command, + array( + 'status' => 'failed', + 'engine_data' => json_encode( + array( + 'runtime_provenance' => array( 'status' => array( 'completed' => true ) ), + 'tool_execution_summary' => array( array( 'tool_name' => 'wiki_upsert', 'success' => true ) ), + ) + ), + ) + ); + $assert( 'successful runtime and handler evidence reconciles to completed', 'completed' === $runtime_success ); + + $no_evidence = $resolver->invoke( + $command, + array( + 'status' => 'failed', + 'engine_data' => json_encode( array() ), + ) + ); + $assert( 'rows without evidence are left alone', '' === $no_evidence ); echo "\nJobs command reconciliation smoke complete: {$total} assertions, {$failed} failures.\n"; exit( $failed > 0 ? 1 : 0 ); diff --git a/plugins/data-machine/tests/jobs-trim-runtime-queues-smoke.php b/plugins/data-machine/tests/jobs-trim-runtime-queues-smoke.php deleted file mode 100644 index 7ed728b61f..0000000000 --- a/plugins/data-machine/tests/jobs-trim-runtime-queues-smoke.php +++ /dev/null @@ -1,43 +0,0 @@ -store_engine_data( $job_id, $after )' ) ); -assert_jobs_trim_runtime_queues_smoke( 'helper strips config patch queue', str_contains( $source, '$flow_step_config[\'config_patch_queue\']' ) ); -assert_jobs_trim_runtime_queues_smoke( 'helper strips prompt queue', str_contains( $source, '$flow_step_config[\'prompt_queue\']' ) ); -assert_jobs_trim_runtime_queues_smoke( 'helper strips queue revision', str_contains( $source, '$flow_step_config[\'_queue_consume_revision\']' ) ); - -echo "\nJobs trim runtime queues smoke complete: {$total} assertions, {$failed} failures.\n"; -if ( $failed > 0 ) { - exit( 1 ); -} diff --git a/plugins/data-machine/tests/processed-items-source-rejected-cli-smoke.php b/plugins/data-machine/tests/processed-items-source-rejected-cli-smoke.php index cfc6b84c8f..849e95ad6e 100644 --- a/plugins/data-machine/tests/processed-items-source-rejected-cli-smoke.php +++ b/plugins/data-machine/tests/processed-items-source-rejected-cli-smoke.php @@ -76,8 +76,7 @@ function datamachine_source_rejected_assert( bool $cond, string $msg ): void { echo "Test 1: default query matches persisted source-rejection evidence\n"; $result = $query_parts->invoke( $cmd, array(), 'wp_datamachine_processed_items', 'wp_datamachine_jobs' ); datamachine_source_rejected_assert( str_contains( $result['where_sql'], 'pi.status = %s' ), 'filters processed item status' ); -datamachine_source_rejected_assert( str_contains( $result['where_sql'], 'j.status = %s' ), 'still matches legacy job status' ); -datamachine_source_rejected_assert( str_contains( $result['where_sql'], 'j.status_reason = %s' ), 'matches legacy structured status_reason column' ); +datamachine_source_rejected_assert( ! str_contains( $result['where_sql'], 'j.status = %s' ), 'does not match by job status' ); datamachine_source_rejected_assert( str_contains( $result['where_sql'], 'j.engine_data REGEXP %s' ), 'matches rejection reason evidence' ); datamachine_source_rejected_assert( ! in_array( 'completed_no_items', $result['values'], true ), 'does not match completed_no_items by status alone' ); datamachine_source_rejected_assert( @@ -85,17 +84,13 @@ function datamachine_source_rejected_assert( bool $cond, string $msg ): void { 'wp_datamachine_processed_items', 'wp_datamachine_jobs', 'processed', - 'agent_skipped - source-rejected', - 'agent_skipped', - 'source-rejected', - '%"job_status_reason":"source-rejected"%', '%"result":"source_rejected"%', '"source_rejection_reason":"[^"]', ) === $result['values'], - 'default values cover legacy storage and modern step-result evidence' + 'default values cover step-result evidence' ); -datamachine_source_rejected_assert( 1 === preg_match( '/' . $result['values'][8] . '/', '{"step_results":{"1_2":{"source_rejection_reason":"irrelevant_location"}}}' ), 'reason pattern matches non-empty reason' ); -datamachine_source_rejected_assert( 0 === preg_match( '/' . $result['values'][8] . '/', '{"step_results":{"1_2":{"source_rejection_reason":""}}}' ), 'reason pattern ignores empty reason' ); +datamachine_source_rejected_assert( 1 === preg_match( '/' . $result['values'][4] . '/', '{"step_results":{"1_2":{"source_rejection_reason":"irrelevant_location"}}}' ), 'reason pattern matches non-empty reason' ); +datamachine_source_rejected_assert( 0 === preg_match( '/' . $result['values'][4] . '/', '{"step_results":{"1_2":{"source_rejection_reason":""}}}' ), 'reason pattern ignores empty reason' ); echo "Test 1b: explicit --job-status overrides evidence matching\n"; $result = $query_parts->invoke( $cmd, array( 'job-status' => 'completed_no_items' ), 'wp_datamachine_processed_items', 'wp_datamachine_jobs' ); diff --git a/plugins/data-machine/tests/runtime-tool-contract-store-smoke.php b/plugins/data-machine/tests/runtime-tool-contract-store-smoke.php index dc26028d87..b6dfca7faf 100644 --- a/plugins/data-machine/tests/runtime-tool-contract-store-smoke.php +++ b/plugins/data-machine/tests/runtime-tool-contract-store-smoke.php @@ -107,7 +107,6 @@ public static function formatToolResultMessage( string $tool_name, array $tool_r use function DataMachine\Engine\AI\datamachine_prepare_runtime_tool_pending_result; use function DataMachine\Engine\AI\datamachine_prepare_runtime_tool_request; use function DataMachine\Engine\AI\datamachine_runtime_tool_request_store; - use function DataMachine\Engine\AI\datamachine_session_has_pending_runtime_tools; use function DataMachine\Engine\AI\datamachine_submit_runtime_tool_result; use function DataMachine\Engine\AI\datamachine_timeout_runtime_tool_request; diff --git a/plugins/data-machine/tests/worker-status-job-counts-smoke.php b/plugins/data-machine/tests/worker-status-job-counts-smoke.php index a8358684fd..10951c72a4 100644 --- a/plugins/data-machine/tests/worker-status-job-counts-smoke.php +++ b/plugins/data-machine/tests/worker-status-job-counts-smoke.php @@ -22,10 +22,6 @@ function esc_html( $value ): string { return htmlspecialchars( (string) $value, ENT_QUOTES, 'UTF-8' ); } -function get_option( string $option, $default = false ) { - return $default; -} - final class WorkerStatusCountsWpdb { public string $prefix = 'wp_'; public string $last_error = ''; @@ -51,7 +47,6 @@ public function get_var( string $query ) { require_once __DIR__ . '/../inc/Core/Database/BaseRepository.php'; require_once __DIR__ . '/../inc/Core/JobStatus.php'; -require_once __DIR__ . '/../inc/Core/Database/Jobs/JobStatusMigration.php'; require_once __DIR__ . '/../inc/Core/Database/Jobs/Jobs.php'; require_once __DIR__ . '/../inc/Cli/BaseCommand.php'; require_once __DIR__ . '/../inc/Cli/Commands/WorkerCommand.php'; @@ -74,9 +69,9 @@ public function get_var( string $query ) { $assert( array( 'processing' => 9, 'pending' => 1122, 'failed' => 5739 ) === $counts, 'operator status returns global repository counts without an acting user' ); $assert( 3 === count( $wpdb->prepare_calls ), 'operator status performs only three COUNT queries' ); -$assert( array( 'processing', 'processing - %', 'processing:%' ) === array_slice( $wpdb->prepare_calls[0], 1 ), 'processing count covers exact and bounded legacy rows' ); -$assert( array( 'pending', 'pending - %', 'pending:%' ) === array_slice( $wpdb->prepare_calls[1], 1 ), 'pending count covers exact and bounded legacy rows' ); -$assert( array( 'failed', 'failed - %', 'failed:%' ) === array_slice( $wpdb->prepare_calls[2], 1 ), 'failed count covers exact and bounded legacy rows' ); +$assert( array( 'processing' ) === array_slice( $wpdb->prepare_calls[0], 1 ), 'processing count matches the exact status' ); +$assert( array( 'pending' ) === array_slice( $wpdb->prepare_calls[1], 1 ), 'pending count matches the exact status' ); +$assert( array( 'failed' ) === array_slice( $wpdb->prepare_calls[2], 1 ), 'failed count matches the exact status' ); $wpdb->counts = array( null ); $wpdb->last_error = 'simulated count failure';