prefix . 'aipt_blueprint_results'; } /** * Create a new result row. * * Expiry is NOT decided here: the caller (the execution service that * knows whether this is a 24h test preview or a longer-lived * provenance record) must pass `expiresAt`. A missing `expiresAt` * defaults to "now" — immediately eligible for the next cleanup tick — * a fail-safe default that surfaces a caller bug as a quickly-pruned * row rather than silently retaining it forever. * * @param array $row { * @type string $resultKey Optional pre-generated 32-hex key (e.g. from a caller that must * bake the key into `payload` before the first write). When given, * this exact key is used for a single insert attempt — a collision * is reported as a plain failure rather than silently retried under * a different key, which would no longer match what the caller * already serialized into `payload`. Omit to fall back to this * method's own random-key generation (with its collision retry). * @type string $generator Required. * @type string $subjectType 'product'|'term'|'attachment'. * @type int $subjectId Required. * @type int $productId Default 0. * @type string $origin 'test'|'bulk'|'regenerate'. Default 'test'. * @type int $blueprintId Default 0. * @type int $snapshotId Default 0 (unsaved draft). * @type string $definitionHash Default ''. * @type string $contextHash Default ''. * @type string $status Default 'ok'. * @type bool $eligible Default false. * @type array $payload Required; GenerationResult shape. * @type int $createdBy Default current user. * @type string $expiresAt MySQL UTC datetime. Default now. * } * @return string The result_key used (32 hex chars), or '' on failure. */ public function create( array $row ): string { global $wpdb; $table = self::table(); $now = current_time( 'mysql', true ); $user = isset( $row['createdBy'] ) ? (int) $row['createdBy'] : (int) ( function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0 ); $expires_at = isset( $row['expiresAt'] ) ? (string) $row['expiresAt'] : $now; $given_key = isset( $row['resultKey'] ) ? (string) $row['resultKey'] : ''; $max_attempts = '' !== $given_key ? 1 : self::MAX_KEY_ATTEMPTS; for ( $attempt = 0; $attempt < $max_attempts; $attempt++ ) { $result_key = '' !== $given_key ? $given_key : bin2hex( random_bytes( 16 ) ); $data = array( 'result_key' => $result_key, 'generator' => (string) ( $row['generator'] ?? '' ), 'subject_type' => (string) ( $row['subjectType'] ?? 'product' ), 'subject_id' => (int) ( $row['subjectId'] ?? 0 ), 'product_id' => (int) ( $row['productId'] ?? 0 ), 'origin' => (string) ( $row['origin'] ?? 'test' ), 'blueprint_id' => (int) ( $row['blueprintId'] ?? 0 ), 'snapshot_id' => (int) ( $row['snapshotId'] ?? 0 ), 'definition_hash' => (string) ( $row['definitionHash'] ?? '' ), 'context_hash' => (string) ( $row['contextHash'] ?? '' ), 'status' => (string) ( $row['status'] ?? 'ok' ), 'eligible' => ! empty( $row['eligible'] ) ? 1 : 0, 'payload' => wp_json_encode( is_array( $row['payload'] ?? null ) ? $row['payload'] : array() ), 'created_by' => $user, 'created_at' => $now, 'expires_at' => $expires_at, 'applied_at' => null, ); $previous_suppress = $wpdb->suppress_errors( true ); $inserted = $wpdb->insert( $table, $data, array( '%s', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%s', '%s', '%s' ) ); $wpdb->suppress_errors( $previous_suppress ); if ( false !== $inserted ) { return $result_key; } $last_error = (string) $wpdb->last_error; if ( false === strpos( $last_error, 'Duplicate entry' ) && false === strpos( $last_error, '1062' ) ) { break; } } return ''; } /** * Read a result by its result_key. * * @param string $key result_key. * @return array|null */ public function get( string $key ): ?array { global $wpdb; if ( '' === $key ) { return null; } $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE result_key = %s", $key ), ARRAY_A ); return is_array( $row ) ? $this->mapRow( $row ) : null; } /** * Replace a stored result's payload after a non-AI recomputation (for * example a source-conflict decision that changes conflicts and * eligibility). * * Derives `status` and `eligible` from the payload's eligibility exactly * like the first persist does, and only touches a row that has not been * claimed or applied yet, so a decision can never rewrite an applied * outcome. * * @param string $key result_key. * @param array $payload Full GenerationResult payload. * @return bool True when an unclaimed row was updated. */ public function updatePayload( string $key, array $payload ): bool { global $wpdb; if ( '' === $key ) { return false; } $eligibility = isset( $payload['eligibility'] ) && is_array( $payload['eligibility'] ) ? $payload['eligibility'] : array(); $status = empty( $eligibility['canApply'] ) ? 'blocked' : ( ! empty( $eligibility['requiresReview'] ) ? 'needs_review' : 'ok' ); $eligible = ! empty( $eligibility['canApply'] ) ? 1 : 0; $encoded = wp_json_encode( $payload ); if ( false === $encoded ) { return false; } $table = self::table(); $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET payload = %s, status = %s, eligible = %d WHERE result_key = %s AND status IN ('ok','needs_review')", $encoded, $status, $eligible, $key ) ); return false !== $affected && (int) $affected >= 1; } /** * Atomically claim a result for apply: one conditional UPDATE, never a * check-then-write pair, so a second concurrent apply call for the * same key always loses the race. * * @param string $key result_key. * @return bool True when this call won the claim. */ public function claimForApply( string $key ): bool { global $wpdb; $table = self::table(); $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET status = 'applying' WHERE result_key = %s AND status IN ('ok','needs_review')", $key ) ); return false !== $affected && (int) $affected >= 1; } /** * Commit the outcome of a claimed apply. * * `applied_at` is stamped only for a genuine success ('applied' or * 'staged') — an 'apply_failed' outcome (unknown write state after the * claim) never gets an applied_at, and is NOT re-applicable (regenerate * instead), so this method deliberately does * not accept a path back to 'ok'/'needs_review' here — see * {@see releaseApply()} for the pre-write failure path. * * @param string $key result_key. * @param string $status 'applied'|'staged'|'apply_failed'. * @return bool True when a claimed row (status='applying') was updated. */ public function finishApply( string $key, string $status ): bool { global $wpdb; $table = self::table(); if ( in_array( $status, array( 'applied', 'staged' ), true ) ) { $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET status = %s, applied_at = %s WHERE result_key = %s AND status = 'applying'", $status, current_time( 'mysql', true ), $key ) ); } else { $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET status = %s WHERE result_key = %s AND status = 'applying'", $status, $key ) ); } return false !== $affected && (int) $affected >= 1; } /** * Release a claim back to its previous status. * * ONLY for a failure BEFORE any write was attempted (e.g. a stale * definition hash or a concurrency-token mismatch discovered right * after the claim) — never after the applier has been invoked, where * {@see finishApply()} with 'apply_failed' is the only allowed outcome. * * @param string $key result_key. * @param string $previous_status 'ok'|'needs_review' — the status the claim came from. * @return bool True when a claimed row (status='applying') was released. */ public function releaseApply( string $key, string $previous_status ): bool { global $wpdb; $table = self::table(); $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET status = %s WHERE result_key = %s AND status = 'applying'", $previous_status, $key ) ); return false !== $affected && (int) $affected >= 1; } /** * Delete result rows whose `expires_at` is before the given cutoff. * * Chunked with `DELETE ... LIMIT`, same shape as * {@see \AIPT\Core\ContentStructure\Storage\SourceCacheStore::purgeExpired()}. * * @param string $mysql_now MySQL UTC datetime cutoff. * @return int Total rows deleted. */ public function purgeExpired( string $mysql_now ): int { global $wpdb; $table = self::table(); $total_deleted = 0; while ( $total_deleted < self::MAX_DELETIONS_PER_CALL ) { $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE expires_at < %s LIMIT %d", $mysql_now, self::DELETE_CHUNK_SIZE ) ); if ( false === $deleted ) { break; } $deleted = (int) $deleted; if ( $deleted <= 0 ) { break; } $total_deleted += $deleted; } return $total_deleted; } /** * Delete every result for one subject (e.g. a permanently deleted * product or attachment). * * @param string $subject_type 'product'|'term'|'attachment'. * @param int $subject_id Subject id. * @return int Rows deleted. */ public function deleteForSubject( string $subject_type, int $subject_id ): int { global $wpdb; $table = self::table(); $result = $wpdb->delete( $table, array( 'subject_type' => $subject_type, 'subject_id' => $subject_id ), array( '%s', '%d' ) ); return false !== $result ? (int) $result : 0; } /** * Delete every result that points at the given Blueprint. * * @param int $blueprint_id Blueprint id. * @return int Rows deleted. */ public function deleteForBlueprint( int $blueprint_id ): int { global $wpdb; $table = self::table(); $result = $wpdb->delete( $table, array( 'blueprint_id' => $blueprint_id ), array( '%d' ) ); return false !== $result ? (int) $result : 0; } /** * Map a raw database row to the canonical camelCase response shape. * * @param array $row Database row. * @return array */ private function mapRow( array $row ): array { $payload = json_decode( (string) ( $row['payload'] ?? '' ), true ); return array( 'id' => (int) ( $row['id'] ?? 0 ), 'resultKey' => (string) ( $row['result_key'] ?? '' ), 'generator' => (string) ( $row['generator'] ?? '' ), 'subjectType' => (string) ( $row['subject_type'] ?? '' ), 'subjectId' => (int) ( $row['subject_id'] ?? 0 ), 'productId' => (int) ( $row['product_id'] ?? 0 ), 'origin' => (string) ( $row['origin'] ?? 'test' ), 'blueprintId' => (int) ( $row['blueprint_id'] ?? 0 ), 'snapshotId' => (int) ( $row['snapshot_id'] ?? 0 ), 'definitionHash' => (string) ( $row['definition_hash'] ?? '' ), 'contextHash' => (string) ( $row['context_hash'] ?? '' ), 'status' => (string) ( $row['status'] ?? 'ok' ), 'eligible' => (bool) ( (int) ( $row['eligible'] ?? 0 ) ), 'payload' => is_array( $payload ) ? $payload : array(), 'createdBy' => (int) ( $row['created_by'] ?? 0 ), 'createdAt' => (string) ( $row['created_at'] ?? '' ), 'expiresAt' => (string) ( $row['expires_at'] ?? '' ), 'appliedAt' => null !== ( $row['applied_at'] ?? null ) ? (string) $row['applied_at'] : null, ); } }