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
11 changes: 0 additions & 11 deletions plugins/data-machine/docs/admin-interface/jobs-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion plugins/data-machine/docs/core-system/database-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
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:** 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
255 changes: 9 additions & 246 deletions plugins/data-machine/inc/Cli/Commands/JobsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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=<count>]
* : Maximum noncanonical candidate rows to inspect in this invocation (1-1000).
* ---
* default: 250
* ---
*
* [--format=<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.
*
Expand Down Expand Up @@ -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=<limit>]
* : Maximum rows to inspect.
* ---
* default: 500
* ---
*
* [--format=<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.
*
Expand Down Expand Up @@ -871,32 +690,30 @@ 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,
$failed_like,
'%Updated wiki article:%',
'%Source rejected:%',
$agent_skipped_like,
$historical_contention_status,
$limit
),
ARRAY_A
Expand All @@ -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;
}
Expand All @@ -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;
Expand Down Expand Up @@ -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'] : '';
Expand All @@ -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.
*
Expand Down Expand Up @@ -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<string,mixed> $engine_data Decoded engine data.
* @return array<string,mixed> 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.
*
Expand Down
Loading
Loading