diff --git a/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php b/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php index 200ddc397b..4aa3138a87 100644 --- a/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php +++ b/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php @@ -617,8 +617,9 @@ public function test_case_variant_sql_row_uses_acquisition_descriptor_authoritat $lowercase = 'tm-case-' . uniqid(); $uppercase = strtoupper( $lowercase ); $processed = new ProcessedItems(); - $this->assertTrue( $processed->claim_item( TicketmasterSourceIdentity::CLAIM_SCOPE, 'ticketmaster', $lowercase, 1701 ) ); - $this->assertSame( 1, $processed->complete_claim_for_job( TicketmasterSourceIdentity::CLAIM_SCOPE, 'ticketmaster', $lowercase, 1701 ) ); + $token = $processed->claim_item_owned( TicketmasterSourceIdentity::CLAIM_SCOPE, 'ticketmaster', $lowercase, 1701 ); + $this->assertIsString( $token ); + $this->assertTrue( $processed->complete_owned_claim( TicketmasterSourceIdentity::CLAIM_SCOPE, 'ticketmaster', $lowercase, $token, 1701 ) ); $packets = ( new TicketmasterHandlerTestDouble( array( 0 => $this->ticketmasterPage( array( $this->ticketmasterEvent( $uppercase, 'Case Variant Event' ) ) ) ) ) ) ->get_fetch_data( 1, $this->handlerConfig( '32.7765,-79.9311', 'case-variant-fetch' ), '1702' ); diff --git a/plugins/data-machine/docs/development/1-0-baseline.md b/plugins/data-machine/docs/development/1-0-baseline.md index 3b3e3c667f..b6405077e0 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 named CLI commands. -- **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. +- **Concrete persisted production data:** generation-less recurring actions, 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/Core/ActionScheduler/BatchScheduler.php b/plugins/data-machine/inc/Core/ActionScheduler/BatchScheduler.php index ae68b5406c..b7438af4eb 100644 --- a/plugins/data-machine/inc/Core/ActionScheduler/BatchScheduler.php +++ b/plugins/data-machine/inc/Core/ActionScheduler/BatchScheduler.php @@ -213,7 +213,7 @@ public static function start( $mutation = EngineData::mutate( $parent_job_id, static function ( array $current ) use ( $total, $chunk_size, $context, $completion_strategy, $extra, $hook, $worklist_checksum ): ?array { - if ( self::STORAGE_VERSION === (int) ( $current['batch_storage_version'] ?? 0 ) && is_array( $current['batch_state'] ?? null ) ) { + if ( is_array( $current['batch_state'] ?? null ) ) { $current_checksum = (string) ( $current['batch_state']['checksum'] ?? '' ); if ( ! hash_equals( $worklist_checksum, $current_checksum ) ) { return null; @@ -248,8 +248,7 @@ static function ( array $current ) use ( $total, $chunk_size, $context, $complet ); if ( empty( $mutation['success'] ) ) { $latest = EngineData::retrieve( $parent_job_id ); - $adopted_elsewhere = self::STORAGE_VERSION === (int) ( $latest['batch_storage_version'] ?? 0 ) - && hash_equals( $worklist_checksum, (string) ( $latest['batch_state']['checksum'] ?? '' ) ); + $adopted_elsewhere = hash_equals( $worklist_checksum, (string) ( $latest['batch_state']['checksum'] ?? '' ) ); if ( ! $adopted_elsewhere && ! empty( $insert['created'] ) ) { if ( self::discardOwnedWorklist( $repository, $parent_job_id, (string) $insert['ownership_token'], $context ) ) { $repository->delete_owned_batch( $parent_job_id, (string) $insert['ownership_token'] ); @@ -347,9 +346,8 @@ private static function discardStartItems( array $items, array $cleanup_contexts * Delegates per-item child creation to the supplied callback. Handles * cancellation, offset bookkeeping, and chunk-rescheduling uniformly. * - * V2 callbacks receive `(item, extra, parent_job_id, item_index, - * payload_checksum)`; legacy callbacks retain the original three arguments. - * The callback returns the + * Callbacks receive `(item, extra, parent_job_id, item_index, + * payload_checksum)`. The callback returns the * created child id (or any truthy value) on success, falsy on failure. * Falsy returns count toward `batch_scheduled` only when truthy. * @@ -357,7 +355,7 @@ private static function discardStartItems( array $items, array $cleanup_contexts * that as a fatal protocol error and complete the parent as failed). * * @param int $parent_job_id Parent job ID. - * @param callable $createItem fn(array $item, array $extra, int $parent_job_id): mixed + * @param callable $createItem fn(array $item, array $extra, int $parent_job_id, int $item_index, string $payload_checksum): mixed * @param int|null $expected_offset Offset key carried by the scheduler action. * @return array{ * scheduled:int, @@ -367,8 +365,8 @@ private static function discardStartItems( array $items, array $cleanup_contexts * cancelled:bool, * missing:bool, * duplicate:bool, - * schedule_failed?:bool, - * item_failed?:bool + * schedule_failed:bool, + * item_failed:bool * } Chunk result. `missing` is true only when the batch_state key * has been lost; consumer must fail the parent in that case. * `item_failed` is true when an item exhausted its attempt budget. @@ -378,21 +376,8 @@ public static function processChunk( int $parent_job_id, callable $createItem, ? // table so stale persistent-cache state cannot hide a committed worklist. $parent_job = ( new Jobs() )->get_job( $parent_job_id ); $parent_engine = is_array( $parent_job['engine_data'] ?? null ) ? $parent_job['engine_data'] : array(); - if ( self::STORAGE_VERSION === (int) ( $parent_engine['batch_storage_version'] ?? 0 ) ) { - return self::processV2Chunk( $parent_job_id, $createItem, $expected_offset, $parent_engine ); - } - - $result = self::processLegacyChunk( $parent_job_id, $createItem, $expected_offset, $parent_engine ); - if ( ! isset( $result['item_failed'] ) ) { - $result['item_failed'] = false; - } - return $result; - } - - /** Process a durable v2 worklist chunk. */ - private static function processV2Chunk( int $parent_job_id, callable $createItem, ?int $expected_offset, array $parent_engine ): array { - $state = is_array( $parent_engine['batch_state'] ?? null ) ? $parent_engine['batch_state'] : null; - $total = (int) ( $parent_engine['batch_total'] ?? 0 ); + $state = is_array( $parent_engine['batch_state'] ?? null ) ? $parent_engine['batch_state'] : null; + $total = (int) ( $parent_engine['batch_total'] ?? 0 ); if ( is_array( $state ) && ! empty( $state['worklist_complete'] ) ) { return self::chunkResult( 0, @@ -560,7 +545,11 @@ private static function processV2Chunk( int $parent_job_id, callable $createItem return self::chunkResult( $scheduled, $new_offset, $total, $more, false, false, false, $failed, $item_failed ); } - /** Build a stable chunk result for both consumers. */ + /** + * Build a stable chunk result for both consumers. + * + * @return array{scheduled:int, offset:int, total:int, more:bool, cancelled:bool, missing:bool, duplicate:bool, schedule_failed:bool, item_failed:bool} + */ private static function chunkResult( int $scheduled, int $offset, int $total, bool $more, bool $cancelled = false, bool $missing = false, bool $duplicate = false, bool $schedule_failed = false, bool $item_failed = false ): array { return array( 'scheduled' => $scheduled, @@ -785,9 +774,8 @@ public static function finalize( int $parent_job_id ): bool { return false; } $repository = new BatchItems(); - $is_v2 = self::STORAGE_VERSION === (int) ( $current['batch_storage_version'] ?? 0 ); $state = is_array( $current['batch_state'] ?? null ) ? $current['batch_state'] : null; - if ( ! $is_v2 || ! is_array( $state ) || empty( $state['worklist_complete'] ) ) { + if ( ! is_array( $state ) || empty( $state['worklist_complete'] ) ) { if ( ! self::discardV2Outstanding( $repository, $parent_job_id, (string) ( $current['batch_context'] ?? '' ) ) ) { self::scheduleFinalizeRetry( $current, $parent_job_id ); return false; @@ -798,9 +786,6 @@ public static function finalize( int $parent_job_id ): bool { self::scheduleFinalizeRetry( $current, $parent_job_id ); return false; } - if ( ! $is_v2 ) { - return true; - } $result = ( new Jobs() )->remove_engine_data_key( $parent_job_id, 'batch_state' ); $finalized = ! empty( $result['updated'] ); if ( ! $finalized && ! empty( $result['retryable'] ) ) { @@ -825,270 +810,6 @@ public static function scheduleFinalizeRetry( array $engine, int $parent_job_id return self::scheduleChunk( $hook, $parent_job_id, (int) ( $state['offset'] ?? $engine['batch_offset'] ?? 0 ), time() + 60 ); } - /** Existing engine_data worklist processor for persisted v1 batches. */ - private static function processLegacyChunk( int $parent_job_id, callable $createItem, ?int $expected_offset, array $parent_engine ): array { - $batch_state = $parent_engine['batch_state'] ?? null; - - if ( ! is_array( $batch_state ) ) { - if ( null !== $expected_offset && ! empty( $parent_engine['batch'] ) ) { - $total = (int) ( $parent_engine['batch_total'] ?? 0 ); - $offset = (int) ( $parent_engine['batch_offset'] ?? $total ); - - return array( - 'scheduled' => 0, - 'offset' => $offset, - 'total' => $total, - 'more' => false, - 'cancelled' => ! empty( $parent_engine['cancelled'] ), - 'missing' => false, - 'duplicate' => true, - ); - } - - return array( - 'scheduled' => 0, - 'offset' => 0, - 'total' => 0, - 'more' => false, - 'cancelled' => false, - 'missing' => true, - 'duplicate' => false, - ); - } - - $context = $parent_engine['batch_context'] ?? ''; - $chunk_size = self::chunkSize( $context ); - $delay = self::chunkDelay( $context ); - - // Cancellation without an in-flight owner may discard from the durable - // offset. An in-flight owner is responsible for its own chunk boundary. - if ( ! empty( $parent_engine['cancelled'] ) ) { - $duplicate = is_array( $batch_state['in_flight'] ?? null ); - if ( ! $duplicate && ! isset( $batch_state['discarded_from'] ) ) { - $discard_from = (int) ( $batch_state['offset'] ?? 0 ); - $remaining = array_slice( is_array( $batch_state['items'] ?? null ) ? $batch_state['items'] : array(), $discard_from ); - $remaining_cleanup = array_slice( is_array( $batch_state['cleanup_contexts'] ?? null ) ? $batch_state['cleanup_contexts'] : array(), $discard_from ); - if ( $remaining ) { - do_action( 'datamachine_batch_items_discarded', $remaining, $parent_job_id, (string) $context, $remaining_cleanup ); - } - } - - if ( ! $duplicate ) { - EngineData::mutate( - $parent_job_id, - static function ( array $current ): array { - if ( ! is_array( $current['batch_state']['in_flight'] ?? null ) ) { - unset( $current['batch_state'] ); - } - return $current; - }, - 'batch_cancelled_cleanup' - ); - } - - return array( - 'scheduled' => 0, - 'offset' => (int) ( $batch_state['offset'] ?? 0 ), - 'total' => (int) ( $batch_state['total'] ?? 0 ), - 'more' => false, - 'cancelled' => true, - 'missing' => false, - 'duplicate' => $duplicate, - ); - } - - if ( null !== $expected_offset ) { - $claim_error = null; - $claim = EngineData::mutate( - $parent_job_id, - static function ( array $current ) use ( $expected_offset, $chunk_size, &$claim_error ): ?array { - $current_state = $current['batch_state'] ?? null; - if ( ! is_array( $current_state ) ) { - $claim_error = 'missing'; - return null; - } - - if ( ! empty( $current['cancelled'] ) ) { - $claim_error = 'cancelled'; - return null; - } - - $current_offset = (int) ( $current_state['offset'] ?? 0 ); - if ( $current_offset !== $expected_offset ) { - $claim_error = 'stale_offset'; - return null; - } - - $claims = is_array( $current_state['claims'] ?? null ) ? $current_state['claims'] : array(); - if ( isset( $claims[ (string) $expected_offset ] ) ) { - $claim_error = 'already_claimed'; - return null; - } - - $current_state['claims'] = $claims; - $current_state['claims'][ (string) $expected_offset ] = current_time( 'mysql' ); - $current_state['in_flight'] = array( - 'offset' => $expected_offset, - 'end' => min( $expected_offset + $chunk_size, (int) ( $current_state['total'] ?? 0 ) ), - ); - $current['batch_state'] = $current_state; - - return $current; - }, - 'batch_chunk_claim' - ); - - if ( empty( $claim['success'] ) ) { - $latest = $claim['snapshot']; - $latest_state = is_array( $latest['batch_state'] ?? null ) ? $latest['batch_state'] : array(); - - return array( - 'scheduled' => 0, - 'offset' => (int) ( $latest_state['offset'] ?? ( $latest['batch_offset'] ?? 0 ) ), - 'total' => (int) ( $latest_state['total'] ?? ( $latest['batch_total'] ?? 0 ) ), - 'more' => ! empty( $latest['batch_state'] ), - 'cancelled' => 'cancelled' === $claim_error || ! empty( $latest['cancelled'] ), - 'missing' => 'missing' === $claim_error && empty( $latest['batch'] ), - 'duplicate' => in_array( $claim_error, array( 'already_claimed', 'stale_offset', 'missing' ), true ), - ); - } - - $parent_engine = $claim['snapshot']; - $batch_state = is_array( $parent_engine['batch_state'] ?? null ) ? $parent_engine['batch_state'] : $batch_state; - } - - $total = (int) ( $batch_state['total'] ?? 0 ); - $offset = (int) ( $batch_state['offset'] ?? 0 ); - $items = is_array( $batch_state['items'] ?? null ) ? $batch_state['items'] : array(); - $cleanup_contexts = is_array( $batch_state['cleanup_contexts'] ?? null ) ? $batch_state['cleanup_contexts'] : array(); - $extra = is_array( $batch_state['extra'] ?? null ) ? $batch_state['extra'] : array(); - $hook = (string) ( $batch_state['hook'] ?? '' ); - - $chunk = array_slice( $items, $offset, $chunk_size ); - $scheduled = 0; - $processed = 0; - $cancelled = false; - $schedule_failed = false; - - foreach ( $chunk as $index => $item ) { - $latest = EngineData::retrieve( $parent_job_id ); - if ( ! empty( $latest['cancelled'] ) ) { - $cancelled = true; - $remaining = array_slice( $chunk, $index ); - $remaining_cleanup = array_slice( $cleanup_contexts, $offset + $index, count( $remaining ) ); - if ( $remaining ) { - do_action( 'datamachine_batch_items_discarded', $remaining, $parent_job_id, (string) $context, $remaining_cleanup ); - } - break; - } - - $cleanup_context = $cleanup_contexts[ $offset + $index ] ?? array(); - $hydration = DataPacketStore::hydrate_packet_collections_with_status( $item ); - $item = $hydration['value']; - if ( empty( $hydration['success'] ) ) { - do_action( 'datamachine_batch_items_discarded', array( $item ), $parent_job_id, (string) $context, array( $cleanup_context ) ); - ++$processed; - continue; - } - $result = $createItem( $item, $extra, $parent_job_id ); - if ( $result ) { - ++$scheduled; - } else { - do_action( 'datamachine_batch_items_discarded', array( $item ), $parent_job_id, (string) $context, array( $cleanup_context ) ); - } - ++$processed; - } - - $new_offset = $cancelled ? $offset + $processed : $offset + count( $chunk ); - - $more = ! $cancelled && $new_offset < $total; - - EngineData::mutate( - $parent_job_id, - static function ( array $current ) use ( $scheduled, $new_offset, $total, $more, $expected_offset, &$cancelled ): array { - $current['batch_scheduled'] = ( $current['batch_scheduled'] ?? 0 ) + $scheduled; - $current['batch_offset'] = min( $new_offset, $total ); - - if ( ! empty( $current['cancelled'] ) ) { - $cancelled = true; - unset( $current['batch_state'] ); - } elseif ( $more ) { - if ( is_array( $current['batch_state'] ?? null ) ) { - $current['batch_state']['offset'] = $new_offset; - unset( $current['batch_state']['in_flight'] ); - if ( null !== $expected_offset && isset( $current['batch_state']['claims'][ (string) $expected_offset ] ) ) { - unset( $current['batch_state']['claims'][ (string) $expected_offset ] ); - } - } - } else { - unset( $current['batch_state'] ); - } - - return $current; - }, - 'batch_chunk_advance' - ); - if ( $cancelled ) { - $more = false; - } - - if ( $more ) { - try { - $action_id = as_schedule_single_action( - time() + $delay, - $hook, - array( - 'parent_job_id' => $parent_job_id, - 'offset' => $new_offset, - ), - GroupRegistrar::GROUP - ); - } catch ( \Throwable $exception ) { - $action_id = 0; - do_action( - 'datamachine_log', - 'error', - 'Batch scheduler failed to schedule next chunk', - array( - 'parent_job_id' => $parent_job_id, - 'offset' => $new_offset, - 'exception' => $exception->getMessage(), - ) - ); - } - - if ( ! $action_id ) { - $remaining = array_slice( $items, $new_offset ); - $remaining_cleanup = array_slice( $cleanup_contexts, $new_offset ); - if ( $remaining ) { - do_action( 'datamachine_batch_items_discarded', $remaining, $parent_job_id, (string) $context, $remaining_cleanup ); - } - EngineData::mutate( - $parent_job_id, - static function ( array $current ): array { - unset( $current['batch_state'] ); - $current['batch_schedule_failed'] = true; - return $current; - }, - 'batch_chunk_schedule_failure' - ); - $more = false; - $schedule_failed = true; - } - } - - return array( - 'scheduled' => $scheduled, - 'offset' => min( $new_offset, $total ), - 'total' => $total, - 'more' => $more, - 'cancelled' => $cancelled, - 'missing' => false, - 'duplicate' => false, - 'schedule_failed' => $schedule_failed, - ); - } - /** * Mark a batch parent as cancelled. * @@ -1100,80 +821,36 @@ static function ( array $current ): array { */ public static function cancel( int $parent_job_id ): bool { $current = EngineData::retrieve( $parent_job_id ); - if ( self::STORAGE_VERSION === (int) ( $current['batch_storage_version'] ?? 0 ) ) { - if ( empty( $current['batch'] ) ) { - return false; - } - $mutation = EngineData::mutate( - $parent_job_id, - static function ( array $engine ): ?array { - if ( empty( $engine['batch'] ) ) { - return null; - } - $engine['cancelled'] = true; - $engine['cancelled_at'] = current_time( 'mysql' ); - return $engine; - }, - 'batch_v2_cancel' - ); - if ( empty( $mutation['success'] ) ) { - return false; - } - $repository = new BatchItems(); - $context = (string) ( $current['batch_context'] ?? '' ); - if ( ! self::requestV2Cancellation( $repository, $parent_job_id, $context ) ) { - return false; - } - if ( null === $repository->first_outstanding_index( $parent_job_id ) ) { - $completed = $repository->count_completed( $parent_job_id ); - $offset = (int) ( $current['batch_state']['offset'] ?? 0 ); - if ( ! self::finishV2State( $parent_job_id, $completed, $offset, true ) ) { - return false; - } - } - return true; + if ( empty( $current['batch'] ) ) { + return false; } - - $remaining = array(); - $remaining_cleanup = array(); - $context = ''; - $mutation = EngineData::mutate( + $mutation = EngineData::mutate( $parent_job_id, - static function ( array $current ) use ( &$remaining, &$remaining_cleanup, &$context ): ?array { - $remaining = array(); - $remaining_cleanup = array(); - if ( empty( $current['batch'] ) ) { + static function ( array $engine ): ?array { + if ( empty( $engine['batch'] ) ) { return null; } - - $current['cancelled'] = true; - $current['cancelled_at'] = current_time( 'mysql' ); - $context = (string) ( $current['batch_context'] ?? '' ); - $state = is_array( $current['batch_state'] ?? null ) ? $current['batch_state'] : array(); - if ( $state && ! isset( $state['discarded_from'] ) ) { - $in_flight = is_array( $state['in_flight'] ?? null ) ? $state['in_flight'] : array(); - $discard_from = $in_flight - ? (int) ( $in_flight['end'] ?? $state['offset'] ?? 0 ) - : (int) ( $state['offset'] ?? 0 ); - $remaining = array_slice( is_array( $state['items'] ?? null ) ? $state['items'] : array(), $discard_from ); - $remaining_cleanup = array_slice( is_array( $state['cleanup_contexts'] ?? null ) ? $state['cleanup_contexts'] : array(), $discard_from ); - $state['discarded_from'] = $discard_from; - $current['batch_state'] = $state; - } - - return $current; + $engine['cancelled'] = true; + $engine['cancelled_at'] = current_time( 'mysql' ); + return $engine; }, - 'batch_cancel' + 'batch_v2_cancel' ); - if ( empty( $mutation['success'] ) ) { return false; } - - if ( $remaining ) { - do_action( 'datamachine_batch_items_discarded', $remaining, $parent_job_id, $context, $remaining_cleanup ); + $repository = new BatchItems(); + $context = (string) ( $current['batch_context'] ?? '' ); + if ( ! self::requestV2Cancellation( $repository, $parent_job_id, $context ) ) { + return false; + } + if ( null === $repository->first_outstanding_index( $parent_job_id ) ) { + $completed = $repository->count_completed( $parent_job_id ); + $offset = (int) ( $current['batch_state']['offset'] ?? 0 ); + if ( ! self::finishV2State( $parent_job_id, $completed, $offset, true ) ) { + return false; + } } - return true; } } diff --git a/plugins/data-machine/inc/Core/ActionScheduler/PathlessBatchRecovery.php b/plugins/data-machine/inc/Core/ActionScheduler/PathlessBatchRecovery.php index 6716c49143..d288d09f91 100644 --- a/plugins/data-machine/inc/Core/ActionScheduler/PathlessBatchRecovery.php +++ b/plugins/data-machine/inc/Core/ActionScheduler/PathlessBatchRecovery.php @@ -20,9 +20,9 @@ class PathlessBatchRecovery { private const CLAIM_TTL = 300; private const CHILD_QUERY_LIMIT = 100; - /** Whether a v2 batch still has work that can be requeued. */ + /** Whether a batch still has work that can be requeued. */ public static function isRecoverable( array $engine_data ): bool { - return BatchScheduler::STORAGE_VERSION === (int) ( $engine_data['batch_storage_version'] ?? 0 ) + return ! empty( $engine_data['batch'] ) && empty( $engine_data['batch_state']['worklist_complete'] ); } diff --git a/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItems.php b/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItems.php index 7c99616a5c..a4de8d4315 100644 --- a/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItems.php +++ b/plugins/data-machine/inc/Core/Database/ProcessedItems/ProcessedItems.php @@ -596,20 +596,6 @@ public function add_processed_item( string $flow_step_id, string $source_type, s return true; } - /** - * Atomically claim a source item for in-flight processing. - * - * @param string $flow_step_id Flow step ID. - * @param string $source_type Source type. - * @param string $item_identifier Unique item identifier. - * @param int $job_id Job creating the claim. - * @param int $ttl_seconds Claim TTL in seconds. - * @return bool True when this caller owns the claim; false when already processed or actively claimed. - */ - public function claim_item( string $flow_step_id, string $source_type, string $item_identifier, int $job_id, int $ttl_seconds = self::DEFAULT_CLAIM_TTL_SECONDS ): bool { - return false !== $this->claim_item_owned( $flow_step_id, $source_type, $item_identifier, $job_id, $ttl_seconds ); - } - /** * Atomically claim a source identity and return its ownership token. * @@ -806,43 +792,6 @@ public function renew_owned_claim_in_transaction( array $claim, int $job_id, int return false !== $updated; } - /** - * Complete a descriptor-less claim while the completing job still owns it. - * - * Reacquisition replaces job_id, so a stale legacy completion cannot mutate - * a token-owned replacement generation. - * - * @param string $flow_step_id Flow step identity scope. - * @param string $source_type Source type. - * @param string $item_identifier Unique item identifier. - * @param int $job_id Completing legacy job ID. - * @return int|false Number of completed claims, or false on error. - */ - public function complete_claim_for_job( string $flow_step_id, string $source_type, string $item_identifier, int $job_id ): int|false { - if ( 1 > $job_id ) { - return false; - } - - $now = current_time( 'mysql', true ); - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Table identifier uses %i; all values use typed placeholders. - $query = $this->wpdb->prepare( - 'UPDATE %i SET status = %s, processed_timestamp = %s, claim_expires_at = NULL, claim_token = NULL WHERE flow_step_id = %s AND source_type = %s AND item_identifier = %s AND job_id = %d AND status = %s', - $this->table_name, - self::STATUS_PROCESSED, - $now, - $flow_step_id, - $source_type, - $item_identifier, - $job_id, - self::STATUS_CLAIMED - ); - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared -- Dynamic identifier is prepared with %i; every value uses a typed placeholder. - $result = $this->wpdb->query( $query ); - // phpcs:enable WordPress.DB.PreparedSQL.NotPrepared - return false === $result ? false : (int) $result; - } - /** * Atomically run completion work and transition an owned claim. * @@ -1084,10 +1033,7 @@ public function release_claims_for_job( int $job_id ): int|false { } /** - * Delete expired legacy claims that have no ownership generation. - * - * Token-owned rows remain available for either completion by the current - * generation or atomic takeover by a replacement generation. + * Delete every in-flight claim whose claim_expires_at has passed. * * @return int|false Number of rows deleted, or false on error. */ @@ -1098,7 +1044,7 @@ public function delete_expired_claims(): int|false { // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared -- Prepared with %i table placeholder. $result = $this->wpdb->query( $this->wpdb->prepare( - 'DELETE FROM %i WHERE status = %s AND claim_token IS NULL AND claim_expires_at IS NOT NULL AND claim_expires_at <= %s', + 'DELETE FROM %i WHERE status = %s AND claim_expires_at IS NOT NULL AND claim_expires_at <= %s', $this->table_name, self::STATUS_CLAIMED, $now diff --git a/plugins/data-machine/inc/Engine/AI/System/Tasks/Retention/RetentionCleanup.php b/plugins/data-machine/inc/Engine/AI/System/Tasks/Retention/RetentionCleanup.php index c6678aeef4..13c589b7b4 100644 --- a/plugins/data-machine/inc/Engine/AI/System/Tasks/Retention/RetentionCleanup.php +++ b/plugins/data-machine/inc/Engine/AI/System/Tasks/Retention/RetentionCleanup.php @@ -1076,8 +1076,8 @@ public static function countProcessedItems(): int { public static function cleanupProcessedItems(): array { $max_age_days = self::processedItemsMaxAgeDays(); - $deleted = ( new ProcessedItems() )->delete_old_processed_items( $max_age_days ); - $deleted = false !== $deleted ? (int) $deleted : 0; + $processed = new ProcessedItems(); + $deleted = (int) $processed->delete_old_processed_items( $max_age_days ) + (int) $processed->delete_expired_claims(); if ( $deleted > 0 ) { self::log( diff --git a/plugins/data-machine/inc/Engine/Actions/Handlers/StepLifecycleHandler.php b/plugins/data-machine/inc/Engine/Actions/Handlers/StepLifecycleHandler.php index 72b9507a50..696c77548d 100644 --- a/plugins/data-machine/inc/Engine/Actions/Handlers/StepLifecycleHandler.php +++ b/plugins/data-machine/inc/Engine/Actions/Handlers/StepLifecycleHandler.php @@ -8,8 +8,6 @@ namespace DataMachine\Engine\Actions\Handlers; -use DataMachine\Core\ActionScheduler\BatchScheduler; -use DataMachine\Core\Database\ProcessedItems\FanoutClaimOwnership; use DataMachine\Core\Database\ProcessedItems\ProcessedItems; use DataMachine\Core\Database\TransactionScope; use DataMachine\Core\DataPacketStore; @@ -443,13 +441,6 @@ public static function renewParkedClaims( int $job_id, int $recovery_generation /** Remove claims transferred to fanout packets from parent terminal ownership. */ public static function transferClaimsToFanout( int $job_id, array $packets, int $recovery_generation = 0, string $recovery_claim_token = '' ): array { - $packets = self::bindOwnedClaimsToPackets( $job_id, $packets ); - if ( false === $packets ) { - return array( - 'success' => false, - 'stale' => false, - ); - } $claims = array(); $seen = array(); foreach ( $packets as $packet ) { @@ -512,73 +503,6 @@ public static function transferClaimsToFanout( int $job_id, array $packets, int return $result; } - /** Bind descriptor-less legacy claims only through an unambiguous exact packet identity. */ - private static function bindOwnedClaimsToPackets( int $job_id, array $packets ): array|false { - $needs_binding = false; - foreach ( $packets as $packet ) { - $metadata = is_array( $packet['metadata'] ?? null ) ? $packet['metadata'] : array(); - if ( ! ProcessedItems::has_claim_metadata( $metadata ) ) { - $needs_binding = true; - break; - } - } - if ( ! $needs_binding ) { - return $packets; - } - - $owned = ( new FanoutClaimOwnership() )->active_claims_for_job( $job_id ); - $owned = array_merge( $owned, array_values( ProcessedItems::disposition_claims( \datamachine_get_engine_data( $job_id ) ) ) ); - $index = array(); - foreach ( $owned as $claim ) { - $key = (string) $claim['source_type'] . "\0" . (string) $claim['item_identifier']; - $index[ $key ][ $claim['disposition_id'] ] = $claim; - } - - foreach ( $packets as &$packet ) { - $metadata = is_array( $packet['metadata'] ?? null ) ? $packet['metadata'] : array(); - if ( ProcessedItems::has_claim_metadata( $metadata ) ) { - continue; - } - - $source_types = array_filter( - array( - trim( (string) ( $metadata['source_type'] ?? '' ) ), - trim( (string) ( $metadata['_engine_data']['source_type'] ?? '' ) ), - ), - static fn( string $source_type ): bool => '' !== $source_type - ); - $source_types = array_values( array_unique( $source_types ) ); - $identifiers = array_filter( - array( - trim( (string) ( $metadata['item_identifier'] ?? '' ) ), - trim( (string) ( $metadata['source_item_id'] ?? '' ) ), - trim( (string) ( $metadata['_engine_data']['item_identifier'] ?? '' ) ), - ), - static fn( string $identifier ): bool => '' !== $identifier - ); - $identifiers = array_values( array_unique( $identifiers ) ); - if ( count( $source_types ) > 1 || count( $identifiers ) > 1 ) { - return false; - } - if ( 1 !== count( $source_types ) || 1 !== count( $identifiers ) ) { - continue; - } - - $matches = array_values( $index[ $source_types[0] . "\0" . $identifiers[0] ] ?? array() ); - if ( count( $matches ) > 1 ) { - return false; - } - if ( empty( $matches ) ) { - continue; - } - $packet['metadata'][ ProcessedItems::CLAIM_METADATA_KEY ] = $matches[0]; - $packet['metadata'][ ProcessedItems::DISPOSITION_ID_METADATA_KEY ] = $matches[0]['disposition_id']; - } - unset( $packet ); - - return $packets; - } - /** Mark a prepared transfer adopted only after BatchItems and batch state are durable. */ public static function adoptPreparedFanoutTransfer( int $job_id, string $transfer_id, int $recovery_generation = 0, string $recovery_claim_token = '' ): bool { return ! empty( self::mutateFanoutTransfer( $job_id, $transfer_id, 'adopt', $recovery_generation, $recovery_claim_token )['success'] ); @@ -813,7 +737,7 @@ public static function filterTerminalEngineData( array $engine, int $job_id, str * @param int $job_id Completed job ID. * @param array|null $engine_data Optional engine data snapshot. * @param bool $within_transaction Whether the caller owns the terminal transaction. - * @return bool Whether all owned descriptor and legacy claims completed. + * @return bool Whether all owned descriptor claims completed. */ public static function handleCompleted( int $job_id, ?array $engine_data = null, bool $within_transaction = false ): bool { $engine_data = is_array( $engine_data ) ? $engine_data : \datamachine_get_engine_data( $job_id ); @@ -829,29 +753,6 @@ public static function handleCompleted( int $job_id, ?array $engine_data = null, } } - $item_identifier = $engine_data['item_identifier'] ?? null; - $source_type = $engine_data['source_type'] ?? null; - if ( empty( $item_identifier ) || empty( $source_type ) ) { - return self::recordCompletedMetrics( $job_id, $completed, $within_transaction ); - } - - $source_flow_step_id = self::resolveSourceIngestionFlowStepId( $engine_data ); - if ( empty( $source_flow_step_id ) ) { - return self::recordCompletedMetrics( $job_id, $completed, $within_transaction ); - } - - $legacy_completed = ( new ProcessedItems() )->complete_claim_for_job( - $source_flow_step_id, - (string) $source_type, - (string) $item_identifier, - $job_id - ); - if ( false === $legacy_completed ) { - unset( self::$pending_processed_metrics[ $job_id ] ); - return false; - } - $completed += $legacy_completed; - return self::recordCompletedMetrics( $job_id, $completed, $within_transaction ); } @@ -860,25 +761,24 @@ public static function handleCompleted( int $job_id, ?array $engine_data = null, * * @param int $job_id Failed job ID. * @param array|null $engine_data Optional engine data snapshot. - * @return bool Whether every descriptor and legacy claim was released. + * @return bool Whether every descriptor claim was released. */ public static function handleFailed( int $job_id, ?array $engine_data = null ): bool { $engine_data = is_array( $engine_data ) ? $engine_data : \datamachine_get_engine_data( $job_id ); $claims = self::claimsFromEngine( $engine_data ); $processed = new ProcessedItems(); - if ( ! empty( $claims ) ) { - foreach ( $claims as $claim ) { - if ( false === self::releaseClaim( $claim, $processed ) ) { - return false; - } + foreach ( $claims as $claim ) { + if ( false === self::releaseClaim( $claim, $processed ) ) { + return false; } } - if ( ! empty( $engine_data['batch'] ) && BatchScheduler::STORAGE_VERSION === (int) ( $engine_data['batch_storage_version'] ?? 0 ) ) { + if ( ! empty( $engine_data['batch'] ) ) { return true; } - // Pre-descriptor and partially migrated jobs still own claims by job_id. - // Reacquisition replaces job_id, so this cannot release a newer worker's row. + // A fetch can fail after claiming an item but before its descriptor + // reaches engine data. Release the job's remaining claims by job_id; + // reacquisition replaces job_id, so this never touches a newer owner's row. return false !== $processed->release_claims_for_job( $job_id ); } @@ -1160,32 +1060,6 @@ private static function normalizeClaim( mixed $claim ): ?array { return $claim; } - /** - * Resolve the source-ingestion step ID from a job engine snapshot. - * - * @param array $engine_data Job engine data. - * @return string|null Source ingestion flow step ID, or null when unavailable. - */ - public static function resolveSourceIngestionFlowStepId( array $engine_data ): ?string { - $flow_config = $engine_data['flow_config'] ?? array(); - if ( ! is_array( $flow_config ) ) { - return null; - } - - foreach ( $flow_config as $step_id => $config ) { - if ( ! is_array( $config ) ) { - continue; - } - - $step_type = $config['step_type'] ?? ''; - if ( self::isSourceIngestionStep( (string) $step_type ) ) { - return (string) $step_id; - } - } - - return null; - } - /** * Determine whether a step owns source-ingestion dedupe lifecycle behavior. * diff --git a/plugins/data-machine/tests/Unit/Abilities/Engine/PipelineBatchSchedulerTest.php b/plugins/data-machine/tests/Unit/Abilities/Engine/PipelineBatchSchedulerTest.php index a4c3ef572e..d09b926d2d 100644 --- a/plugins/data-machine/tests/Unit/Abilities/Engine/PipelineBatchSchedulerTest.php +++ b/plugins/data-machine/tests/Unit/Abilities/Engine/PipelineBatchSchedulerTest.php @@ -538,120 +538,6 @@ public function test_process_chunk_keeps_distinct_packet_claims_with_distinct_ch } } - public function test_scheduled_fanout_reconstructs_exact_legacy_claims_and_disposes_idempotently(): void { - $parent_id = $this->create_parent_job(); - $engine = $this->make_engine_snapshot( $parent_id ); - $source_step_id = 'source-step'; - $engine['flow_config'] = array( - $source_step_id => array( - 'step_type' => 'event_import', - 'execution_order' => 0, - 'pipeline_id' => $this->test_pipeline_id, - ), - 'ai-step' => array( - 'step_type' => 'ai', - 'execution_order' => 1, - ), - ); - datamachine_set_engine_data( $parent_id, $engine ); - - $packets = array(); - $claims = array(); - foreach ( array( 'reject-id' => 'Reject Event', 'defer-id' => 'Defer Event' ) as $item_identifier => $title ) { - $claims[ $item_identifier ] = $this->claim_for_parent( $parent_id, $item_identifier ); - $packet = $this->make_data_packet( $title ); - $packet['metadata']['source_item_id'] = $item_identifier; - $packet['metadata']['_engine_data'] = array( - 'item_identifier' => $item_identifier, - 'source_type' => 'source_api', - ); - $packets[] = $packet; - } - - $route = new \ReflectionMethod( ExecuteStepAbility::class, 'routeAfterExecution' ); - $result = $route->invoke( - new ExecuteStepAbility(), - $parent_id, - $source_step_id, - $this->test_flow_id, - $engine['flow_config'][ $source_step_id ], - 'event_import', - '', - $packets, - array( - 'job_id' => $parent_id, - 'engine' => new EngineData( $engine, $parent_id ), - ), - true, - null - ); - $this->assertTrue( $result['success'] ); - $this->assertSame( 'batch_scheduled', $result['outcome'] ); - - global $wpdb; - $worklist = $wpdb->get_results( - $wpdb->prepare( 'SELECT payload FROM %i WHERE batch_job_id = %d ORDER BY item_index', $wpdb->prefix . 'datamachine_batch_items', $parent_id ), - ARRAY_A - ); - $this->assertCount( 2, $worklist ); - foreach ( $worklist as $index => $row ) { - $stored = json_decode( $row['payload'], true ); - $this->assertArrayHasKey( ProcessedItems::CLAIM_METADATA_KEY, $stored['metadata'] ); - $this->assertArrayHasKey( ProcessedItems::DISPOSITION_ID_METADATA_KEY, $stored['metadata'] ); - $item_identifier = 'Reject Event' === $stored['data']['title'] ? 'reject-id' : 'defer-id'; - $this->assertTrue( ( new ProcessedItems() )->owns_active_claim( $claims[ $item_identifier ], $parent_id ), 'Worklist adoption must precede child ownership transfer at index ' . $index ); - } - - wp_cache_delete( $parent_id, 'datamachine_engine_data' ); - $this->assertArrayHasKey( 'batch_state', datamachine_get_engine_data( $parent_id ) ); - - $scheduler = new PipelineBatchScheduler(); - $scheduler->processChunk( $parent_id, 0 ); - - $children = $wpdb->get_results( - $wpdb->prepare( 'SELECT job_id, label FROM %i WHERE parent_job_id = %d', $wpdb->prefix . 'datamachine_jobs', $parent_id ), - ARRAY_A - ); - $this->assertCount( 2, $children ); - $children = array_column( $children, 'job_id', 'label' ); - $tool = new FetchItemDispositionTool(); - $cases = array( - 'Reject Event' => array( 'reject-id', 'reject_source' ), - 'Defer Event' => array( 'defer-id', 'defer_item' ), - ); - foreach ( $cases as $label => $case ) { - list( $item_identifier, $disposition ) = $case; - $child_id = (int) $children[ $label ]; - $claim = $claims[ $item_identifier ]; - $this->assertTrue( ( new ProcessedItems() )->owns_active_claim( $claim, $child_id ) ); - - $params = array( - 'job_id' => $child_id, - 'disposition_id' => $claim['disposition_id'], - 'reason' => 'production-shaped test', - ); - $first = $tool->handle_tool_call( $params, array( 'disposition' => $disposition ) ); - $second = $tool->handle_tool_call( $params, array( 'disposition' => $disposition ) ); - $this->assertTrue( $first['success'] ); - $this->assertSame( $claim['disposition_id'], $first['disposition_id'] ); - $this->assertTrue( $second['success'] ); - $this->assertTrue( $second['already_dispositioned'] ); - - $result_packet = array( - 'metadata' => array( - ProcessedItems::CLAIM_METADATA_KEY => $claim, - ProcessedItems::DISPOSITION_ID_METADATA_KEY => $claim['disposition_id'], - 'packet_disposition' => $disposition, - ), - ); - $reconciled = StepLifecycleHandler::reconcileStepOutput( $child_id, array( 'step_type' => 'ai' ), array( $result_packet ), true ); - $replayed = StepLifecycleHandler::reconcileStepOutput( $child_id, array( 'step_type' => 'ai' ), array( $result_packet ), true ); - $this->assertTrue( $reconciled['success'] ); - $this->assertTrue( $replayed['success'] ); - $this->assertFalse( ( new ProcessedItems() )->has_active_claim( $claim['identity_scope'], $claim['source_type'], $claim['item_identifier'] ) ); - } - } - public function test_scheduled_fanout_reconciles_handler_identity_from_normalized_execution_parameters(): void { $parent_id = $this->create_parent_job(); $packets = array(); @@ -724,33 +610,6 @@ public function test_scheduled_fanout_reconciles_handler_identity_from_normalize } } - public function test_scheduled_fanout_does_not_bind_ambiguous_or_conflicting_identity(): void { - $parent_id = $this->create_parent_job(); - $processed = new ProcessedItems(); - $this->assertIsString( $processed->claim_item_owned( 'scope-a', 'source_api', 'shared-id', $parent_id ) ); - $this->assertIsString( $processed->claim_item_owned( 'scope-b', 'source_api', 'shared-id', $parent_id ) ); - - $ambiguous = $this->make_data_packet( 'Ambiguous Event' ); - $ambiguous['metadata']['source_item_id'] = 'shared-id'; - $conflicting = $this->make_data_packet( 'Conflicting Event' ); - $conflicting['metadata']['source_item_id'] = 'shared-id'; - $conflicting['metadata']['_engine_data']['item_identifier'] = 'different-id'; - - $transfer = StepLifecycleHandler::transferClaimsToFanout( $parent_id, array( $ambiguous, $conflicting ) ); - $this->assertFalse( $transfer['success'] ); - - $source_parent = $this->create_parent_job(); - $this->claim_for_parent( $source_parent, 'source-conflict' ); - $source_conflict = $this->make_data_packet( 'Source Conflict' ); - $source_conflict['metadata']['source_item_id'] = 'source-conflict'; - $source_conflict['metadata']['_engine_data'] = array( - 'item_identifier' => 'source-conflict', - 'source_type' => 'other-source', - ); - $source_transfer = StepLifecycleHandler::transferClaimsToFanout( $source_parent, array( $source_conflict ) ); - $this->assertFalse( $source_transfer['success'] ); - } - public function test_duplicate_exact_packet_identity_fails_before_batch_adoption(): void { $parent_id = $this->create_parent_job(); $engine = $this->make_engine_snapshot( $parent_id ); @@ -766,13 +625,10 @@ public function test_duplicate_exact_packet_identity_fails_before_batch_adoption ), ); datamachine_set_engine_data( $parent_id, $engine ); - $this->claim_for_parent( $parent_id, 'duplicate-id' ); + $claim = $this->claim_for_parent( $parent_id, 'duplicate-id' ); $packet = $this->make_data_packet( 'Duplicate Event' ); - $packet['metadata']['source_item_id'] = 'duplicate-id'; - $packet['metadata']['_engine_data'] = array( - 'item_identifier' => 'duplicate-id', - 'source_type' => 'source_api', - ); + $packet['metadata'][ ProcessedItems::CLAIM_METADATA_KEY ] = $claim; + $packet['metadata'][ ProcessedItems::DISPOSITION_ID_METADATA_KEY ] = $claim['disposition_id']; $route = new \ReflectionMethod( ExecuteStepAbility::class, 'routeAfterExecution' ); $result = $route->invoke( diff --git a/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php b/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php index 5a27b1da39..d0bb7bc14a 100644 --- a/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php +++ b/plugins/data-machine/tests/Unit/Core/Database/ProcessedItemsTest.php @@ -257,7 +257,7 @@ public function test_claim_item_converts_existing_processed_row_to_claim(): void $this->db->add_processed_item( $this->flow_step_id, $this->source_type, 'claim-existing', 10 ); - $this->assertTrue( $this->db->claim_item( $this->flow_step_id, $this->source_type, 'claim-existing', 11 ) ); + $this->assertIsString( $this->db->claim_item_owned( $this->flow_step_id, $this->source_type, 'claim-existing', 11 ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared $row = $wpdb->get_row( @@ -277,8 +277,37 @@ public function test_claim_item_converts_existing_processed_row_to_claim(): void } public function test_claim_item_does_not_steal_active_claim(): void { - $this->assertTrue( $this->db->claim_item( $this->flow_step_id, $this->source_type, 'active-claim', 10 ) ); - $this->assertFalse( $this->db->claim_item( $this->flow_step_id, $this->source_type, 'active-claim', 11 ) ); + $this->assertIsString( $this->db->claim_item_owned( $this->flow_step_id, $this->source_type, 'active-claim', 10 ) ); + $this->assertFalse( $this->db->claim_item_owned( $this->flow_step_id, $this->source_type, 'active-claim', 11 ) ); + } + + public function test_delete_expired_claims_sweeps_rows_regardless_of_claim_token(): void { + global $wpdb; + + $this->owned_claim( 'expired-owned', 12 ); + $this->owned_claim( 'expired-tokenless', 13 ); + $this->owned_claim( 'active-owned', 14 ); + foreach ( array( 'expired-owned' => 'token', 'expired-tokenless' => null ) as $identifier => $token ) { + $data = array( 'claim_expires_at' => gmdate( 'Y-m-d H:i:s', time() - 60 ) ); + if ( null === $token ) { + $data['claim_token'] = null; + } + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching + $wpdb->update( + $this->db->get_table_name(), + $data, + array( + 'flow_step_id' => $this->flow_step_id, + 'source_type' => $this->source_type, + 'item_identifier' => $identifier, + ) + ); + } + + $this->assertSame( 2, $this->db->delete_expired_claims() ); + $this->assertNull( $this->row( 'expired-owned' ) ); + $this->assertNull( $this->row( 'expired-tokenless' ) ); + $this->assertSame( ProcessedItems::STATUS_CLAIMED, $this->row( 'active-owned' )['status'] ); } public function test_deferral_count_persists_across_source_reappearance_and_same_job_is_idempotent(): void { diff --git a/plugins/data-machine/tests/Unit/Core/ExecutionContextSourceEligibilityTest.php b/plugins/data-machine/tests/Unit/Core/ExecutionContextSourceEligibilityTest.php index 5f734cb209..ff79bae425 100644 --- a/plugins/data-machine/tests/Unit/Core/ExecutionContextSourceEligibilityTest.php +++ b/plugins/data-machine/tests/Unit/Core/ExecutionContextSourceEligibilityTest.php @@ -38,8 +38,8 @@ public function test_classifies_mixed_ordered_states_without_lifecycle_writes(): $this->db->add_processed_item( $this->flow_step_id, $this->source_type, 'processed', 1 ); $this->db->add_processed_item( $this->flow_step_id, $this->source_type, 'reprocess', 1 ); - $this->db->claim_item( $this->flow_step_id, $this->source_type, 'active-claim', 2 ); - $this->db->claim_item( $this->flow_step_id, $this->source_type, 'expired-claim', 3 ); + $this->db->claim_item_owned( $this->flow_step_id, $this->source_type, 'active-claim', 2 ); + $this->db->claim_item_owned( $this->flow_step_id, $this->source_type, 'expired-claim', 3 ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->update( @@ -124,7 +124,7 @@ public function test_two_thousand_identifiers_use_bounded_chunked_reads(): void public function test_fetch_handler_uses_the_same_classification_decisions(): void { $this->db->add_processed_item( $this->flow_step_id, $this->source_type, 'processed', 1 ); - $this->db->claim_item( $this->flow_step_id, $this->source_type, 'claimed', 2 ); + $this->db->claim_item_owned( $this->flow_step_id, $this->source_type, 'claimed', 2 ); $items = array( array( 'title' => 'Fresh', 'metadata' => array( 'item_identifier' => 'fresh' ) ), @@ -162,7 +162,7 @@ public function test_fetch_handler_records_bounded_stage_diagnostics(): void { $this->assertIsInt( $job_id ); $this->db->add_processed_item( $this->flow_step_id, $this->source_type, 'processed', 1 ); - $this->db->claim_item( $this->flow_step_id, $this->source_type, 'claimed', 2 ); + $this->db->claim_item_owned( $this->flow_step_id, $this->source_type, 'claimed', 2 ); $items = array( array( 'title' => 'Fresh one', 'metadata' => array( 'item_identifier' => 'fresh-1' ) ), diff --git a/plugins/data-machine/tests/Unit/Core/ItemClaimLifecycleTest.php b/plugins/data-machine/tests/Unit/Core/ItemClaimLifecycleTest.php index 87819bf763..719b9eb054 100644 --- a/plugins/data-machine/tests/Unit/Core/ItemClaimLifecycleTest.php +++ b/plugins/data-machine/tests/Unit/Core/ItemClaimLifecycleTest.php @@ -345,7 +345,7 @@ public function test_reject_source_defers_owned_claim_completion_to_terminal_lif datamachine_set_engine_data( $job_id, array_merge( - $this->legacyEngineData( 'rejected-by-agent' ), + $this->sourceEngineData( 'rejected-by-agent' ), array( ProcessedItems::CLAIM_METADATA_KEY => $claim ) ) ); @@ -372,7 +372,7 @@ public function test_defer_item_defers_owned_claim_release_to_terminal_lifecycle datamachine_set_engine_data( $job_id, array_merge( - $this->legacyEngineData( 'deferred-by-agent' ), + $this->sourceEngineData( 'deferred-by-agent' ), array( ProcessedItems::CLAIM_METADATA_KEY => $claim ) ) ); @@ -564,23 +564,15 @@ public function test_process_death_after_commit_replays_persisted_processed_clai $this->assertSame( 1, RunMetrics::fromJob( $this->jobs->get_job( $job_id ) )['counts']['processed'] ); } - public function test_cancellation_atomically_releases_mixed_descriptor_and_legacy_claims(): void { + public function test_cancellation_atomically_releases_descriptor_claim(): void { $job_id = $this->createJobWithClaim( array(), true ); $claim = $this->claim( 'cancel-mixed-owned', $job_id, 'must-not-persist' ); - $this->assertTrue( $this->processed->claim_item( self::SCOPE, self::SOURCE, 'cancel-mixed-legacy', $job_id ) ); - datamachine_set_engine_data( - $job_id, - array_merge( - $this->legacyEngineData( 'cancel-mixed-legacy' ), - array( ProcessedItems::CLAIM_METADATA_KEY => $claim ) - ) - ); + datamachine_set_engine_data( $job_id, array( ProcessedItems::CLAIM_METADATA_KEY => $claim ) ); $this->assertTrue( $this->jobs->complete_job( $job_id, JobStatus::CANCELLED ) ); $this->assertSame( JobStatus::CANCELLED, $this->jobs->get_job( $job_id )['status'] ); $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'cancel-mixed-owned' ) ); - $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'cancel-mixed-legacy' ) ); $this->assertNull( $this->tracked->get( self::NAMESPACE, 'cancel-mixed-owned' ) ); } @@ -1089,90 +1081,6 @@ static function () use ( &$called ): bool { $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'corrupt-id' ) ); } - /** - * @dataProvider legacy_terminal_status_provider - */ - public function test_predeployment_job_without_descriptor_releases_legacy_claim( string $status ): void { - $job_id = $this->createJobWithClaim( array(), true ); - $this->assertTrue( $this->processed->claim_item( self::SCOPE, self::SOURCE, 'legacy-' . $status, $job_id ) ); - - $this->assertTrue( $this->jobs->complete_job( $job_id, $status ) ); - $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'legacy-' . $status ) ); - } - - public function test_descriptorless_success_completes_job_owned_claim(): void { - $job_id = $this->createJobWithClaim( array(), true ); - $this->assertTrue( $this->processed->claim_item( self::SCOPE, self::SOURCE, 'legacy-success', $job_id ) ); - - StepLifecycleHandler::handleCompleted( $job_id, $this->legacyEngineData( 'legacy-success' ) ); - - $this->assertTrue( $this->processed->has_item_been_processed( self::SCOPE, self::SOURCE, 'legacy-success' ) ); - } - - public function test_stale_descriptorless_success_cannot_overwrite_replacement_owner(): void { - $legacy_job_id = $this->createJobWithClaim( array(), true ); - $this->assertTrue( $this->processed->claim_item( self::SCOPE, self::SOURCE, 'legacy-replaced', $legacy_job_id ) ); - $this->expireClaim( 'legacy-replaced' ); - $replacement = $this->claim( 'legacy-replaced', 905, 'replacement-revision' ); - - StepLifecycleHandler::handleCompleted( $legacy_job_id, $this->legacyEngineData( 'legacy-replaced' ) ); - - $this->assertTrue( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'legacy-replaced' ) ); - StepLifecycleHandler::handleCompleted( 905, array( ProcessedItems::CLAIM_METADATA_KEY => $replacement ) ); - $this->assertSame( 'replacement-revision', $this->tracked->get( self::NAMESPACE, 'legacy-replaced' )['source_revision'] ); - } - - public function legacy_terminal_status_provider(): array { - return array( - 'failure' => array( JobStatus::failed( 'legacy' )->toString() ), - 'cancellation' => array( JobStatus::CANCELLED ), - ); - } - - public function test_predeployment_stale_recovery_releases_legacy_claim(): void { - $job_id = $this->createJobWithClaim( array(), true ); - $this->assertTrue( $this->processed->claim_item( self::SCOPE, self::SOURCE, 'legacy-recovery', $job_id ) ); - datamachine_merge_engine_data( $job_id, array( 'job_status' => JobStatus::failed( 'stale' )->toString() ) ); - - ( new RecoverStuckJobsAbility() )->execute( - array( - 'dry_run' => false, - 'job_id' => $job_id, - ) - ); - $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'legacy-recovery' ) ); - } - - public function test_mixed_descriptor_and_legacy_claims_are_both_released(): void { - $job_id = $this->createJobWithClaim( array(), true ); - $claim = $this->claim( 'mixed-owned', $job_id, 'mixed-revision' ); - $this->assertTrue( $this->processed->claim_item( self::SCOPE, self::SOURCE, 'mixed-legacy', $job_id ) ); - - StepLifecycleHandler::handleFailed( $job_id, array( ProcessedItems::CLAIM_METADATA_KEY => $claim ) ); - $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'mixed-owned' ) ); - $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'mixed-legacy' ) ); - } - - public function test_mixed_descriptor_and_legacy_claims_are_both_completed(): void { - $job_id = $this->createJobWithClaim( array(), true ); - $claim = $this->claim( 'mixed-success-owned', $job_id, 'mixed-success-revision' ); - $this->assertTrue( $this->processed->claim_item( self::SCOPE, self::SOURCE, 'mixed-success-legacy', $job_id ) ); - datamachine_set_engine_data( - $job_id, - array_merge( - $this->legacyEngineData( 'mixed-success-legacy' ), - array( ProcessedItems::CLAIM_METADATA_KEY => $claim ) - ) - ); - - $this->assertTrue( $this->jobs->complete_job( $job_id, JobStatus::COMPLETED ) ); - - $this->assertSame( 'mixed-success-revision', $this->tracked->get( self::NAMESPACE, 'mixed-success-owned' )['source_revision'] ); - $this->assertTrue( $this->processed->has_item_been_processed( self::SCOPE, self::SOURCE, 'mixed-success-legacy' ) ); - $this->assertFalse( $this->processed->has_active_claim( self::SCOPE, self::SOURCE, 'mixed-success-owned' ) ); - $this->assertSame( 2, RunMetrics::fromJob( $this->jobs->get_job( $job_id ) )['counts']['processed'] ); - } - public function test_malformed_content_addressed_ref_releases_sidecar_claim(): void { $parent_id = $this->createJobWithClaim( array(), true ); $claim = $this->claim( 'malformed-ref', $parent_id, 'malformed-revision' ); @@ -1272,7 +1180,7 @@ private function openMysqlConnection(): ?\mysqli { return $connection; } - private function legacyEngineData( string $item_id ): array { + private function sourceEngineData( string $item_id ): array { return array( 'item_identifier' => $item_id, 'source_type' => self::SOURCE, diff --git a/plugins/data-machine/tests/batch-completion-strategy-smoke.php b/plugins/data-machine/tests/batch-completion-strategy-smoke.php index b17f373349..9cbfb68f5c 100644 --- a/plugins/data-machine/tests/batch-completion-strategy-smoke.php +++ b/plugins/data-machine/tests/batch-completion-strategy-smoke.php @@ -131,6 +131,6 @@ function build_task_batch_status_strategy( array $engine_data ): string { 'getBatchStatus exposes completion_strategy from engine_data' ); datamachine_strategy_assert( $chunks_strategy === build_task_batch_status_strategy( $metadata ), 'status helper resolves stored strategy' ); -datamachine_strategy_assert( '' === build_task_batch_status_strategy( array() ), 'missing legacy strategy resolves to empty string' ); +datamachine_strategy_assert( '' === build_task_batch_status_strategy( array() ), 'missing strategy resolves to empty string' ); echo "\n=== batch-completion-strategy-smoke: ALL PASS ===\n";