dbh instanceof \mysqli, 'storage_session_unavailable', 503); $retries = $database->reconnect_retries; $query_filter = $wp_filter['query'] ?? null; $reporting = error_reporting(); $database->reconnect_retries = 0; unset($wp_filter['query']); try { demand($database->check_connection(false), 'operation_lock_lost', 503); return $fn(); } finally { $database->reconnect_retries = $retries; error_reporting($reporting); // Core's failed connection check can lower it. if ($query_filter === null) unset($wp_filter['query']); else $wp_filter['query'] = $query_filter; } } function session_connection_id($database) { return session_database_call($database, static function () use ($database) { $id = $database->get_var('SELECT CONNECTION_ID()'); demand(!$database->last_error && ctype_digit((string) $id) && (int) $id > 0, 'operation_lock_lost', 503); return (int) $id; }); } /** Check the original session without reconnecting or replaying SQL. */ function assert_lock_session($database, $connection, $thread, $name) { global $wpdb; try { demand($wpdb === $database && $database->dbh === $connection, 'operation_lock_lost', 503); session_database_call($database, static function () use ($database, $thread, $name) { $proof = $database->get_row($database->prepare('SELECT CONNECTION_ID() AS connection_id, IS_USED_LOCK(%s) AS owner_id', $name)); demand(!$database->last_error && $proof && (int) $proof->connection_id === $thread && (int) $proof->owner_id === $thread, 'operation_lock_lost', 503); }); } catch (\Throwable $e) { throw new Failure('operation_lock_lost', 503); } } /** Cleanup is best effort and must never reconnect to a different session. */ function session_cleanup($database, $thread, $sql) { try { session_database_call($database, static function () use ($database, $thread, $sql) { if ((int) $database->get_var('SELECT CONNECTION_ID()') === $thread) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Callers supply prepared RELEASE_LOCK or the fixed ROLLBACK literal. $database->query($sql); } }); } catch (\Throwable $ignored) {} } function with_effect_lock($scope, $key, $fn, $wait_seconds = 0) { global $wpdb; // A database drop-in can replace core retry semantics; do not claim the fence covers it. demand(get_class($wpdb) === 'wpdb' && $wpdb->dbh instanceof \mysqli, 'storage_session_unavailable', 503); $name = effect_lock_name($scope, $key); demand((string) $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s,%d)', $name, $wait_seconds)) === '1', 'operation_busy', 409); $database = $wpdb; $connection = $database->dbh; $thread = session_connection_id($database); $retries = $database->reconnect_retries; $guard = static function ($value) use ($database, $connection, $thread, $name) { assert_lock_session($database, $connection, $thread, $name); return $value; }; // Core's query() retries a failed SQL statement after check_connection(). Disable // that retry even if the session dies between our query guard and the SQL call. $database->reconnect_retries = 0; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Existing WordPress core query filter. add_filter('query', $guard, PHP_INT_MAX); // Check before HTTP dispatch, including account setup, rather than only after the callback. add_filter('pre_http_request', $guard, PHP_INT_MAX); try { assert_lock_session($database, $connection, $thread, $name); $result = $fn(); assert_lock_session($database, $connection, $thread, $name); return $result; } finally { remove_filter('query', $guard, PHP_INT_MAX); remove_filter('pre_http_request', $guard, PHP_INT_MAX); $database->reconnect_retries = $retries; if ($database->dbh === $connection) session_cleanup($database, $thread, $database->prepare('SELECT RELEASE_LOCK(%s)', $name)); } } /** Current connection controls an immutable older request from the same installation. */ function control_historical_operation($b,$control) { schema('historicalControlRequest',$control);current_binding($b); foreach (['tenant_id','site_id','installation_id','connection_id','policy_hash'] as $k) demand($control->{$k}===$b->{$k},'binding_mismatch',403); $body=$control->original_request; foreach (['tenant_id','site_id','installation_id'] as $k) demand($body->{$k}===$b->{$k},'historical_identity_mismatch',403); demand($body->idempotency_key===$control->idempotency_key,'idempotency_mismatch',409); demand($body->connection_id!==$b->connection_id || $control->original_key_id!==$b->key_id || $body->policy_hash!==$b->policy_hash,'historical_connection_required',409); return retire_operation($b,$body,$control->original_key_id); } /** Fenced cancellation: journal absence is checked only while holding execute's lock. */ function retire_operation($b, $body, $original_key_id = null) { demand(in_array($body->operation, ['media.upload', 'publication.create_draft', 'publication.amend_draft', 'publication.publish_draft', 'publication.amend_published'], true), 'retirement_unsupported', 409); demand(in_array('operation.read', effective_policy($b)->capabilities, true), 'grant_denied', 403); $a=$body->authorization;$start=utc_seconds($a->approved_at);$end=utc_seconds($a->expires_at); demand($end>$start && $end-$start<=900 && $end$value) if ($name!=='execution_fingerprint') demand(hash_equals($body->{$name},$value),'semantic_mismatch',409); $scope=journal_scope($b);$key=$body->idempotency_key;$fingerprint=effect_hashes($body)['execution_fingerprint']; $historical=$original_key_id!==null;$audit_key=$original_key_id??$b->key_id;$audit_hash=semantic_hash(obj(['key_id'=>$audit_key,'body'=>$body])); return with_effect_lock($scope,$key,function() use($b,$body,$scope,$key,$fingerprint,$a,$historical,$audit_key,$audit_hash) { current_binding($b);$row=journal_read($scope,'operation:'.$key); if ($row!==null) { demand($row->execution_fingerprint===$fingerprint,'idempotency_conflict',409); if ($historical && $row->state!=='cancelled') demand(isset($row->request_audit_fingerprint) && $row->request_audit_fingerprint===$audit_hash,'historical_request_changed',409); if ($row->state==='completed') return operation_status($b,$key,$row); if ($row->state==='cancelled') { if ($historical) demand(isset($row->request_audit_fingerprint) && $row->request_audit_fingerprint===$audit_hash,'historical_request_changed',409);demand($row->retirement->original_expired_at===$a->expires_at,'retirement_conflict',409);$proof=clone $row->retirement;$proof->checked_at=utc_now();return $proof; } // An explicit authenticated result control may repair metadata only. // The original execution shares this lock and cannot be in flight. if ($row->state==='executing' && isset($row->object_id) && is_int($row->object_id) && $row->object_id>0) { try { return recover_correlated_receipt_locked($b,$body,$row,$audit_key); } catch (Failure $e) { if ($e->status!==409 && $e->status!==403) throw $e; } } return obj(['state'=>'needs_provider_resolution']); } $proof=pick($body,['tenant_id','site_id','installation_id','connection_id','effect_id','idempotency_key','subject_hash','target_fingerprint','policy_hash']); $proof->state='absent_retired';$proof->execution_fingerprint=$fingerprint; $proof->content_hash=$body->operation==='media.upload' ? $body->media->sha256 : semantic_hash($body->publication->projection); $proof->original_expired_at=$a->expires_at;$proof->checked_at=utc_now();$proof->write_attempted=false; demand(journal_insert($scope,'operation:'.$key,obj(['state'=>'cancelled','execution_fingerprint'=>$fingerprint,'request_audit_fingerprint'=>$audit_hash,'receipt'=>null,'retirement'=>$proof])),'retirement_conflict',409); return $proof; },5); } /** Exact existing-object proof; neither a reservation nor a title/URL search is proof. */ function correlated_recovery_snapshot($b,$body,$audit_key = null) { global $wpdb; current_binding($b); demand(in_array($body->operation,['media.upload','publication.create_draft','publication.amend_draft','publication.publish_draft'],true),'recovery_unsupported',409); $scope=journal_scope($b);$key=$body->idempotency_key;$row=journal_read($scope,'operation:'.$key); demand($row && $row->state==='executing' && $row->receipt===null && isset($row->object_id) && is_int($row->object_id) && $row->object_id>0,'recovery_not_available',409); demand($row->execution_fingerprint===effect_hashes($body)['execution_fingerprint'] && $row->request_audit_fingerprint===semantic_hash(obj(['key_id'=>$audit_key??$b->key_id,'body'=>$body])),'recovery_request_changed',409); demand(journal_read($scope,'recovery:'.$key)===null,'recovery_not_available',409); $id=$row->object_id;clean_post_cache($id);$post=get_post($id); $media=$body->operation==='media.upload'; $status=$media?'inherit':($body->operation==='publication.publish_draft'?'publish':'draft'); demand($post && $post->post_type===($media?'attachment':'post') && $post->post_status===$status,'recovery_object_changed',409); $scopes=get_post_meta($id,'_publisher_connector_scope',false);$handles=get_post_meta($id,'_publisher_connector_handle',false); demand(count($scopes)===1 && $scopes[0]===$scope && count($handles)===1,'recovery_identity_ambiguous',409); $handle=schema('uuid',$handles[0]); $count=$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %i WHERE meta_key='_publisher_connector_handle' AND BINARY meta_value=BINARY %s", $wpdb->postmeta, $handle)); demand(!$wpdb->last_error && (int)$count===1,'recovery_identity_ambiguous',409); $slot=($media?'media:':'publication:').$handle;$before=journal_read($scope,$slot); if ($media) { $hashes=get_post_meta($id,'_publisher_connector_original_sha256',false); $path=get_attached_file($id);$metadata=wp_get_attachment_metadata($id); demand(count($hashes)===1 && $hashes[0]===$body->media->sha256 && $path && is_file($path) && hash_file('sha256',$path)===$body->media->sha256 && $post->post_mime_type===$body->media->mime_type && is_array($metadata) && !empty($metadata['width']) && !empty($metadata['height']) && get_post_meta($id,'_wp_attachment_image_alt',true)===$body->media->alt_text && get_post_meta($id,'_publisher_connector_credit',true)===$body->media->credit,'recovery_content_changed',409); $record=obj(['installation_id'=>$b->installation_id,'object_id'=>$id,'original_sha256'=>$body->media->sha256]); demand($before===null || canonical($before)===canonical($record),'recovery_identity_ambiguous',409); $result=obj(['kind'=>'media','media_handle'=>$handle,'attachment_id'=>$id,'original_sha256'=>$body->media->sha256]); } else { $p=$body->publication->projection; $record=obj(['installation_id'=>$b->installation_id,'object_id'=>$id,'projection'=>$p]); if ($body->operation!=='publication.create_draft') { demand($body->publication->draft_handle===$handle && $before && $before->installation_id===$b->installation_id && $before->object_id===$id,'recovery_identity_ambiguous',409); $prior=semantic_hash($before->projection); demand($prior===$body->publication->expected_draft_hash || $prior===semantic_hash($p),'recovery_content_changed',409); } else demand($before===null || canonical($before)===canonical($record),'recovery_identity_ambiguous',409); $projection=projection_read($b,$record); demand(canonical($projection)===canonical($p),'recovery_content_changed',409); $url=$status==='publish'?get_permalink($id):null; if ($url!==null) { $home=trailingslashit(home_url('/'));demand(str_starts_with($home,'https://') && str_starts_with($url,$home) && !preg_match('/[\x00-\x20]/',$url),'recovery_content_changed',409); } $result=obj(['kind'=>'publication','publication_handle'=>$handle,'post_id'=>$id,'status'=>$status,'projection'=>$projection,'content_hash'=>semantic_hash($projection),'public_url'=>$url]); } return obj(['journal'=>$row,'post_hash'=>hash('sha256',serialize($post->to_array())),'slot'=>$slot,'before'=>$before,'record'=>$record,'result'=>$result]); } /** Caller holds the original effect lock. One transaction repairs only Connector journals. */ function recover_correlated_receipt_locked($b,$body,$expected_row,$audit_key = null) { global $wpdb; demand($wpdb->dbh instanceof \mysqli,'recovery_transaction_unavailable',503); $connection_id=session_connection_id($wpdb);$scope=journal_scope($b);$key=$body->idempotency_key;$id=$expected_row->object_id; demand((int)$wpdb->get_var('SELECT @@in_transaction')===0,'recovery_transaction_active',409); foreach ([$wpdb->options,$wpdb->posts,$wpdb->postmeta,$wpdb->term_relationships,table()] as $table) demand($wpdb->get_var($wpdb->prepare('SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s',$table))==='InnoDB','recovery_transaction_unavailable',503); db_ok($wpdb->query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE'));db_ok($wpdb->query('START TRANSACTION')); try { foreach ([ $wpdb->prepare("SELECT option_id FROM %i WHERE option_name IN (%s,%s) FOR UPDATE", $wpdb->options, 'publisher_connector_binding','publisher_connector_installation'), $wpdb->prepare('SELECT data FROM %i WHERE scope=%s AND slot=%s FOR UPDATE', table(),$scope,'operation:'.$key), $wpdb->prepare("SELECT ID FROM %i WHERE ID=%d FOR UPDATE", $wpdb->posts, $id), $wpdb->prepare("SELECT meta_id FROM %i WHERE post_id=%d FOR UPDATE", $wpdb->postmeta, $id), $wpdb->prepare("SELECT object_id FROM %i WHERE object_id=%d FOR UPDATE", $wpdb->term_relationships, $id) ] as $sql) recovery_transaction_query($sql,$connection_id); $s=correlated_recovery_snapshot($b,$body,$audit_key); demand(canonical($s->journal)===canonical($expected_row),'recovery_snapshot_changed',409); if ($s->before===null) demand(recovery_transaction_query($wpdb->prepare('INSERT INTO %i (scope,slot,data) VALUES (%s,%s,%s)', table(),$scope,$s->slot,canonical($s->record)),$connection_id)===1,'recovery_conflict',409); elseif (canonical($s->before)!==canonical($s->record)) demand(recovery_transaction_query($wpdb->prepare('UPDATE %i SET data=%s WHERE scope=%s AND slot=%s AND BINARY data=BINARY %s', table(),canonical($s->record),$scope,$s->slot,canonical($s->before)),$connection_id)===1,'recovery_conflict',409); $receipt=pick($body,['protocol_version','tenant_id','site_id','installation_id','effect_id','operation','idempotency_key','subject_hash','target_fingerprint','policy_hash']); $receipt->original_connection_id=$body->connection_id;$receipt->state='completed';$receipt->write_attempted=true;$receipt->result=$s->result; $receipt->receipt_hash=semantic_hash($receipt);schema('receipt',$receipt); $audit=obj(['operation'=>'correlated_receipt_recovery','control_connection_id'=>$b->connection_id,'original_key_id'=>$audit_key??$b->key_id,'request_hash'=>semantic_hash($body),'recovered_at'=>utc_now(),'receipt_hash'=>$receipt->receipt_hash,'original_journal_hash'=>semantic_hash($s->journal),'original_handle_record'=>$s->before,'post_hash'=>$s->post_hash]); demand(recovery_transaction_query($wpdb->prepare('INSERT INTO %i (scope,slot,data) VALUES (%s,%s,%s)', table(),$scope,'recovery:'.$key,canonical($audit)),$connection_id)===1,'recovery_conflict',409); $complete=clone $s->journal;$complete->state='completed';$complete->receipt=$receipt; demand(recovery_transaction_query($wpdb->prepare('UPDATE %i SET data=%s WHERE scope=%s AND slot=%s AND BINARY data=BINARY %s', table(),canonical($complete),$scope,'operation:'.$key,canonical($s->journal)),$connection_id)===1,'recovery_conflict',409); $observed=observe_receipt($b,$receipt);demand($observed->state==='match','recovery_content_changed',409); recovery_transaction_query('COMMIT',$connection_id); return operation_status($b,$key,$complete); } catch (\Throwable $e) { session_cleanup($wpdb, $connection_id, 'ROLLBACK'); throw $e; } } /** No content writes. Read exact durable identity and current projection. */ function draft_recovery_snapshot($body) { global $wpdb; schema('publicationRequest', $body); demand($body->operation === 'publication.create_draft' && $body->publication->mode === 'create_draft' && $body->publication->projection->media_handle === null, 'recovery_unsupported', 409); $b = binding_read(); demand($b->state === 'active' && $b->installation_id === option_read('publisher_connector_installation') && $b->api_base === api_base(), 'recovery_binding_changed', 409); foreach (['tenant_id','site_id','installation_id','connection_id','policy_hash'] as $k) demand($body->{$k} === $b->{$k}, 'recovery_binding_changed', 409); demand(semantic_hash($b->policy) === $b->policy_hash && in_array('operation.read', effective_policy($b)->capabilities, true), 'recovery_binding_changed', 409); $hashes = effect_hashes($body); foreach (['subject_hash','target_fingerprint','idempotency_key'] as $k) demand($body->{$k} === $hashes[$k], 'recovery_request_changed', 409); $scope = journal_scope($b); $row = journal_read($scope, 'operation:' . $body->idempotency_key); demand($row && $row->state === 'executing' && $row->receipt === null && isset($row->object_id) && is_int($row->object_id) && $row->object_id > 0, 'recovery_not_available', 409); demand($row->execution_fingerprint === $hashes['execution_fingerprint'] && $row->request_audit_fingerprint === semantic_hash(obj(['key_id'=>$b->key_id,'body'=>$body])), 'recovery_request_changed', 409); // The old attestation proves the original request, never authorizes a new write. $a = $body->authorization; demand(utc_seconds($a->approved_at) < utc_seconds($a->expires_at) && utc_seconds($a->expires_at) - utc_seconds($a->approved_at) <= 900 && utc_seconds($a->expires_at) < microtime(true), 'recovery_wait_for_expiry', 409); $id = $row->object_id; clean_post_cache($id); $post = get_post($id); demand($post && $post->post_type === 'post' && $post->post_status === 'draft', 'recovery_object_changed', 409); $scopes = get_post_meta($id, '_publisher_connector_scope', false); $handles = get_post_meta($id, '_publisher_connector_handle', false); demand(count($scopes) === 1 && $scopes[0] === $scope && count($handles) === 1, 'recovery_identity_ambiguous', 409); $handle = schema('uuid', $handles[0]); $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %i WHERE meta_key='_publisher_connector_handle' AND BINARY meta_value=BINARY %s", $wpdb->postmeta, $handle)); demand(!$wpdb->last_error && (int) $count === 1, 'recovery_identity_ambiguous', 409); demand(journal_read($scope, 'publication:' . $handle) === null && journal_read($scope, 'recovery:' . $body->idempotency_key) === null, 'recovery_not_available', 409); $record = obj(['installation_id'=>$b->installation_id,'object_id'=>$id,'projection'=>$body->publication->projection]); $projection = projection_read($b, $record); demand(canonical($projection) === canonical($body->publication->projection), 'recovery_content_changed', 409); return obj(['binding'=>pick($b,['tenant_id','site_id','installation_id','connection_id','key_id','policy_hash','api_base']), 'request_hash'=>semantic_hash($body),'journal'=>$row,'post_hash'=>hash('sha256',serialize($post->to_array())),'post_id'=>$id,'handle'=>$handle,'projection'=>$projection]); } function admin_plan_draft_recovery($body, $nonce) { admin_authorize($nonce); $s = draft_recovery_snapshot($body); $plan = obj(['version'=>1,'operation'=>'recover_draft_receipt','effect_id'=>$body->effect_id,'idempotency_key'=>$body->idempotency_key,'post_id'=>$s->post_id,'snapshot_hash'=>semantic_hash($s),'request_hash'=>semantic_hash($body),'admin_user_id'=>get_current_user_id(),'created_at'=>utc_now(),'expires_at'=>gmdate('Y-m-d\TH:i:s',time()+900).'.000Z','original_worker_must_be_stopped'=>true]); $plan->plan_hash = semantic_hash($plan); $plan->seal = hash_hmac('sha256', 'publisher-recovery-plan-v1/' . $plan->plan_hash, independent_secret_key(RECOVERY_KEY_OPTION, true)); $plan->expected_command = 'PUBLISHER RECOVER DRAFT ' . $body->effect_id . ' ' . $plan->plan_hash . ' ORIGINAL WORKER STOPPED'; return $plan; } /** wpdb may reconnect/retry a query. A recovery transaction must never do that. */ function recovery_transaction_query($sql, $connection_id) { global $wpdb; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Preserve the existing WordPress core query filter on the pinned transaction. $sql = apply_filters('query', $sql); $database = $wpdb; return session_database_call($database, static function () use ($database, $sql, $connection_id) { $proof = $database->get_row('SELECT CONNECTION_ID() AS connection_id, @@in_transaction AS in_transaction'); demand(!$database->last_error && $proof && (int) $proof->connection_id === $connection_id, 'recovery_connection_lost', 503); demand((int) $proof->in_transaction === 1, 'recovery_transaction_lost', 503); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Callers prepare dynamic queries; fixed COMMIT/ROLLBACK contain no parameters. Filters already ran before the proof. $result = $database->query($sql); demand($result !== false, 'recovery_storage_failed', 503); return $result; }); } function admin_apply_draft_recovery($body, $plan, $command, $nonce) { global $wpdb; admin_authorize($nonce); demand($plan instanceof \stdClass && isset($plan->plan_hash,$plan->seal,$plan->expected_command), 'recovery_plan_invalid', 409); $unsigned = clone $plan; unset($unsigned->plan_hash,$unsigned->seal,$unsigned->expected_command); $expected = 'PUBLISHER RECOVER DRAFT ' . $body->effect_id . ' ' . $plan->plan_hash . ' ORIGINAL WORKER STOPPED'; demand(semantic_hash($unsigned) === $plan->plan_hash && hash_equals(hash_hmac('sha256','publisher-recovery-plan-v1/'.$plan->plan_hash,independent_secret_key(RECOVERY_KEY_OPTION, true)),$plan->seal) && $plan->expected_command === $expected && $command === $expected, 'recovery_approval_required', 403); demand($plan->admin_user_id === get_current_user_id() && $plan->request_hash === semantic_hash($body) && utc_seconds($plan->created_at) <= microtime(true) && utc_seconds($plan->expires_at) >= microtime(true), 'recovery_plan_stale', 409); $b = binding_read(); $scope = journal_scope($b); $key = $body->idempotency_key; return with_effect_lock($scope, $key, function () use ($body,$plan,$command,$scope,$key) { global $wpdb; $connection_id = session_connection_id($wpdb); // A nested transaction would commit the caller's unrelated work. demand((int)$wpdb->get_var('SELECT @@in_transaction') === 0, 'recovery_transaction_active', 409); foreach ([$wpdb->options,$wpdb->posts,$wpdb->postmeta,$wpdb->term_relationships,table()] as $table) { demand($wpdb->get_var($wpdb->prepare('SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s',$table)) === 'InnoDB','recovery_transaction_unavailable',503); } db_ok($wpdb->query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')); db_ok($wpdb->query('START TRANSACTION')); try { db_ok($wpdb->query($wpdb->prepare("SELECT option_id FROM %i WHERE option_name IN (%s,%s) FOR UPDATE", $wpdb->options, 'publisher_connector_binding','publisher_connector_installation'))); db_ok($wpdb->query($wpdb->prepare('SELECT data FROM %i WHERE scope=%s AND slot=%s FOR UPDATE', table(),$scope,'operation:'.$key))); db_ok($wpdb->query($wpdb->prepare("SELECT ID FROM %i WHERE ID=%d FOR UPDATE", $wpdb->posts, $plan->post_id))); db_ok($wpdb->query($wpdb->prepare("SELECT meta_id FROM %i WHERE post_id=%d FOR UPDATE", $wpdb->postmeta, $plan->post_id))); db_ok($wpdb->query($wpdb->prepare("SELECT object_id FROM %i WHERE object_id=%d FOR UPDATE", $wpdb->term_relationships, $plan->post_id))); $s = draft_recovery_snapshot($body); demand(semantic_hash($s) === $plan->snapshot_hash, 'recovery_snapshot_changed', 409); $record = obj(['installation_id'=>$body->installation_id,'object_id'=>$s->post_id,'projection'=>$s->projection]); demand(recovery_transaction_query($wpdb->prepare('INSERT INTO %i (scope,slot,data) VALUES (%s,%s,%s)', table(),$scope,'publication:'.$s->handle,canonical($record)),$connection_id) === 1,'recovery_conflict',409); $receipt = pick($body,['protocol_version','tenant_id','site_id','installation_id','effect_id','operation','idempotency_key','subject_hash','target_fingerprint','policy_hash']); $receipt->original_connection_id=$body->connection_id;$receipt->state='completed';$receipt->write_attempted=true; $receipt->result=obj(['kind'=>'publication','publication_handle'=>$s->handle,'post_id'=>$s->post_id,'status'=>'draft','projection'=>$s->projection,'content_hash'=>semantic_hash($s->projection),'public_url'=>null]); $receipt->receipt_hash=semantic_hash($receipt);schema('receipt',$receipt); $audit=obj(['plan'=>$plan,'approved_command'=>$command,'recovered_at'=>utc_now(),'receipt_hash'=>$receipt->receipt_hash,'original_journal_hash'=>semantic_hash($s->journal)]); demand(recovery_transaction_query($wpdb->prepare('INSERT INTO %i (scope,slot,data) VALUES (%s,%s,%s)', table(),$scope,'recovery:'.$key,canonical($audit)),$connection_id) === 1,'recovery_conflict',409); $complete=clone $s->journal;$complete->state='completed';$complete->receipt=$receipt; demand(recovery_transaction_query($wpdb->prepare('UPDATE %i SET data=%s WHERE scope=%s AND slot=%s AND BINARY data=BINARY %s', table(),canonical($complete),$scope,'operation:'.$key,canonical($s->journal)),$connection_id) === 1,'recovery_conflict',409); recovery_transaction_query('COMMIT',$connection_id);return $receipt; } catch (\Throwable $e) { session_cleanup($wpdb, $connection_id, 'ROLLBACK'); throw $e; } }); }