You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudAutomaticOperationReco...

1142 lines
46 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\Cloud {
/** Isolated encrypted envelope for automatic-recovery tests. */
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'automatic-recovery-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$key = substr($value, strlen('automatic-recovery-test:'));
if (!array_key_exists($key, self::$values)) {
throw new \RuntimeException('Missing recovery test payload.');
}
return self::$values[$key];
}
}
final class AutomaticRecoveryTestAgentClient
{
public array $requests = [];
public array $responses = [];
public function systemRecoveryRequest(
string $method,
string $target,
string $operationId,
?array $payload = null
): array {
$request = compact(
'method', 'target', 'operationId', 'payload'
);
$this->requests[] = $request;
if ($this->responses === []) {
throw new \RuntimeException('Unexpected Agent request.');
}
$response = array_shift($this->responses);
if (is_callable($response)) {
$response = $response($request);
}
if ($response instanceof \Throwable) {
throw $response;
}
if (!is_array($response)) {
throw new \RuntimeException('Invalid test Agent response.');
}
return $response;
}
}
final class CloudAgentSettingsService
{
public static ?AutomaticRecoveryTestAgentClient $client = null;
public static function clientForConfiguration(
int $hostId,
float $timeoutSeconds = 120.0
): AutomaticRecoveryTestAgentClient {
if ($hostId !== 7 || $timeoutSeconds !== 30.0
|| self::$client === null) {
throw new \RuntimeException(
'Unexpected automatic recovery client request.'
);
}
return self::$client;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudJob;
use App\Services\Cloud\AutomaticRecoveryTestAgentClient;
use App\Services\Cloud\CloudAgentError;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudAutomaticOperationRecoveryService;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudOperationCompletionService;
use App\Services\Cloud\CloudOperationRecoveryService;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudWorkerService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('enable')->default(1);
$table->integer('is_admin')->default(0);
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id')->unique();
$table->string('request_idempotency_key')->unique();
$table->string('request_fingerprint');
$table->integer('parent_job_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('invoice_id')->nullable();
$table->integer('instance_id')->nullable();
$table->integer('snapshot_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->nullable();
$table->string('kind');
$table->string('execution_mode');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('status');
$table->text('sealed_payload');
$table->integer('attempts')->default(0);
$table->integer('dispatch_attempts')->default(0);
$table->integer('dispatch_deadline_at');
$table->integer('dispatch_started_at')->nullable();
$table->integer('agent_accepted_at')->nullable();
$table->integer('receipt_deadline_at')->nullable();
$table->integer('terminal_at')->nullable();
$table->boolean('effect_may_have_applied')->nullable();
$table->boolean('safe_to_resubmit')->nullable();
$table->string('effect_resolution');
$table->integer('effect_resolved_at')->nullable();
$table->integer('effect_resolved_by')->nullable();
$table->string('effect_resolution_reason')->default('');
$table->string('completion_event_id')->nullable();
$table->integer('read_at')->nullable();
$table->integer('dispatched_at')->nullable();
$table->string('lease_token')->nullable();
$table->integer('lease_until')->default(0);
$table->integer('available_at')->default(0);
$table->string('error_code')->nullable();
$table->boolean('finalization_incident')->default(0);
$table->string('finalization_error_code')->nullable();
$table->text('result_json')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->string('uuid');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('order_id')->nullable();
$table->integer('plan_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('resource_pool_id')->nullable();
$table->integer('reservation_id')->nullable();
$table->integer('current_period_id')->nullable();
$table->string('name');
$table->string('status');
$table->string('service_status');
$table->string('network_status');
$table->integer('expires_at')->nullable();
$table->decimal('renewal_price', 12, 2)->nullable();
$table->integer('renewal_days')->default(0);
$table->integer('renewal_traffic_bytes')->default(0);
$table->integer('traffic_quota_bytes')->default(0);
$table->integer('traffic_download_bytes')->default(0);
$table->integer('traffic_upload_bytes')->default(0);
$table->integer('lifetime_download_bytes')->default(0);
$table->integer('lifetime_upload_bytes')->default(0);
$table->integer('traffic_synced_at')->default(0);
$table->integer('suspended_at')->nullable();
$table->integer('network_suspended_at')->nullable();
$table->text('spec_json');
$table->text('sealed_credential')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_agent_completion_events',
static function (Blueprint $table): void {
$table->string('event_id')->primary();
$table->integer('host_id');
$table->string('operation_id');
$table->string('payload_sha256');
$table->string('outcome');
$table->boolean('effect_may_have_applied');
$table->boolean('safe_to_resubmit');
$table->string('error_code')->default('');
$table->text('result_json')->nullable();
$table->string('disposition')->default('received');
$table->integer('received_at');
$table->integer('applied_at')->nullable();
$table->unique(['host_id', 'operation_id']);
});
Capsule::table('user')->insert([
'id' => 1, 'enable' => 1, 'is_admin' => 0,
]);
$now = time();
$nextId = 100;
$insertSettingsJob = static function (
string $operationId,
array $body,
?array $credential = null
) use (&$nextId, $now): array {
$id = $nextId++;
$uuid = sprintf(
'00000000-0000-4000-8000-%012d',
$id
);
Capsule::table('cloud_instances')->insert([
'id' => $id,
'uuid' => $uuid,
'host_id' => 7,
'user_id' => 1,
'order_id' => null,
'plan_id' => null,
'offer_id' => null,
'resource_pool_id' => null,
'reservation_id' => null,
'current_period_id' => null,
'name' => 'settings-' . $id,
'status' => 'active',
'service_status' => 'exempt',
'network_status' => 'active',
'expires_at' => null,
'renewal_price' => null,
'renewal_days' => 0,
'renewal_traffic_bytes' => 0,
'traffic_quota_bytes' => 0,
'traffic_download_bytes' => 0,
'traffic_upload_bytes' => 0,
'lifetime_download_bytes' => 0,
'lifetime_upload_bytes' => 0,
'traffic_synced_at' => 0,
'suspended_at' => null,
'network_suspended_at' => null,
'spec_json' => json_encode(
['managed' => true],
JSON_THROW_ON_ERROR
),
'sealed_credential' => null,
'created_at' => $now - 3600,
'updated_at' => $now - 3600,
]);
$fields = [];
foreach ([
'hostname' => 'hostname',
'root_password' => 'password',
'ssh_public_key' => 'ssh_key',
] as $field => $code) {
if (array_key_exists($field, $body)) {
$fields[] = $code;
}
}
$payload = [
'method' => 'POST',
'request_target' => '/v1/vms/' . $uuid . '/settings',
'body' => $body + ['confirm_restart' => true],
'owner_id' => 1,
'can_manage' => false,
'credential' => $credential,
'settings_fields' => $fields,
];
Capsule::table('cloud_jobs')->insert([
'id' => $id,
'operation_id' => $operationId,
'request_idempotency_key' => $operationId,
'request_fingerprint' => hash('sha256', $operationId),
'parent_job_id' => null,
'order_id' => null,
'invoice_id' => null,
'instance_id' => $id,
'snapshot_id' => null,
'user_id' => 1,
'host_id' => 7,
'kind' => 'instance_settings',
'execution_mode' => 'agent',
'phase' => 'terminal',
'outcome' => 'failed',
'status' => 'failed',
'sealed_payload' => CloudSecrets::encrypt(
$payload,
'job-payload'
),
'attempts' => 1,
'dispatch_attempts' => 1,
'dispatch_deadline_at' => $now - 1000,
'dispatch_started_at' => $now - 990,
'agent_accepted_at' => $now - 980,
'receipt_deadline_at' => $now - 20,
'terminal_at' => $now - 10,
'effect_may_have_applied' => 1,
'safe_to_resubmit' => 0,
'effect_resolution' => 'unknown',
'effect_resolved_at' => null,
'effect_resolved_by' => null,
'effect_resolution_reason' => '',
'completion_event_id' => null,
'read_at' => null,
'dispatched_at' => $now - 980,
'lease_token' => null,
'lease_until' => 0,
'available_at' => 0,
'error_code' => 'operation_deadline_exceeded',
'finalization_incident' => 0,
'finalization_error_code' => null,
'result_json' => json_encode(
['cause_code' => 'operation_deadline_exceeded'],
JSON_THROW_ON_ERROR
),
'created_at' => $now - 1000,
'updated_at' => $now - 10,
]);
return [$id, $uuid];
};
$insertDispatchableJob = static function (
string $operationId
) use (&$nextId, $now): int {
$id = $nextId++;
Capsule::table('cloud_jobs')->insert([
'id' => $id,
'operation_id' => $operationId,
'request_idempotency_key' => $operationId,
'request_fingerprint' => hash('sha256', $operationId),
'parent_job_id' => null,
'order_id' => null,
'invoice_id' => null,
'instance_id' => null,
'snapshot_id' => null,
// A missing actor closes safely before dispatch. It keeps this
// fixture focused on the public worker scheduling seam rather
// than sharing an HTTP transport with system recovery.
'user_id' => 999,
'host_id' => 7,
'kind' => 'power_start',
'execution_mode' => 'agent',
'phase' => 'accepted',
'outcome' => null,
'status' => 'queued',
'sealed_payload' => CloudSecrets::encrypt([
'method' => 'POST',
'request_target' => '/v1/vms/'
. '00000000-0000-4000-8000-000000000999/start',
'body' => [],
'owner_id' => 999,
'can_manage' => false,
], 'job-payload'),
'attempts' => 0,
'dispatch_attempts' => 0,
'dispatch_deadline_at' => $now + 300,
'dispatch_started_at' => null,
'agent_accepted_at' => null,
'receipt_deadline_at' => null,
'terminal_at' => null,
'effect_may_have_applied' => null,
'safe_to_resubmit' => null,
'effect_resolution' => 'not_applicable',
'effect_resolved_at' => null,
'effect_resolved_by' => null,
'effect_resolution_reason' => '',
'completion_event_id' => null,
'read_at' => null,
'dispatched_at' => null,
'lease_token' => null,
'lease_until' => 0,
'available_at' => 0,
'error_code' => null,
'finalization_incident' => 0,
'finalization_error_code' => null,
'result_json' => null,
'created_at' => $now,
'updated_at' => $now,
]);
return $id;
};
$audit = static function (int $id): array {
$job = CloudJob::find($id);
return [
'operation_id' => (string) $job->operation_id,
'kind' => (string) $job->kind,
'phase' => (string) $job->phase,
'outcome' => (string) $job->outcome,
'status' => (string) $job->status,
'dispatch_attempts' => (int) $job->dispatch_attempts,
'effect_may_have_applied' =>
(bool) $job->effect_may_have_applied,
'safe_to_resubmit' => (bool) $job->safe_to_resubmit,
'error_code' => (string) $job->error_code,
'result_json' => $job->result_json,
'terminal_at' => (int) $job->terminal_at,
'completion_event_id' => $job->completion_event_id,
'read_at' => $job->read_at,
];
};
$inspection = static function (
string $operationId,
string $journalStatus,
string $resolution,
?array $projection = null,
?bool $fenceResolutionRequired = null,
?string $errorCode = null,
?string $fenceState = null
): array {
$applied = $resolution === 'applied';
$uncertain = in_array(
$resolution,
['partial', 'inconclusive'],
true
);
$value = [
'operation_id' => $operationId,
'operation_status' => $journalStatus,
'checked_at' => time(),
'outcome' => $uncertain
? 'uncertain' : ($applied ? 'succeeded' : 'failed'),
'summary_code' => $uncertain
? 'evidence_incomplete'
: ($applied ? 'operation_succeeded' : 'operation_failed'),
'effect_resolution' => $resolution,
'fence_resolution_required' => $fenceResolutionRequired
?? $journalStatus === 'failed',
'fence_state' => $fenceState ?? (($fenceResolutionRequired
?? $journalStatus === 'failed') ? 'active' : 'not_required'),
'abort_job' => ['available' => false],
'cleanup' => ['available' => false],
];
if ($projection !== null) {
$value['effect_projection'] = $projection;
}
if ($resolution === 'not_applied') {
$value['error_code'] = $errorCode ?? 'settings_not_committed';
}
return $value;
};
$notFound = static fn (): CloudAgentError => new CloudAgentError(
'not found', 404, 'fence_resolution_not_found', false, 404
);
$fenceResponse = static function (
array $request,
int $resolvedAt
): array {
$payload = $request['payload'];
return [
'operation_id' => $request['operationId'],
'resolution_id' => $payload['resolution_id'],
'resolution' => $payload['resolution'],
'inspection_checked_at' =>
$payload['inspection_checked_at'],
'reason_sha256' => $payload['reason_sha256'],
'resolved_at' => $resolvedAt,
'resolved_by' => 0,
'replayed' => false,
];
};
$client = new AutomaticRecoveryTestAgentClient();
CloudAgentSettingsService::$client = $client;
// The recovery worker is a kind-specific finalizer, not a generic way to
// clear unknown effects. A fully eligible non-settings task must remain
// byte-for-byte untouched and must not contact the Agent.
[$nonSettingsId] = $insertSettingsJob(
str_repeat('0f', 16),
['hostname' => 'not-a-settings-recovery.example']
);
Capsule::table('cloud_jobs')->where('id', $nonSettingsId)->update([
'kind' => 'network_change',
]);
$nonSettingsBefore = CloudJob::find($nonSettingsId)->getAttributes();
$beforeNonSettingsRequests = count($client->requests);
$assert(!(new CloudAutomaticOperationRecoveryService())->tick()
&& CloudJob::find($nonSettingsId)->getAttributes()
=== $nonSettingsBefore
&& count($client->requests) === $beforeNonSettingsRequests,
'The settings recovery worker claimed a different operation kind.');
// A journal success is immutable exact evidence and has no active fence.
[$succeededId, $succeededUuid] = $insertSettingsJob(
str_repeat('1', 32),
['root_password' => 'New-automatic9!Pass'],
[
'password' => 'New-automatic9!Pass',
'login_name' => 'root',
'auth_mode' => 'password',
]
);
$succeededAudit = $audit($succeededId);
$client->responses[] = $inspection(
str_repeat('1', 32),
'succeeded',
'applied',
[
'uuid' => $succeededUuid,
'status' => 'running',
'settings_changed' => true,
]
);
$dispatchId = $insertDispatchableJob(str_repeat('8', 32));
$beforeDispatchRequests = count($client->requests);
$assert((new CloudWorkerService())->tick(),
'The worker did not claim the ordinary dispatchable task first.');
$dispatch = CloudJob::find($dispatchId);
$unrecovered = CloudJob::find($succeededId);
$assert((string) $dispatch->phase === 'terminal'
&& (string) $dispatch->outcome === 'failed'
&& (int) $dispatch->dispatch_attempts === 0
&& (string) $unrecovered->effect_resolution === 'unknown'
&& count($client->requests) === $beforeDispatchRequests,
'Automatic recovery ran before an ordinary dispatchable task.');
$queuedBehindRecovery = $insertDispatchableJob(str_repeat('b', 32));
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The dedicated recovery service did not claim a recoverable task.');
$assert((string) CloudJob::find($queuedBehindRecovery)->phase
=== 'accepted',
'The dedicated recovery service consumed an ordinary task.');
$assert((new CloudWorkerService())->tick()
&& (string) CloudJob::find($queuedBehindRecovery)->phase
=== 'terminal',
'The ordinary worker did not keep processing its independent queue.');
$succeeded = CloudJob::find($succeededId);
$credential = CloudSecrets::decrypt(
(string) Capsule::table('cloud_instances')
->where('id', $succeededId)->value('sealed_credential'),
'instance-credential'
);
$redacted = CloudSecrets::decrypt(
(string) $succeeded->sealed_payload,
'job-payload'
);
$assert((string) $succeeded->effect_resolution === 'applied'
&& (int) $succeeded->effect_resolved_by === 0
&& $audit($succeededId) === $succeededAudit
&& ($credential['password'] ?? null)
=== 'New-automatic9!Pass'
&& !array_key_exists('credential', $redacted)
&& !CloudJobService::blockingQueryForInstance(
$succeededId
)->exists()
&& count($client->requests) === 1
&& str_ends_with($client->requests[0]['target'], '/inspect'),
'Journal-success recovery did not converge without a fence write.');
// Receipt proof is validated before comparing it with an existing
// automatic prepared marker. Otherwise a malformed success receipt would
// be misclassified as a conflict with sound automatic evidence.
$invalidProofRequests = count($client->requests);
$invalidProofCases = [
[
'operation_id' => str_repeat('c1', 16),
'body' => ['root_password' => 'Invalid-proof9!Pass'],
'credential' => [
'password' => 'Invalid-proof9!Pass',
'login_name' => 'root',
'auth_mode' => 'password',
],
'receipt_result' => [],
'message' => 'missing settings_changed proof',
],
[
'operation_id' => str_repeat('d2', 16),
'body' => ['hostname' => 'prepared-proof.example'],
'credential' => null,
'receipt_result' => [
'settings_changed' => true,
'hostname' => 'different-proof.example',
],
'message' => 'mismatched hostname proof',
],
];
foreach ($invalidProofCases as $index => $case) {
[$invalidProofId, $invalidProofUuid] = $insertSettingsJob(
$case['operation_id'],
$case['body'],
$case['credential']
);
Capsule::table('cloud_jobs')->where(
'id',
$invalidProofId
)->update([
'effect_resolution_reason' => 'automatic_recovery:v1:'
. time() . ':1:pending',
]);
$preparedResult = [
'uuid' => $invalidProofUuid,
'settings_changed' => true,
];
if (array_key_exists('hostname', $case['body'])) {
$preparedResult['hostname'] = $case['body']['hostname'];
}
CloudOperationRecoveryService::prepareApplied(
$invalidProofId,
[
'operation_id' => $case['operation_id'],
'status' => 'succeeded',
'effect_may_have_applied' => false,
'safe_to_resubmit' => false,
'error_code' => '',
'result' => $preparedResult,
],
'automatic_applied_succeeded_nofence:'
. str_repeat((string) ($index + 3), 64)
);
$preparedInvalidProof = CloudJob::find($invalidProofId);
$preparedMarker = (string) $preparedInvalidProof
->effect_resolution_reason;
$receiptResult = ['uuid' => $invalidProofUuid]
+ $case['receipt_result'];
$eventId = 'automatic-invalid-proof-' . ($index + 1);
$accepted = CloudOperationCompletionService::accept([
'type' => 'completion',
'id' => $eventId,
'agent_id' => '7',
'operation_id' => $case['operation_id'],
'status' => 'succeeded',
'effect_may_have_applied' => false,
'safe_to_resubmit' => false,
'error_code' => '',
'result' => $receiptResult,
]);
$invalidProofJob = CloudJob::find($invalidProofId);
$invalidProofEvent = Capsule::table(
'cloud_agent_completion_events'
)->where('event_id', $eventId)->first();
$assert($accepted === [
'accepted' => true,
'disposition' => 'late',
]
&& (string) $invalidProofJob->effect_resolution === 'unknown'
&& (string) $invalidProofJob->effect_resolution_reason
=== $preparedMarker
&& (bool) $invalidProofJob->finalization_incident
&& (string) $invalidProofJob->finalization_error_code
=== 'recovery_receipt_invalid'
&& (string) $invalidProofEvent->disposition === 'late'
&& CloudJobService::blockingQueryForInstance(
$invalidProofId
)->exists(),
'A success receipt with ' . $case['message']
. ' was not parked as invalid.');
}
$assert(count($client->requests) === $invalidProofRequests,
'Invalid late receipt proof unexpectedly contacted the Agent.');
// Failed journal + dual settings markers: prepare first, then resolve the
// fence. Simulate a lost POST response and prove one GET recovers it.
[$lostId, $lostUuid] = $insertSettingsJob(
str_repeat('2', 32),
['hostname' => 'recovered.example']
);
$lostAudit = $audit($lostId);
$lostFenceRequest = null;
$client->responses[] = $inspection(
str_repeat('2', 32),
'failed',
'applied',
[
'uuid' => $lostUuid,
'hostname' => 'recovered.example',
'status' => 'shutoff',
'settings_changed' => true,
]
);
$client->responses[] = $notFound();
$client->responses[] = static function (array $request) use (
&$lostFenceRequest
): Throwable {
$lostFenceRequest = $request;
return new RuntimeException('response lost after durable commit');
};
$client->responses[] = static function (array $request) use (
&$lostFenceRequest,
$fenceResponse
): array {
$read = $lostFenceRequest;
$read['method'] = $request['method'];
$read['target'] = $request['target'];
return $fenceResponse($read, time());
};
$beforeLostRequests = count($client->requests);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The worker did not recover a failed-journal applied task.');
$lost = CloudJob::find($lostId);
$lostSpec = json_decode(
(string) Capsule::table('cloud_instances')
->where('id', $lostId)->value('spec_json'),
true,
flags: JSON_THROW_ON_ERROR
);
$lostRequests = array_slice(
$client->requests,
$beforeLostRequests
);
$assert((string) $lost->effect_resolution === 'applied'
&& $audit($lostId) === $lostAudit
&& ($lostSpec['guest_hostname'] ?? null)
=== 'recovered.example'
&& count(array_filter(
$lostRequests,
static fn (array $request): bool =>
$request['method'] === 'POST'
)) === 1
&& count($lostRequests) === 4
&& !CloudJobService::blockingQueryForInstance($lostId)->exists(),
'Lost fence response recovery was not single-write and convergent.');
// Exact absence markers prove a settings request did not commit. PHP has
// no instance ledger delta, but still prepares before releasing the fence.
[$absentId] = $insertSettingsJob(
str_repeat('3', 32),
['hostname' => 'not-applied.example']
);
$absentAudit = $audit($absentId);
$absentSpec = (string) Capsule::table('cloud_instances')
->where('id', $absentId)->value('spec_json');
$client->responses[] = $inspection(
str_repeat('3', 32),
'failed',
'not_applied'
);
$client->responses[] = $notFound();
$client->responses[] = static fn (array $request): array =>
$fenceResponse($request, time());
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The worker did not converge exact not-applied evidence.');
$absent = CloudJob::find($absentId);
$assert((string) $absent->effect_resolution === 'not_applied'
&& (int) $absent->effect_resolved_by === 0
&& $audit($absentId) === $absentAudit
&& (string) Capsule::table('cloud_instances')
->where('id', $absentId)->value('spec_json') === $absentSpec
&& !CloudJobService::blockingQueryForInstance($absentId)->exists(),
'Not-applied recovery changed the ledger or retained its blocker.');
// An immutable failed Journal row which explicitly records no possible
// effect has no Agent fence. Its bounded original error code is evidence,
// not a reason to invent a settings_not_committed fence marker.
[$exactAbsentId] = $insertSettingsJob(
str_repeat('9', 32),
['hostname' => 'exact-not-applied.example']
);
$exactAbsentAudit = $audit($exactAbsentId);
$client->responses[] = $inspection(
str_repeat('9', 32),
'failed',
'not_applied',
null,
false,
'cloudinit_validation_failed'
);
$beforeExactAbsent = count($client->requests);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The worker did not converge exact no-effect Journal evidence.');
$exactAbsentRequests = array_slice(
$client->requests,
$beforeExactAbsent
);
$exactAbsent = CloudJob::find($exactAbsentId);
$assert((string) $exactAbsent->effect_resolution === 'not_applied'
&& $audit($exactAbsentId) === $exactAbsentAudit
&& !CloudJobService::blockingQueryForInstance(
$exactAbsentId
)->exists()
&& count($exactAbsentRequests) === 1
&& $exactAbsentRequests[0]['method'] === 'GET'
&& str_ends_with($exactAbsentRequests[0]['target'], '/inspect'),
'Exact no-effect Journal recovery contacted a fence endpoint.');
// A Journal fence already resolved outside this coordinator is not the
// same thing as an operation which never needed a fence. Without PHP's
// matching durable prepare marker, automatic recovery must not accept the
// possibly conflicting Agent verdict.
[$externallyResolvedId] = $insertSettingsJob(
str_repeat('a', 32),
['hostname' => 'externally-resolved.example']
);
$client->responses[] = $inspection(
str_repeat('a', 32),
'failed',
'not_applied',
null,
false,
'settings_not_committed',
'resolved'
);
$beforeExternallyResolved = count($client->requests);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The externally resolved fence was not inspected.');
$externallyResolved = CloudJob::find($externallyResolvedId);
$externallyResolvedRequests = array_slice(
$client->requests,
$beforeExternallyResolved
);
$assert((string) $externallyResolved->effect_resolution === 'unknown'
&& (int) $externallyResolved->available_at >= time() + 590
&& CloudJobService::blockingQueryForInstance(
$externallyResolvedId
)->exists()
&& count($externallyResolvedRequests) === 1
&& str_ends_with(
$externallyResolvedRequests[0]['target'],
'/inspect'
),
'An unprepared externally resolved fence bypassed PHP recovery intent.');
// Partial and inconclusive evidence stay blocked and receive a 10-minute
// retry delay. Two tasks also prove each worker tick handles only one.
[$partialId] = $insertSettingsJob(
str_repeat('4', 32),
['hostname' => 'partial.example']
);
[$inconclusiveId] = $insertSettingsJob(
str_repeat('5', 32),
['hostname' => 'inconclusive.example']
);
$client->responses[] = $inspection(
str_repeat('4', 32),
'failed',
'partial'
);
$client->responses[] = $inspection(
str_repeat('5', 32),
'failed',
'inconclusive'
);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The partial-evidence task was not inspected.');
$partial = CloudJob::find($partialId);
$notYetClaimed = CloudJob::find($inconclusiveId);
$assert((string) $partial->effect_resolution === 'unknown'
&& (int) $partial->available_at >= time() + 590
&& CloudJobService::blockingQueryForInstance($partialId)->exists()
&& (int) $notYetClaimed->available_at === 0,
'One worker tick did not stop after one inconclusive recovery.');
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The inconclusive-evidence task was not inspected.');
$inconclusive = CloudJob::find($inconclusiveId);
$assert((string) $inconclusive->effect_resolution === 'unknown'
&& (int) $inconclusive->available_at >= time() + 590
&& CloudJobService::blockingQueryForInstance(
$inconclusiveId
)->exists(),
'Inconclusive evidence released its blocker or hot-looped.');
// Agent downtime backs off without changing the immutable task outcome.
[$offlineId] = $insertSettingsJob(
str_repeat('6', 32),
['hostname' => 'offline.example']
);
$offlineAudit = $audit($offlineId);
$client->responses[] = new CloudAgentError(
'offline', 503, 'agent_unavailable', true, 503
);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The offline recovery task was not claimed.');
$offline = CloudJob::find($offlineId);
$assert((string) $offline->effect_resolution === 'unknown'
&& $audit($offlineId) === $offlineAudit
&& $offline->lease_token === null
&& (int) $offline->available_at >= time() + 290
&& CloudJobService::blockingQueryForInstance($offlineId)->exists(),
'Agent downtime changed audit state or did not back off.');
// A retried low-ID offline host must not repeatedly jump ahead of a
// never-attempted higher-ID task. Persisted available_at age, then ID,
// defines the recovery queue order.
Capsule::table('cloud_jobs')->where('id', $offlineId)->update([
'available_at' => time() - 1,
'lease_until' => 0,
'lease_token' => null,
]);
[$fairId, $fairUuid] = $insertSettingsJob(
str_repeat('d', 32),
['hostname' => 'fair-queue.example']
);
$client->responses[] = $inspection(
str_repeat('d', 32),
'succeeded',
'applied',
[
'uuid' => $fairUuid,
'hostname' => 'fair-queue.example',
'settings_changed' => true,
]
);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The recovery queue did not claim a fair successor.');
$assert((string) CloudJob::find($fairId)->effect_resolution === 'applied'
&& (string) CloudJob::find($offlineId)->effect_resolution === 'unknown',
'A retried low-ID offline task starved a never-attempted task.');
Capsule::table('cloud_jobs')->where('id', $offlineId)->update([
'available_at' => time() + 300,
]);
// Automatic read-only recovery has the same durable 12-attempt / six-hour
// safety bound as other reconciliation loops. Once exhausted it must stop
// contacting the Agent while preserving both the blocker and escrow.
[$limitedId] = $insertSettingsJob(
str_repeat('c', 32),
['hostname' => 'retry-limit.example']
);
$beforeLimitedRequests = count($client->requests);
for ($attempt = 1; $attempt <= 12; $attempt++) {
Capsule::table('cloud_jobs')->where('id', $limitedId)->update([
'available_at' => 0,
'lease_until' => 0,
'lease_token' => null,
]);
$client->responses[] = new CloudAgentError(
'offline', 503, 'agent_unavailable', true, 503
);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'A bounded recovery attempt was not claimed.');
}
$limited = CloudJob::find($limitedId);
$limitedPayloadBefore = (string) $limited->sealed_payload;
$limitedRequestCount = count($client->requests);
$assert((bool) $limited->finalization_incident
&& (string) $limited->finalization_error_code
=== 'recovery_limit_reached'
&& preg_match(
'/^automatic_recovery:v1:[1-9][0-9]{0,10}:12:pending$/D',
(string) $limited->effect_resolution_reason
) === 1
&& (string) $limited->effect_resolution === 'unknown'
&& (string) $limited->sealed_payload === $limitedPayloadBefore
&& CloudJobService::blockingQueryForInstance($limitedId)->exists()
&& $limitedRequestCount - $beforeLimitedRequests === 12,
'Recovery exhaustion did not stop safely with durable audit state.');
$assert(!(new CloudAutomaticOperationRecoveryService())->tick()
&& count($client->requests) === $limitedRequestCount,
'An exhausted recovery continued contacting the Agent.');
// First pass prepares PHP, commits the Agent fence, then loses both the
// POST response and its verification GET. A later pass must read that
// existing fence and commit PHP without depending on a new host inspect.
[$crashId, $crashUuid] = $insertSettingsJob(
str_repeat('7', 32),
['hostname' => 'crash-recovered.example']
);
Capsule::table('cloud_jobs')->where('id', $crashId)->update([
// The pending inspection budget is about to expire. A successful
// prepare must start a separate crash-resume budget instead of
// stranding the durable intent at attempt 12.
'effect_resolution_reason' => 'automatic_recovery:v1:'
. (time() - 300) . ':11:pending',
]);
$crashInspection = $inspection(
str_repeat('7', 32),
'failed',
'applied',
[
'uuid' => $crashUuid,
'hostname' => 'crash-recovered.example',
'settings_changed' => true,
]
);
$client->responses[] = $crashInspection;
$client->responses[] = $notFound();
$crashFenceRequest = null;
$client->responses[] = static function (array $request) use (
&$crashFenceRequest
): Throwable {
$crashFenceRequest = $request;
return new RuntimeException('fence committed before response loss');
};
$client->responses[] = new CloudAgentError(
'verification read offline', 503, 'agent_unavailable', true, 503
);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The crash-window fixture was not prepared.');
$prepared = CloudJob::find($crashId);
$assert(str_starts_with(
(string) $prepared->effect_resolution_reason,
'automatic_recovery:v1:'
)
&& preg_match(
'/^automatic_recovery:v1:[1-9][0-9]{0,10}:1:prepared:/D',
(string) $prepared->effect_resolution_reason
) === 1
&& str_contains(
(string) $prepared->effect_resolution_reason,
':prepared:automatic_applied_failed_fence:'
)
&& (string) $prepared->effect_resolution === 'unknown'
&& CloudJobService::blockingQueryForInstance($crashId)->exists(),
'Prepare failure window did not retain its blocker and intent.');
Capsule::table('cloud_jobs')->where('id', $crashId)->update([
'available_at' => 0,
'lease_until' => 0,
'lease_token' => null,
]);
$client->responses[] = static function (array $request) use (
&$crashFenceRequest,
$fenceResponse
): array {
$read = $crashFenceRequest;
$read['method'] = $request['method'];
$read['target'] = $request['target'];
return $fenceResponse($read, time());
};
$beforeCrashRetry = count($client->requests);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'Prepared recovery did not resume after the crash window.');
$crashRetryRequests = array_slice(
$client->requests,
$beforeCrashRetry
);
$assert((string) CloudJob::find($crashId)->effect_resolution === 'applied'
&& count(array_filter(
$crashRetryRequests,
static fn (array $request): bool =>
$request['method'] === 'POST'
)) === 0
&& !CloudJobService::blockingQueryForInstance($crashId)->exists()
&& count($crashRetryRequests) === 1
&& str_ends_with(
$crashRetryRequests[0]['target'],
'/fence-resolution'
),
'Prepared recovery re-inspected/replayed or failed to commit.');
// The prepared crash-resume stage is independently bounded. If its
// Agent fence read remains unavailable for all 12 attempts, automatic
// network traffic stops while the blocker, escrow and prepared intent
// remain available for a later exact receipt or explicit repair.
[$preparedLimitId] = $insertSettingsJob(
str_repeat('e', 32),
['hostname' => 'prepared-limit.example']
);
$client->responses[] = $inspection(
str_repeat('e', 32),
'failed',
'not_applied'
);
$client->responses[] = $notFound();
$client->responses[] = new RuntimeException(
'fence response lost before verification'
);
$client->responses[] = new CloudAgentError(
'verification read offline',
503,
'agent_unavailable',
true,
503
);
$beforePreparedLimit = count($client->requests);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'The prepared-limit fixture did not enter its resume stage.');
$preparedLimitFirst = CloudJob::find($preparedLimitId);
$assert(preg_match(
'/^automatic_recovery:v1:[1-9][0-9]{0,10}:1:prepared:automatic_not_applied_failed_fence:/D',
(string) $preparedLimitFirst->effect_resolution_reason
) === 1,
'Preparing did not reset the independent resume budget.');
for ($attempt = 2; $attempt <= 12; $attempt++) {
Capsule::table('cloud_jobs')->where('id', $preparedLimitId)->update([
'available_at' => 0,
'lease_until' => 0,
'lease_token' => null,
]);
$client->responses[] = new CloudAgentError(
'prepared fence read offline',
503,
'agent_unavailable',
true,
503
);
$assert((new CloudAutomaticOperationRecoveryService())->tick(),
'A bounded prepared-resume attempt was not claimed.');
}
$preparedLimited = CloudJob::find($preparedLimitId);
$preparedLimitRequestCount = count($client->requests);
$preparedLimitPayload = (string) $preparedLimited->sealed_payload;
$assert((bool) $preparedLimited->finalization_incident
&& (string) $preparedLimited->finalization_error_code
=== 'recovery_limit_reached'
&& preg_match(
'/^automatic_recovery:v1:[1-9][0-9]{0,10}:12:prepared:/D',
(string) $preparedLimited->effect_resolution_reason
) === 1
&& (string) $preparedLimited->effect_resolution === 'unknown'
&& CloudJobService::blockingQueryForInstance(
$preparedLimitId
)->exists()
&& count($client->requests) - $beforePreparedLimit === 15,
'Prepared-resume exhaustion did not stop with durable safety state.');
$assert(!(new CloudAutomaticOperationRecoveryService())->tick()
&& count($client->requests) === $preparedLimitRequestCount
&& (string) CloudJob::find($preparedLimitId)->sealed_payload
=== $preparedLimitPayload,
'An exhausted prepared recovery continued contacting the Agent.');
// The wall-clock limit is independent of attempt count and is evaluated
// before any network call.
[$agedId] = $insertSettingsJob(
str_repeat('f', 32),
['hostname' => 'age-limit.example']
);
Capsule::table('cloud_jobs')->where('id', $agedId)->update([
'effect_resolution_reason' => 'automatic_recovery:v1:'
. (time() - 21601) . ':1:pending',
]);
$beforeAged = count($client->requests);
$assert(!(new CloudAutomaticOperationRecoveryService())->tick(),
'An aged recovery was unexpectedly claimed for network work.');
$aged = CloudJob::find($agedId);
$assert((bool) $aged->finalization_incident
&& (string) $aged->finalization_error_code
=== 'recovery_limit_reached'
&& (string) $aged->effect_resolution === 'unknown'
&& CloudJobService::blockingQueryForInstance($agedId)->exists()
&& count($client->requests) === $beforeAged,
'The wall-clock recovery bound contacted Agent or released safety.');
foreach ($client->requests as $request) {
$allowed = preg_match(
'#^/v1/operations/[a-f0-9]{32}/(?:inspect|fence-resolution|resolve-fence)$#D',
$request['target']
) === 1;
$assert($allowed
&& ($request['method'] === 'GET'
|| ($request['method'] === 'POST'
&& str_ends_with(
$request['target'],
'/resolve-fence'
))),
'Automatic recovery called an Agent mutation endpoint.');
}
echo "Cloud automatic operation recovery tests passed.\n";
}