Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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' );
Expand Down
2 changes: 1 addition & 1 deletion plugins/data-machine/docs/development/1-0-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
393 changes: 35 additions & 358 deletions plugins/data-machine/inc/Core/ActionScheduler/BatchScheduler.php

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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'] );
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*/
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 ) {
Expand Down Expand Up @@ -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'] );
Expand Down Expand Up @@ -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 );
Expand All @@ -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 );
}

Expand All @@ -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 );
}

Expand Down Expand Up @@ -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.
*
Expand Down
Loading
Loading