fix(cloud): keep operation recovery identity-bound
parent
cf2cd70b6f
commit
0659a75b45
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Fail-closed interpretation of the immutable single-dispatch counter.
|
||||
*
|
||||
* Zero is the only proof that no Agent mutation crossed the dispatch boundary.
|
||||
* One is the only valid dispatched generation. Any other value is corruption:
|
||||
* callers must retain the resource fence and must not consume recovery proof
|
||||
* until an operator repairs the ledger.
|
||||
*/
|
||||
final class CloudDispatchLedger
|
||||
{
|
||||
public const CONFLICT_CODE = 'recovery_dispatch_ledger_conflict';
|
||||
private const REPAIR_INCIDENT_CODES = [
|
||||
self::CONFLICT_CODE,
|
||||
'recovery_dispatch_repair_completion_receipt_missing',
|
||||
'recovery_dispatch_repair_receipt_invalid',
|
||||
'recovery_dispatch_repair_aggregate_state_conflict',
|
||||
'recovery_dispatch_repair_payload_unavailable',
|
||||
'recovery_dispatch_repair_operation_identity_conflict',
|
||||
'recovery_dispatch_repair_evidence_conflict',
|
||||
'recovery_dispatch_repair_instance_state_conflict',
|
||||
'recovery_dispatch_repair_ledger_conflict',
|
||||
'recovery_dispatch_repair_internal_error',
|
||||
];
|
||||
|
||||
public static function attempts(object $job): int
|
||||
{
|
||||
$value = $job->dispatch_attempts ?? null;
|
||||
if (is_int($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (is_string($value)
|
||||
&& preg_match('/^-?[0-9]+$/D', $value) === 1) {
|
||||
return (int) $value;
|
||||
}
|
||||
// A missing, NULL or non-integral value is corruption rather than
|
||||
// evidence that the mutation never crossed the dispatch boundary.
|
||||
return PHP_INT_MIN;
|
||||
}
|
||||
|
||||
public static function isNeverDispatched(object $job): bool
|
||||
{
|
||||
return self::attempts($job) === 0;
|
||||
}
|
||||
|
||||
public static function isDispatched(object $job): bool
|
||||
{
|
||||
return self::attempts($job) === 1;
|
||||
}
|
||||
|
||||
public static function isInvalid(object $job): bool
|
||||
{
|
||||
return !in_array(self::attempts($job), [0, 1], true);
|
||||
}
|
||||
|
||||
/** Invalid non-zero state is conservatively treated as possibly sent. */
|
||||
public static function mayHaveDispatched(object $job): bool
|
||||
{
|
||||
return !self::isNeverDispatched($job);
|
||||
}
|
||||
|
||||
public static function assertValid(object $job): void
|
||||
{
|
||||
if (self::isInvalid($job)) {
|
||||
throw new CloudRecoveryDispatchLedgerConflict(
|
||||
'任务单次派发计数账本异常',
|
||||
409
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static function assertDispatched(object $job): void
|
||||
{
|
||||
self::assertValid($job);
|
||||
if (!self::isDispatched($job)) {
|
||||
throw new CloudError('任务没有跨越 Agent 派发边界', 409);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function repairIncidentCodes(): array
|
||||
{
|
||||
return self::REPAIR_INCIDENT_CODES;
|
||||
}
|
||||
|
||||
/**
|
||||
* A repaired counter remains sticky until the background coordinator has
|
||||
* revalidated the immutable terminal row. This closes the brief window in
|
||||
* which changing 2 to 0/1 could otherwise release the resource early.
|
||||
*/
|
||||
public static function hasRepairIncident(object $job): bool
|
||||
{
|
||||
return (string) ($job->execution_mode ?? '') === 'agent'
|
||||
&& (string) ($job->phase ?? '') === 'terminal'
|
||||
&& (bool) ($job->finalization_incident ?? false)
|
||||
&& in_array(
|
||||
(string) ($job->finalization_error_code ?? ''),
|
||||
self::REPAIR_INCIDENT_CODES,
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Allow-list of single-dispatch Agent leaf operations whose PHP ledgers may be
|
||||
* converged from immutable completion or operation-bound inspection evidence.
|
||||
*
|
||||
* Aggregate parents are deliberately absent: they never cross the Agent
|
||||
* dispatch boundary and must be recomputed from their recovered child jobs.
|
||||
*/
|
||||
final class CloudOperationRecoveryPolicy
|
||||
{
|
||||
private const AGENT_LEAF_KINDS = [
|
||||
'action',
|
||||
'reinstall',
|
||||
'rescue',
|
||||
'delete',
|
||||
'delete_force',
|
||||
'expiry_delete',
|
||||
'network_change',
|
||||
'instance_settings',
|
||||
'snapshot_create',
|
||||
'snapshot_restore',
|
||||
'snapshot_delete',
|
||||
'firewall_apply',
|
||||
'service_suspend',
|
||||
'network_suspend',
|
||||
'network_resume',
|
||||
'template_import_replica',
|
||||
'template_metadata_replica',
|
||||
'template_delete_replica',
|
||||
'rescue_template_import',
|
||||
'rescue_template_delete',
|
||||
'user_iso_import_replica',
|
||||
'user_iso_delete_replica',
|
||||
];
|
||||
|
||||
/** @return list<string> */
|
||||
public static function kinds(): array
|
||||
{
|
||||
return self::AGENT_LEAF_KINDS;
|
||||
}
|
||||
|
||||
public static function supports(string $kind): bool
|
||||
{
|
||||
return in_array($kind, self::AGENT_LEAF_KINDS, true);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** The aggregate parent/child ledger cannot safely publish a leaf verdict. */
|
||||
final class CloudRecoveryAggregateStateConflict extends CloudError
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** The single-dispatch ledger contains a value outside its 0/1 contract. */
|
||||
final class CloudRecoveryDispatchLedgerConflict extends CloudError
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** The current PHP-owned instance/resource ledger contradicts recovery input. */
|
||||
final class CloudRecoveryInstanceStateConflict extends CloudError
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** The Agent Journal identity does not name the exact PHP operation request. */
|
||||
final class CloudRecoveryOperationIdentityConflict extends CloudError
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** The encrypted recovery escrow is missing, unreadable, or incomplete. */
|
||||
final class CloudRecoveryPayloadUnavailable extends CloudError
|
||||
{
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026102005' scope='global'}
|
||||
{assign var=venix_asset_version value='2026102101' scope='global'}
|
||||
|
||||
@ -0,0 +1,650 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
/** Isolated encrypted envelope for Agent mutation identity 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 'agent-mutation-identity-test:' . $key;
|
||||
}
|
||||
|
||||
public static function decrypt(string $value, string $purpose): array
|
||||
{
|
||||
$key = substr(
|
||||
$value,
|
||||
strlen('agent-mutation-identity-test:')
|
||||
);
|
||||
if (!array_key_exists($key, self::$values)) {
|
||||
throw new \RuntimeException('Missing identity test payload.');
|
||||
}
|
||||
return self::$values[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudJob;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudOperationCompletionService;
|
||||
use App\Services\Cloud\CloudOperationRecoveryIdentity;
|
||||
use App\Services\Cloud\CloudOperationRecoveryPolicy;
|
||||
use App\Services\Cloud\CloudRecoveryOperationIdentityConflict;
|
||||
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);
|
||||
}
|
||||
};
|
||||
$expectCloudError = static function (
|
||||
callable $callback,
|
||||
int $status
|
||||
) use ($assert): void {
|
||||
try {
|
||||
$callback();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status,
|
||||
'Unexpected CloudError status.');
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException('Expected CloudError was not thrown.');
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection([
|
||||
'driver' => 'sqlite', 'database' => ':memory:',
|
||||
], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('cloud_jobs', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('host_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('snapshot_id')->nullable();
|
||||
$table->string('operation_id')->unique();
|
||||
$table->string('execution_mode');
|
||||
$table->string('kind');
|
||||
$table->string('phase');
|
||||
$table->string('outcome')->nullable();
|
||||
$table->string('status');
|
||||
$table->integer('dispatch_attempts')->default(1);
|
||||
$table->integer('terminal_at')->nullable();
|
||||
$table->boolean('effect_may_have_applied')->nullable();
|
||||
$table->boolean('safe_to_resubmit')->nullable();
|
||||
$table->string('effect_resolution')->default('not_applicable');
|
||||
$table->text('sealed_payload');
|
||||
$table->string('completion_event_id')->nullable();
|
||||
$table->boolean('finalization_incident')->default(0);
|
||||
$table->string('finalization_error_code')->nullable();
|
||||
$table->integer('read_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->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']);
|
||||
});
|
||||
$schema->create('cloud_host_storage_configurations',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('host_id')->primary();
|
||||
$table->integer('revision');
|
||||
foreach (['managed', 'template', 'seed', 'user_iso', 'rescue']
|
||||
as $role) {
|
||||
$table->text($role . '_directory');
|
||||
}
|
||||
$table->string('state');
|
||||
$table->string('operation_id')->nullable();
|
||||
$table->integer('job_id')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
|
||||
$now = time();
|
||||
$createBody = static function (string $operationId, int $suffix): array {
|
||||
return [
|
||||
'operation_id' => $operationId,
|
||||
'source' => 'cloud',
|
||||
'name' => 'identity-vm-' . $suffix,
|
||||
'vcpu' => 2,
|
||||
'memory_mib' => 2048,
|
||||
'disk_gib' => 40,
|
||||
'bandwidth_mbps' => 100,
|
||||
'network' => 'bridge:br0',
|
||||
'template_id' => 'debian-13',
|
||||
'template_revision' => 1,
|
||||
'template_generation_token' => str_repeat('1', 32),
|
||||
'root_password' => 'Identity-test9!Pass',
|
||||
'public_pool_key' => str_repeat('2', 32),
|
||||
'public_pool_cidr' => '203.0.113.0/24',
|
||||
'public_ip_cidr' => '203.0.113.' . $suffix . '/24',
|
||||
'gateway' => '203.0.113.1',
|
||||
'dns_servers' => ['1.1.1.1'],
|
||||
'platform_network_policy_snapshot' => ['schema_version' => 1],
|
||||
];
|
||||
};
|
||||
$insertCreate = static function (
|
||||
int $id,
|
||||
string $operationId
|
||||
) use ($createBody, $now): void {
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => $id,
|
||||
'host_id' => 7,
|
||||
'user_id' => 11,
|
||||
'order_id' => 1000 + $id,
|
||||
'operation_id' => $operationId,
|
||||
'execution_mode' => 'agent',
|
||||
'kind' => 'create',
|
||||
'phase' => 'awaiting_receipt',
|
||||
'outcome' => null,
|
||||
'status' => 'running',
|
||||
'dispatch_attempts' => 1,
|
||||
'effect_resolution' => 'not_applicable',
|
||||
'sealed_payload' => CloudSecrets::encrypt([
|
||||
'method' => 'POST',
|
||||
'request_target' => '/v1/vms',
|
||||
'body' => $createBody($operationId, 20 + $id),
|
||||
'credential' => [
|
||||
'password' => 'Identity-test9!Pass',
|
||||
'login_name' => 'root',
|
||||
'auth_mode' => 'password',
|
||||
],
|
||||
'template_metadata' => [
|
||||
'template_id' => 'debian-13',
|
||||
'os_source' => 'cloud_template',
|
||||
'os_name' => 'Debian 13',
|
||||
'login_name' => 'root',
|
||||
],
|
||||
], 'job-payload'),
|
||||
'created_at' => $now - 30,
|
||||
'updated_at' => $now - 10,
|
||||
]);
|
||||
};
|
||||
|
||||
$createOperation = str_repeat('1a', 16);
|
||||
$storageOperation = str_repeat('2b', 16);
|
||||
$invalidCreateOperation = str_repeat('3c', 16);
|
||||
$hashCreateOperation = str_repeat('4d', 16);
|
||||
$secretCreateOperation = str_repeat('5e', 16);
|
||||
$activeLedgerConflictOperation = str_repeat('6f', 16);
|
||||
$terminalLedgerConflictOperation = str_repeat('70', 16);
|
||||
$repairedDuringDeferOperation = str_repeat('81', 16);
|
||||
$insertCreate(1, $createOperation);
|
||||
$insertCreate(3, $invalidCreateOperation);
|
||||
$insertCreate(4, $hashCreateOperation);
|
||||
$insertCreate(5, $secretCreateOperation);
|
||||
$insertCreate(6, $activeLedgerConflictOperation);
|
||||
$insertCreate(7, $terminalLedgerConflictOperation);
|
||||
$insertCreate(8, $repairedDuringDeferOperation);
|
||||
$storageBody = [
|
||||
'operation_id' => $storageOperation,
|
||||
'managed_directory' => '/srv/virt/managed',
|
||||
'template_directory' => '/srv/virt/templates',
|
||||
'seed_directory' => '/srv/virt/seeds',
|
||||
'user_iso_directory' => '/srv/virt/user-isos',
|
||||
'rescue_directory' => '/srv/virt/rescue',
|
||||
];
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => 2,
|
||||
'host_id' => 8,
|
||||
'user_id' => 11,
|
||||
'operation_id' => $storageOperation,
|
||||
'execution_mode' => 'agent',
|
||||
'kind' => 'host_storage_configure',
|
||||
'phase' => 'dispatching',
|
||||
'outcome' => null,
|
||||
'status' => 'running',
|
||||
'dispatch_attempts' => 1,
|
||||
'effect_resolution' => 'not_applicable',
|
||||
'sealed_payload' => CloudSecrets::encrypt([
|
||||
'method' => 'POST',
|
||||
'request_target' => '/v1/storage/configuration',
|
||||
'body' => $storageBody,
|
||||
'owner_id' => 11,
|
||||
'can_manage' => true,
|
||||
'storage_revision' => 4,
|
||||
], 'job-payload'),
|
||||
'created_at' => $now - 30,
|
||||
'updated_at' => $now - 10,
|
||||
]);
|
||||
Capsule::table('cloud_host_storage_configurations')->insert([
|
||||
'host_id' => 8,
|
||||
'revision' => 4,
|
||||
'managed_directory' => $storageBody['managed_directory'],
|
||||
'template_directory' => $storageBody['template_directory'],
|
||||
'seed_directory' => $storageBody['seed_directory'],
|
||||
'user_iso_directory' => $storageBody['user_iso_directory'],
|
||||
'rescue_directory' => $storageBody['rescue_directory'],
|
||||
'state' => 'applying',
|
||||
'operation_id' => $storageOperation,
|
||||
'job_id' => 2,
|
||||
'created_at' => $now - 30,
|
||||
'updated_at' => $now - 10,
|
||||
]);
|
||||
|
||||
$createJob = CloudJob::findOrFail(1);
|
||||
$storageJob = CloudJob::findOrFail(2);
|
||||
$createIdentity = CloudOperationRecoveryIdentity::expected($createJob);
|
||||
$storageIdentity = CloudOperationRecoveryIdentity::expected($storageJob);
|
||||
$assert(CloudOperationRecoveryIdentity::supports('create')
|
||||
&& CloudOperationRecoveryIdentity::supports(
|
||||
'host_storage_configure'
|
||||
)
|
||||
&& !CloudOperationRecoveryPolicy::supports('create')
|
||||
&& !CloudOperationRecoveryPolicy::supports(
|
||||
'host_storage_configure'
|
||||
)
|
||||
&& $createIdentity['action'] === 'create-vm'
|
||||
&& preg_match(
|
||||
'/^[a-f0-9]{8}-[a-f0-9]{4}-5[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/D',
|
||||
$createIdentity['resource_id']
|
||||
) === 1
|
||||
&& $storageIdentity['action'] === 'configure-storage'
|
||||
&& $storageIdentity['resource_id'] === 'host-storage',
|
||||
'Agent identity support was incorrectly coupled to recovery policy.');
|
||||
|
||||
$operationForJob = new ReflectionMethod(
|
||||
CloudWorkerService::class,
|
||||
'operationForJob'
|
||||
);
|
||||
$validSync = [
|
||||
'operation_id' => $createOperation,
|
||||
'status' => 'succeeded',
|
||||
] + $createIdentity;
|
||||
$assert($operationForJob->invoke(null, $createJob, $validSync)
|
||||
=== $validSync,
|
||||
'A correctly bound synchronous create response was rejected.');
|
||||
$wrongSync = $validSync;
|
||||
$wrongSync['resource_id'] = 'different-create-resource';
|
||||
try {
|
||||
$operationForJob->invoke(null, $createJob, $wrongSync);
|
||||
throw new RuntimeException(
|
||||
'A cross-operation synchronous create response was accepted.'
|
||||
);
|
||||
} catch (CloudRecoveryOperationIdentityConflict $expected) {
|
||||
// Expected: no result from the mismatched response can reach ledgers.
|
||||
}
|
||||
$validStorageSync = [
|
||||
'operation_id' => $storageOperation,
|
||||
'status' => 'succeeded',
|
||||
] + $storageIdentity;
|
||||
$wrongStorageSync = $validStorageSync;
|
||||
$wrongStorageSync['request_fingerprint'] = str_repeat('f', 64);
|
||||
try {
|
||||
$operationForJob->invoke(null, $storageJob, $wrongStorageSync);
|
||||
throw new RuntimeException(
|
||||
'A cross-operation synchronous storage response was accepted.'
|
||||
);
|
||||
} catch (CloudRecoveryOperationIdentityConflict $expected) {
|
||||
// Expected.
|
||||
}
|
||||
|
||||
$receipt = static function (
|
||||
string $eventId,
|
||||
int $hostId,
|
||||
string $operationId,
|
||||
array $identity
|
||||
): array {
|
||||
return [
|
||||
'type' => 'completion',
|
||||
'id' => $eventId,
|
||||
'agent_id' => (string) $hostId,
|
||||
'operation_id' => $operationId,
|
||||
'action' => $identity['action'],
|
||||
'resource_id' => $identity['resource_id'],
|
||||
'request_fingerprint' => $identity['request_fingerprint'],
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => false,
|
||||
'safe_to_resubmit' => false,
|
||||
'error_code' => '',
|
||||
'result' => [],
|
||||
];
|
||||
};
|
||||
|
||||
// Completion ingestion may persist evidence for a corrupt dispatch
|
||||
// ledger, but it must not ACK/consume that evidence. Both an active task
|
||||
// and an apparently settled terminal task stay visibly repairable until
|
||||
// dispatch_attempts is restored to one of its only valid states (0/1).
|
||||
Capsule::table('cloud_jobs')->where('id', 6)->update([
|
||||
'dispatch_attempts' => 2,
|
||||
]);
|
||||
$activeLedgerConflictJob = CloudJob::findOrFail(6);
|
||||
$activeLedgerConflictReceipt = $receipt(
|
||||
'active-dispatch-ledger-conflict',
|
||||
7,
|
||||
$activeLedgerConflictOperation,
|
||||
CloudOperationRecoveryIdentity::expected(
|
||||
$activeLedgerConflictJob,
|
||||
true
|
||||
)
|
||||
);
|
||||
$activeLedgerConflictAccepted =
|
||||
CloudOperationCompletionService::accept(
|
||||
$activeLedgerConflictReceipt
|
||||
);
|
||||
$activeLedgerConflictJob->refresh();
|
||||
$activeLedgerConflictEvent = Capsule::table(
|
||||
'cloud_agent_completion_events'
|
||||
)->where(
|
||||
'event_id',
|
||||
$activeLedgerConflictReceipt['id']
|
||||
)->first();
|
||||
$assert($activeLedgerConflictAccepted === [
|
||||
'accepted' => true,
|
||||
'disposition' => 'received',
|
||||
]
|
||||
&& (string) $activeLedgerConflictJob->phase === 'terminal'
|
||||
&& (string) $activeLedgerConflictJob->outcome === 'failed'
|
||||
&& (bool) $activeLedgerConflictJob->effect_may_have_applied
|
||||
&& !(bool) $activeLedgerConflictJob->safe_to_resubmit
|
||||
&& (string) $activeLedgerConflictJob->effect_resolution === 'unknown'
|
||||
&& (bool) $activeLedgerConflictJob->finalization_incident
|
||||
&& (string) $activeLedgerConflictJob->finalization_error_code
|
||||
=== 'recovery_dispatch_ledger_conflict'
|
||||
&& (string) $activeLedgerConflictEvent->disposition === 'received'
|
||||
&& $activeLedgerConflictEvent->applied_at === null,
|
||||
'An active invalid dispatch ledger consumed its immutable completion: '
|
||||
. json_encode([
|
||||
'accepted' => $activeLedgerConflictAccepted,
|
||||
'job' => $activeLedgerConflictJob->toArray(),
|
||||
'event' => (array) $activeLedgerConflictEvent,
|
||||
], JSON_THROW_ON_ERROR));
|
||||
|
||||
$terminalLedgerConflictEventId =
|
||||
'terminal-dispatch-ledger-conflict';
|
||||
Capsule::table('cloud_jobs')->where('id', 7)->update([
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'dispatch_attempts' => 2,
|
||||
'terminal_at' => time(),
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'completion_event_id' => $terminalLedgerConflictEventId,
|
||||
]);
|
||||
$terminalLedgerConflictJob = CloudJob::findOrFail(7);
|
||||
$terminalLedgerConflictTerminalAt =
|
||||
(int) $terminalLedgerConflictJob->terminal_at;
|
||||
$terminalLedgerConflictReceipt = $receipt(
|
||||
$terminalLedgerConflictEventId,
|
||||
7,
|
||||
$terminalLedgerConflictOperation,
|
||||
CloudOperationRecoveryIdentity::expected(
|
||||
$terminalLedgerConflictJob,
|
||||
true
|
||||
)
|
||||
);
|
||||
$terminalLedgerConflictAccepted =
|
||||
CloudOperationCompletionService::accept(
|
||||
$terminalLedgerConflictReceipt
|
||||
);
|
||||
$terminalLedgerConflictJob->refresh();
|
||||
$terminalLedgerConflictEvent =
|
||||
\App\Models\CloudAgentCompletionEvent::where(
|
||||
'event_id',
|
||||
$terminalLedgerConflictEventId
|
||||
)->firstOrFail();
|
||||
$assert($terminalLedgerConflictAccepted === [
|
||||
'accepted' => true,
|
||||
'disposition' => 'received',
|
||||
]
|
||||
&& (string) $terminalLedgerConflictJob->phase === 'terminal'
|
||||
&& (string) $terminalLedgerConflictJob->outcome === 'succeeded'
|
||||
&& (string) $terminalLedgerConflictJob->status === 'succeeded'
|
||||
&& !(bool) $terminalLedgerConflictJob->effect_may_have_applied
|
||||
&& !(bool) $terminalLedgerConflictJob->safe_to_resubmit
|
||||
&& (string) $terminalLedgerConflictJob->effect_resolution === 'applied'
|
||||
&& $terminalLedgerConflictJob->error_code === null
|
||||
&& (int) $terminalLedgerConflictJob->terminal_at
|
||||
=== $terminalLedgerConflictTerminalAt
|
||||
&& (string) $terminalLedgerConflictJob->completion_event_id
|
||||
=== $terminalLedgerConflictEventId
|
||||
&& (bool) $terminalLedgerConflictJob->finalization_incident
|
||||
&& (string) $terminalLedgerConflictJob->finalization_error_code
|
||||
=== 'recovery_dispatch_ledger_conflict'
|
||||
&& (string) $terminalLedgerConflictEvent->disposition === 'received'
|
||||
&& $terminalLedgerConflictEvent->applied_at === null
|
||||
&& !CloudOperationCompletionService::settledTaskWithEvent(
|
||||
$terminalLedgerConflictJob,
|
||||
$terminalLedgerConflictEvent
|
||||
),
|
||||
'A terminal invalid dispatch ledger ACKed a received completion.');
|
||||
|
||||
// Simulate an operator repairing the counter after a worker observed the
|
||||
// invalid value but before deferDispatchLedgerConflict acquired its lock.
|
||||
// The repaired value must remain sticky until background validation.
|
||||
Capsule::table('cloud_jobs')->where('id', 8)->update([
|
||||
'dispatch_attempts' => 2,
|
||||
]);
|
||||
$repairedDuringDefer = CloudJob::findOrFail(8);
|
||||
Capsule::table('cloud_jobs')->where('id', 8)->update([
|
||||
'dispatch_attempts' => 1,
|
||||
]);
|
||||
CloudOperationCompletionService::deferDispatchLedgerConflict(
|
||||
$repairedDuringDefer
|
||||
);
|
||||
$repairedDuringDefer->refresh();
|
||||
$assert((int) $repairedDuringDefer->dispatch_attempts === 1
|
||||
&& (string) $repairedDuringDefer->phase === 'terminal'
|
||||
&& (string) $repairedDuringDefer->outcome === 'failed'
|
||||
&& (bool) $repairedDuringDefer->effect_may_have_applied
|
||||
&& (string) $repairedDuringDefer->effect_resolution === 'unknown'
|
||||
&& (bool) $repairedDuringDefer->finalization_incident
|
||||
&& (string) $repairedDuringDefer->finalization_error_code
|
||||
=== 'recovery_dispatch_ledger_conflict',
|
||||
'A lock-window dispatch repair bypassed the sticky safety incident.');
|
||||
|
||||
$wrongCreate = $receipt(
|
||||
'create-wrong-identity-event',
|
||||
7,
|
||||
$createOperation,
|
||||
$createIdentity
|
||||
);
|
||||
$wrongCreate['resource_id'] = 'different-create-resource';
|
||||
$createAccepted = CloudOperationCompletionService::accept($wrongCreate);
|
||||
$wrongStorage = $receipt(
|
||||
'storage-wrong-identity-event',
|
||||
8,
|
||||
$storageOperation,
|
||||
$storageIdentity
|
||||
);
|
||||
$wrongStorage['request_fingerprint'] = str_repeat('f', 64);
|
||||
$storageAccepted = CloudOperationCompletionService::accept($wrongStorage);
|
||||
$createAfterWrong = CloudJob::findOrFail(1);
|
||||
$storageAfterWrong = CloudJob::findOrFail(2);
|
||||
$assert($createAccepted === [
|
||||
'accepted' => true, 'disposition' => 'rejected',
|
||||
]
|
||||
&& $storageAccepted === [
|
||||
'accepted' => true, 'disposition' => 'rejected',
|
||||
]
|
||||
&& (string) $createAfterWrong->phase === 'awaiting_receipt'
|
||||
&& $createAfterWrong->outcome === null
|
||||
&& (string) $createAfterWrong->effect_resolution === 'not_applicable'
|
||||
&& (string) $storageAfterWrong->phase === 'dispatching'
|
||||
&& $storageAfterWrong->outcome === null
|
||||
&& (string) $storageAfterWrong->effect_resolution
|
||||
=== 'not_applicable'
|
||||
&& (string) Capsule::table('cloud_host_storage_configurations')
|
||||
->where('host_id', 8)->value('state') === 'applying',
|
||||
'A wrong identity bypassed create or storage deadline finalization.');
|
||||
|
||||
$invalidCreate = $receipt(
|
||||
'create-invalid-receipt-event',
|
||||
7,
|
||||
$invalidCreateOperation,
|
||||
CloudOperationRecoveryIdentity::expected(CloudJob::findOrFail(3))
|
||||
);
|
||||
unset($invalidCreate['action']);
|
||||
$expectCloudError(
|
||||
static fn () => CloudOperationCompletionService::accept(
|
||||
$invalidCreate
|
||||
),
|
||||
400
|
||||
);
|
||||
$invalidStorage = $receipt(
|
||||
'storage-invalid-receipt-event',
|
||||
8,
|
||||
$storageOperation,
|
||||
$storageIdentity
|
||||
);
|
||||
unset($invalidStorage['action']);
|
||||
$expectCloudError(
|
||||
static fn () => CloudOperationCompletionService::accept(
|
||||
$invalidStorage
|
||||
),
|
||||
400
|
||||
);
|
||||
$invalidCreateJob = CloudJob::findOrFail(3);
|
||||
$invalidStorageJob = CloudJob::findOrFail(2);
|
||||
$assert((string) $invalidCreateJob->phase === 'awaiting_receipt'
|
||||
&& $invalidCreateJob->outcome === null
|
||||
&& (bool) $invalidCreateJob->finalization_incident
|
||||
&& (string) $invalidCreateJob->finalization_error_code
|
||||
=== 'recovery_receipt_invalid'
|
||||
&& (string) $invalidStorageJob->phase === 'dispatching'
|
||||
&& $invalidStorageJob->outcome === null
|
||||
&& (bool) $invalidStorageJob->finalization_incident
|
||||
&& (string) $invalidStorageJob->finalization_error_code
|
||||
=== 'recovery_receipt_invalid'
|
||||
&& (string) Capsule::table('cloud_host_storage_configurations')
|
||||
->where('host_id', 8)->value('state') === 'applying',
|
||||
'An attributable invalid receipt bypassed create/storage finalizers.');
|
||||
|
||||
$hashIdentity = CloudOperationRecoveryIdentity::expected(
|
||||
CloudJob::findOrFail(4)
|
||||
);
|
||||
$hashReceipt = $receipt(
|
||||
'create-hash-conflict-event',
|
||||
7,
|
||||
$hashCreateOperation,
|
||||
$hashIdentity
|
||||
);
|
||||
Capsule::table('cloud_agent_completion_events')->insert([
|
||||
'event_id' => $hashReceipt['id'],
|
||||
'host_id' => 7,
|
||||
'operation_id' => $hashCreateOperation,
|
||||
'payload_sha256' => str_repeat('0', 64),
|
||||
'outcome' => 'failed',
|
||||
'effect_may_have_applied' => 1,
|
||||
'safe_to_resubmit' => 0,
|
||||
'error_code' => 'old_conflicting_receipt',
|
||||
'result_json' => null,
|
||||
'disposition' => 'rejected',
|
||||
'received_at' => $now - 5,
|
||||
'applied_at' => null,
|
||||
]);
|
||||
$expectCloudError(
|
||||
static fn () => CloudOperationCompletionService::accept($hashReceipt),
|
||||
409
|
||||
);
|
||||
$hashJob = CloudJob::findOrFail(4);
|
||||
$assert((string) $hashJob->phase === 'awaiting_receipt'
|
||||
&& $hashJob->outcome === null
|
||||
&& (bool) $hashJob->finalization_incident
|
||||
&& (string) $hashJob->finalization_error_code
|
||||
=== 'recovery_operation_identity_conflict',
|
||||
'A payload-hash conflict was invisible or bypassed create finalization.');
|
||||
|
||||
$secretReceipt = $receipt(
|
||||
'create-secret-result-event',
|
||||
7,
|
||||
$secretCreateOperation,
|
||||
CloudOperationRecoveryIdentity::expected(
|
||||
CloudJob::findOrFail(5),
|
||||
true
|
||||
)
|
||||
);
|
||||
$secretReceipt['result'] = [
|
||||
'vm' => ['ssh_private_key' => 'must-never-be-persisted'],
|
||||
];
|
||||
$expectCloudError(
|
||||
static fn () => CloudOperationCompletionService::accept(
|
||||
$secretReceipt
|
||||
),
|
||||
400
|
||||
);
|
||||
$secretJob = CloudJob::findOrFail(5);
|
||||
$assert(!Capsule::table('cloud_agent_completion_events')
|
||||
->where('event_id', $secretReceipt['id'])->exists()
|
||||
&& (string) $secretJob->phase === 'awaiting_receipt'
|
||||
&& $secretJob->outcome === null
|
||||
&& (bool) $secretJob->finalization_incident
|
||||
&& (string) $secretJob->finalization_error_code
|
||||
=== 'recovery_receipt_invalid',
|
||||
'A create completion secret was persisted or bypassed its finalizer.');
|
||||
|
||||
$unknownSecretCases = [
|
||||
'unknown-generated-password' => [
|
||||
'generatedPassword' => 'must-never-persist',
|
||||
],
|
||||
'unknown-root-password' => [
|
||||
'nested' => ['root-password' => 'must-never-persist'],
|
||||
],
|
||||
'unknown-access-token' => [
|
||||
'access_token' => 'must-never-persist',
|
||||
],
|
||||
'unknown-passphrase' => [
|
||||
'diskPassphrase' => 'must-never-persist',
|
||||
],
|
||||
'unknown-plain-token' => [
|
||||
'token' => 'must-never-persist',
|
||||
],
|
||||
];
|
||||
$unknownIndex = 0;
|
||||
foreach ($unknownSecretCases as $eventId => $secretResult) {
|
||||
$unknownIndex++;
|
||||
$unknownOperation = substr(hash(
|
||||
'sha256',
|
||||
'unknown-secret-operation:' . $unknownIndex
|
||||
), 0, 32);
|
||||
$unknownReceipt = $receipt(
|
||||
$eventId . '-event',
|
||||
77,
|
||||
$unknownOperation,
|
||||
$createIdentity
|
||||
);
|
||||
$unknownReceipt['result'] = $secretResult;
|
||||
$expectCloudError(
|
||||
static fn () => CloudOperationCompletionService::accept(
|
||||
$unknownReceipt
|
||||
),
|
||||
400
|
||||
);
|
||||
$assert(!Capsule::table('cloud_agent_completion_events')
|
||||
->where('event_id', $unknownReceipt['id'])->exists(),
|
||||
'An unknown-operation secret completion was persisted.');
|
||||
}
|
||||
|
||||
echo "Agent mutation identity binding tests passed.\n";
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,585 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudTemplate;
|
||||
use App\Models\CloudUserIso;
|
||||
use App\Models\CloudJob;
|
||||
use App\Services\Cloud\CloudDispatchLedger;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudJobService;
|
||||
use App\Services\Cloud\CloudTemplateCatalogService;
|
||||
use App\Services\Cloud\CloudUserIsoService;
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
foreach ([
|
||||
0 => false,
|
||||
1 => true,
|
||||
2 => true,
|
||||
-1 => true,
|
||||
] as $attempts => $mayHaveDispatched) {
|
||||
$job = (object) ['dispatch_attempts' => $attempts];
|
||||
$assert(
|
||||
CloudDispatchLedger::mayHaveDispatched($job) === $mayHaveDispatched,
|
||||
'The dispatch ledger did not treat only zero as proof of no dispatch.'
|
||||
);
|
||||
}
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection([
|
||||
'driver' => 'sqlite',
|
||||
'database' => ':memory:',
|
||||
], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$capsule->schema('default')->create(
|
||||
'cloud_jobs',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('operation_id')->default(
|
||||
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
|
||||
);
|
||||
$table->string('request_idempotency_key')->default(
|
||||
'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
|
||||
);
|
||||
$table->string('request_fingerprint')->default(
|
||||
'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'
|
||||
);
|
||||
$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')->default(1);
|
||||
$table->integer('host_id')->nullable();
|
||||
$table->string('kind')->default('template_import');
|
||||
$table->string('execution_mode')->default('aggregate');
|
||||
$table->integer('attempts')->default(0);
|
||||
$table->integer('dispatch_attempts');
|
||||
$table->integer('dispatch_deadline_at')->default(1);
|
||||
$table->integer('dispatch_started_at')->nullable();
|
||||
$table->integer('agent_accepted_at')->nullable();
|
||||
$table->integer('dispatched_at')->nullable();
|
||||
$table->integer('receipt_deadline_at')->nullable()->default(1);
|
||||
$table->string('phase');
|
||||
$table->string('outcome')->nullable();
|
||||
$table->string('status')->default('succeeded');
|
||||
$table->integer('terminal_at')->nullable()->default(1);
|
||||
$table->string('completion_event_id')->nullable();
|
||||
$table->boolean('effect_may_have_applied')->nullable();
|
||||
$table->boolean('safe_to_resubmit')->nullable();
|
||||
$table->string('effect_resolution');
|
||||
$table->string('error_code')->nullable();
|
||||
$table->text('result_json')->nullable();
|
||||
$table->boolean('finalization_incident')->default(0);
|
||||
$table->string('finalization_error_code')->nullable();
|
||||
}
|
||||
);
|
||||
|
||||
$agentEnvelope = [
|
||||
'host_id' => 7,
|
||||
'attempts' => 1,
|
||||
'dispatch_deadline_at' => 1,
|
||||
'dispatch_started_at' => 1,
|
||||
'agent_accepted_at' => 1,
|
||||
'dispatched_at' => 1,
|
||||
'receipt_deadline_at' => 1,
|
||||
'terminal_at' => 1,
|
||||
];
|
||||
$capsule->schema('default')->create(
|
||||
'cloud_templates',
|
||||
static function (Blueprint $table): void {
|
||||
$table->string('id')->primary();
|
||||
$table->integer('active_job_id')->nullable();
|
||||
}
|
||||
);
|
||||
$capsule->schema('default')->create(
|
||||
'cloud_user_isos',
|
||||
static function (Blueprint $table): void {
|
||||
$table->string('id')->primary();
|
||||
$table->integer('user_id');
|
||||
$table->integer('active_job_id')->nullable();
|
||||
}
|
||||
);
|
||||
|
||||
foreach ([
|
||||
[1, 0, 'terminal', 'succeeded', 'applied'],
|
||||
[2, 1, 'terminal', 'succeeded', 'applied'],
|
||||
[3, 2, 'terminal', 'succeeded', 'applied'],
|
||||
[4, -1, 'terminal', 'succeeded', 'applied'],
|
||||
[5, 1, 'awaiting_receipt', null, 'unknown'],
|
||||
] as [$id, $attempts, $phase, $outcome, $resolution]) {
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => $id,
|
||||
'parent_job_id' => null,
|
||||
'dispatch_attempts' => $attempts,
|
||||
'phase' => $phase,
|
||||
'outcome' => $outcome,
|
||||
'status' => $outcome ?? 'running',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => $resolution,
|
||||
]);
|
||||
}
|
||||
foreach ([1, 2] as $parentId) {
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
...$agentEnvelope,
|
||||
'id' => 100 + $parentId,
|
||||
'parent_job_id' => $parentId,
|
||||
'user_id' => 1,
|
||||
'kind' => 'template_import_replica',
|
||||
'execution_mode' => 'agent',
|
||||
'dispatch_attempts' => 1,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
}
|
||||
foreach ([
|
||||
[201, 0, 'terminal', 'succeeded', 'applied'],
|
||||
[202, 1, 'terminal', 'succeeded', 'applied'],
|
||||
[203, 2, 'terminal', 'succeeded', 'applied'],
|
||||
[204, -1, 'terminal', 'succeeded', 'applied'],
|
||||
[205, 1, 'awaiting_receipt', null, 'unknown'],
|
||||
] as [$id, $attempts, $phase, $outcome, $resolution]) {
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => $id,
|
||||
'parent_job_id' => null,
|
||||
'user_id' => 1,
|
||||
'kind' => 'user_iso_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'dispatch_attempts' => $attempts,
|
||||
'phase' => $phase,
|
||||
'outcome' => $outcome,
|
||||
'status' => $outcome ?? 'running',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => $resolution,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
}
|
||||
foreach ([201, 202] as $parentId) {
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
...$agentEnvelope,
|
||||
'id' => 100 + $parentId,
|
||||
'parent_job_id' => $parentId,
|
||||
'user_id' => 1,
|
||||
'kind' => 'user_iso_import_replica',
|
||||
'execution_mode' => 'agent',
|
||||
'dispatch_attempts' => 1,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
$invokeBoundary = static function (
|
||||
string $service,
|
||||
object $resource,
|
||||
bool $shouldBlock
|
||||
) use ($assert): void {
|
||||
$method = new ReflectionMethod($service, 'assertMutationBoundaryLocked');
|
||||
$jobId = (int) ($resource->active_job_id ?? 0);
|
||||
$parent = $jobId > 0 ? CloudJob::find($jobId) : null;
|
||||
$validKinds = $service === CloudTemplateCatalogService::class
|
||||
? ['template_import', 'template_metadata_sync', 'template_delete']
|
||||
: ['user_iso_import', 'user_iso_delete'];
|
||||
if ($parent === null
|
||||
|| (string) $parent->execution_mode !== 'aggregate'
|
||||
|| $parent->parent_job_id !== null
|
||||
|| !in_array((string) $parent->kind, $validKinds, true)) {
|
||||
$parent = null;
|
||||
}
|
||||
try {
|
||||
$method->invoke(null, $resource, $parent);
|
||||
} catch (CloudError $error) {
|
||||
$assert($shouldBlock && $error->httpStatus === 409,
|
||||
$service . ' rejected a valid settled job boundary.');
|
||||
return;
|
||||
}
|
||||
$assert(!$shouldBlock,
|
||||
$service . ' released an unsafe prior job boundary.');
|
||||
};
|
||||
|
||||
// This focused fixture intentionally has no replica tables. Exercise the
|
||||
// parent/child dispatch-ledger predicate directly; full catalog projection
|
||||
// ownership is covered by CloudCatalogActiveJobPointerRecoveryTest.
|
||||
$parentSafelySettled = static function (
|
||||
string $service,
|
||||
object $resource,
|
||||
int $jobId
|
||||
): bool {
|
||||
$method = new ReflectionMethod($service, 'aggregateParentSafelySettled');
|
||||
$parent = CloudJob::find($jobId);
|
||||
if ($parent === null) {
|
||||
return false;
|
||||
}
|
||||
return $service === CloudTemplateCatalogService::class
|
||||
? $method->invoke(null, $parent, false)
|
||||
: $method->invoke(null, $resource, $parent, false);
|
||||
};
|
||||
|
||||
foreach ([
|
||||
1 => false,
|
||||
2 => true,
|
||||
3 => true,
|
||||
4 => true,
|
||||
5 => true,
|
||||
999 => true,
|
||||
] as $jobId => $shouldBlock) {
|
||||
$template = new CloudTemplate();
|
||||
$template->active_job_id = $jobId;
|
||||
$assert(
|
||||
$parentSafelySettled(
|
||||
CloudTemplateCatalogService::class,
|
||||
$template,
|
||||
$jobId
|
||||
) === !$shouldBlock,
|
||||
'The template aggregate dispatch ledger boundary was misclassified.'
|
||||
);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
201 => false,
|
||||
202 => true,
|
||||
203 => true,
|
||||
204 => true,
|
||||
205 => true,
|
||||
999 => true,
|
||||
] as $jobId => $shouldBlock) {
|
||||
$iso = new CloudUserIso();
|
||||
$iso->active_job_id = $jobId;
|
||||
$iso->user_id = 1;
|
||||
$assert(
|
||||
$parentSafelySettled(
|
||||
CloudUserIsoService::class,
|
||||
$iso,
|
||||
$jobId
|
||||
) === !$shouldBlock,
|
||||
'The ISO aggregate dispatch ledger boundary was misclassified.'
|
||||
);
|
||||
}
|
||||
|
||||
// A fail-open aggregate parent may already say succeeded/applied while one of
|
||||
// its Agent children still needs recovery. Both template and ISO mutation
|
||||
// boundaries must follow the child fence rather than trusting the parent row.
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => 6,
|
||||
'parent_job_id' => null,
|
||||
'user_id' => 1,
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'dispatch_attempts' => 0,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
...$agentEnvelope,
|
||||
'id' => 106,
|
||||
'parent_job_id' => 6,
|
||||
'user_id' => 1,
|
||||
'kind' => 'template_import_replica',
|
||||
'execution_mode' => 'agent',
|
||||
'dispatch_attempts' => 2,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => 206,
|
||||
'parent_job_id' => null,
|
||||
'user_id' => 1,
|
||||
'kind' => 'user_iso_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'dispatch_attempts' => 0,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
...$agentEnvelope,
|
||||
'id' => 306,
|
||||
'parent_job_id' => 206,
|
||||
'user_id' => 1,
|
||||
'kind' => 'user_iso_import_replica',
|
||||
'execution_mode' => 'agent',
|
||||
'dispatch_attempts' => 2,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$failOpenTemplate = new CloudTemplate();
|
||||
$failOpenTemplate->active_job_id = 6;
|
||||
$failOpenIso = new CloudUserIso();
|
||||
$failOpenIso->active_job_id = 206;
|
||||
$failOpenIso->user_id = 1;
|
||||
$assertBothBoundaries = static function (bool $shouldBlock) use (
|
||||
$assert,
|
||||
$parentSafelySettled,
|
||||
$failOpenTemplate,
|
||||
$failOpenIso
|
||||
): void {
|
||||
$assert(
|
||||
$parentSafelySettled(
|
||||
CloudTemplateCatalogService::class,
|
||||
$failOpenTemplate,
|
||||
6
|
||||
) === !$shouldBlock,
|
||||
'The template child dispatch ledger boundary was misclassified.'
|
||||
);
|
||||
$assert(
|
||||
$parentSafelySettled(
|
||||
CloudUserIsoService::class,
|
||||
$failOpenIso,
|
||||
206
|
||||
) === !$shouldBlock,
|
||||
'The ISO child dispatch ledger boundary was misclassified.'
|
||||
);
|
||||
};
|
||||
$assertBothBoundaries(true);
|
||||
Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([
|
||||
'dispatch_attempts' => 1,
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_dispatch_ledger_conflict',
|
||||
]);
|
||||
$assertBothBoundaries(true);
|
||||
Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([
|
||||
'dispatch_attempts' => 0,
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_ledger_conflict',
|
||||
]);
|
||||
$assertBothBoundaries(true);
|
||||
Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([
|
||||
'dispatch_attempts' => 1,
|
||||
'effect_may_have_applied' => 1,
|
||||
'effect_resolution' => 'unknown',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$assertBothBoundaries(true);
|
||||
Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
]);
|
||||
$assertBothBoundaries(false);
|
||||
|
||||
// A settled-looking row is not a valid catalog boundary unless its active job
|
||||
// is the exact aggregate root for that resource type and identity, and exactly
|
||||
// one main record owns that job.
|
||||
foreach ([
|
||||
[20, 'user_iso_import', 1],
|
||||
[21, 'user_iso_import', 2],
|
||||
[22, 'template_import', 1],
|
||||
[23, 'user_iso_import', 1],
|
||||
] as [$id, $kind, $userId]) {
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => $id,
|
||||
'parent_job_id' => null,
|
||||
'user_id' => $userId,
|
||||
'kind' => $kind,
|
||||
'execution_mode' => 'aggregate',
|
||||
'dispatch_attempts' => 0,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 1,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
}
|
||||
Capsule::table('cloud_templates')->insert([
|
||||
['id' => 'wrong-kind-template', 'active_job_id' => 20],
|
||||
['id' => 'duplicate-template-a', 'active_job_id' => 22],
|
||||
['id' => 'duplicate-template-b', 'active_job_id' => 22],
|
||||
]);
|
||||
Capsule::table('cloud_user_isos')->insert([
|
||||
['id' => 'cross-user-iso', 'user_id' => 1, 'active_job_id' => 21],
|
||||
['id' => 'duplicate-iso-a', 'user_id' => 1, 'active_job_id' => 23],
|
||||
['id' => 'duplicate-iso-b', 'user_id' => 1, 'active_job_id' => 23],
|
||||
]);
|
||||
$invokeBoundary(
|
||||
CloudTemplateCatalogService::class,
|
||||
CloudTemplate::findOrFail('wrong-kind-template'),
|
||||
true
|
||||
);
|
||||
$invokeBoundary(
|
||||
CloudUserIsoService::class,
|
||||
CloudUserIso::findOrFail('cross-user-iso'),
|
||||
true
|
||||
);
|
||||
foreach (['duplicate-template-a', 'duplicate-template-b'] as $id) {
|
||||
$invokeBoundary(
|
||||
CloudTemplateCatalogService::class,
|
||||
CloudTemplate::findOrFail($id),
|
||||
true
|
||||
);
|
||||
}
|
||||
foreach (['duplicate-iso-a', 'duplicate-iso-b'] as $id) {
|
||||
$invokeBoundary(
|
||||
CloudUserIsoService::class,
|
||||
CloudUserIso::findOrFail($id),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
// The current receipt is still nonterminal while its catalog projection is
|
||||
// finalized. It is the sole allowed exception; sibling and current ledger
|
||||
// corruption remain blockers.
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => 7,
|
||||
'parent_job_id' => null,
|
||||
'user_id' => 1,
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'dispatch_attempts' => 0,
|
||||
'phase' => 'awaiting_receipt',
|
||||
'outcome' => null,
|
||||
'status' => 'running',
|
||||
'effect_may_have_applied' => null,
|
||||
'safe_to_resubmit' => null,
|
||||
'effect_resolution' => 'not_applicable',
|
||||
'terminal_at' => null,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
array_replace($agentEnvelope, [
|
||||
'id' => 107,
|
||||
'parent_job_id' => 7,
|
||||
'user_id' => 1,
|
||||
'kind' => 'template_import_replica',
|
||||
'execution_mode' => 'agent',
|
||||
'dispatch_attempts' => 1,
|
||||
'phase' => 'awaiting_receipt',
|
||||
'outcome' => null,
|
||||
'status' => 'running',
|
||||
'effect_may_have_applied' => null,
|
||||
'safe_to_resubmit' => null,
|
||||
'effect_resolution' => 'not_applicable',
|
||||
'terminal_at' => null,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]),
|
||||
array_replace($agentEnvelope, [
|
||||
'id' => 108,
|
||||
'parent_job_id' => 7,
|
||||
'user_id' => 1,
|
||||
'kind' => 'template_import_replica',
|
||||
'execution_mode' => 'agent',
|
||||
'dispatch_attempts' => 1,
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]),
|
||||
]);
|
||||
$settlingParent = CloudJob::findOrFail(7);
|
||||
$assert(
|
||||
!CloudJobService::aggregateParentRecoveryPending(
|
||||
$settlingParent,
|
||||
107
|
||||
)
|
||||
&& CloudJobService::aggregateParentRecoveryPending($settlingParent),
|
||||
'The normal completing child exception was not scoped to that child.'
|
||||
);
|
||||
Capsule::table('cloud_jobs')->where('id', 107)->update([
|
||||
'dispatch_attempts' => 2,
|
||||
]);
|
||||
$assert(CloudJobService::aggregateParentRecoveryPending(
|
||||
$settlingParent,
|
||||
107
|
||||
), 'A corrupt currently completing child bypassed the aggregate gate.');
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$templateSource = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudTemplateCatalogService.php'
|
||||
);
|
||||
$isoSource = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudUserIsoService.php'
|
||||
);
|
||||
$rescueImportSource = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudRescueTemplateImportService.php'
|
||||
);
|
||||
$rescueDeleteSource = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudRescueTemplateDeletionService.php'
|
||||
);
|
||||
|
||||
$assert(substr_count(
|
||||
$templateSource,
|
||||
'CloudDispatchLedger::mayHaveDispatched($child)'
|
||||
) === 1 && substr_count(
|
||||
$isoSource,
|
||||
'CloudDispatchLedger::mayHaveDispatched($child)'
|
||||
) === 1,
|
||||
'A catalog aggregate can still classify a corrupt child as undispatched.');
|
||||
$assert(substr_count(
|
||||
$isoSource,
|
||||
'self::assertMutationBoundaryLocked('
|
||||
) >= 2,
|
||||
'ISO import does not reuse the unresolved-child mutation boundary.');
|
||||
$assert(str_contains($rescueImportSource,
|
||||
'CloudDispatchLedger::isInvalid($job)')
|
||||
&& str_contains($rescueImportSource,
|
||||
'CloudJobService::hasResolvedTerminalStateConflict($job)')
|
||||
&& str_contains($rescueDeleteSource,
|
||||
'CloudDispatchLedger::isInvalid($job)')
|
||||
&& str_contains($rescueDeleteSource,
|
||||
'CloudJobService::hasResolvedTerminalStateConflict($job)')
|
||||
&& str_contains($rescueDeleteSource,
|
||||
'$priorJobId = (int) ($catalog->job_id ?? 0)'),
|
||||
'A rescue-template history boundary can release a corrupt prior job.');
|
||||
|
||||
echo "Catalog dispatch-ledger safety checks passed.\n";
|
||||
@ -0,0 +1,191 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$worker = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudWorkerService.php'
|
||||
);
|
||||
$recovery = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudOperationRecoveryService.php'
|
||||
);
|
||||
$automatic = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudAutomaticOperationRecoveryService.php'
|
||||
);
|
||||
$jobs = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudJobService.php'
|
||||
);
|
||||
$templates = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudTemplateCatalogService.php'
|
||||
);
|
||||
$isos = file_get_contents(
|
||||
$root . '/app/Services/Cloud/CloudUserIsoService.php'
|
||||
);
|
||||
if (!is_string($worker) || !is_string($recovery) || !is_string($automatic)
|
||||
|| !is_string($jobs)
|
||||
|| !is_string($templates) || !is_string($isos)) {
|
||||
throw new RuntimeException('Cannot read catalog lock-order sources.');
|
||||
}
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$method = static function (
|
||||
string $source,
|
||||
string $start,
|
||||
string $end
|
||||
): string {
|
||||
$from = strpos($source, $start);
|
||||
$to = $from === false ? false : strpos($source, $end, $from + 1);
|
||||
return $from === false || $to === false
|
||||
? '' : substr($source, $from, $to - $from);
|
||||
};
|
||||
$ordered = static function (
|
||||
string $source,
|
||||
array $needles
|
||||
): bool {
|
||||
$offset = -1;
|
||||
foreach ($needles as $needle) {
|
||||
$next = strpos($source, $needle, $offset + 1);
|
||||
if ($next === false || $next <= $offset) {
|
||||
return false;
|
||||
}
|
||||
$offset = $next;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
$finish = $method(
|
||||
$worker,
|
||||
'$aggregateParentId = (int) ($claimed->parent_job_id ?? 0);',
|
||||
'private static function throwInvalidSettingsResult('
|
||||
);
|
||||
$assert($ordered($finish, [
|
||||
"CloudJob::where('id', \$aggregateParentId)",
|
||||
'CloudTemplateCatalogService::lockAggregateCatalogLocked(',
|
||||
'CloudUserIsoService::lockAggregateCatalogLocked(',
|
||||
"CloudJob::where('id', \$claimed->id)",
|
||||
'CloudTemplateCatalogService::finishJobLocked(',
|
||||
]), 'Worker completion does not lock parent, catalog, child, replica in order.');
|
||||
|
||||
foreach (['commitApplied', 'commitNotApplied'] as $name) {
|
||||
$commit = $method(
|
||||
$recovery,
|
||||
'public static function ' . $name . '(',
|
||||
$name === 'commitApplied'
|
||||
? 'public static function prepareNotApplied('
|
||||
: 'private static function assertResolvedBy('
|
||||
);
|
||||
$assert($ordered($commit, [
|
||||
'$aggregateParent = CloudJob::where(',
|
||||
'$aggregateParentId',
|
||||
'CloudTemplateCatalogService::lockAggregateCatalogLocked(',
|
||||
'CloudUserIsoService::lockAggregateCatalogLocked(',
|
||||
"CloudJob::where('id', \$jobId)",
|
||||
]), $name . ' takes a child lock before its catalog lock.');
|
||||
}
|
||||
|
||||
$automaticCommit = $method(
|
||||
$automatic,
|
||||
'private static function resolveFenceAndCommit(',
|
||||
'private static function assertFreshInspection('
|
||||
);
|
||||
$assert($ordered($automaticCommit, [
|
||||
'$aggregateParent = CloudJob::where(',
|
||||
'$aggregateParentId',
|
||||
'CloudTemplateCatalogService::lockAggregateCatalogLocked(',
|
||||
'CloudUserIsoService::lockAggregateCatalogLocked(',
|
||||
"\$aggregateChildren = CloudJob::where(",
|
||||
"'parent_job_id',",
|
||||
'$aggregateParentId',
|
||||
]), 'Automatic fence commit locks the child before its catalog.');
|
||||
|
||||
$aggregateCommit = $method(
|
||||
$jobs,
|
||||
'public static function reconcileAggregateParentEffectLocked(',
|
||||
'private static function wherePublishedAggregateNeedsRecheck('
|
||||
);
|
||||
$assert($ordered($aggregateCommit, [
|
||||
"CloudJob::where('id', \$parentId)",
|
||||
'CloudTemplateCatalogService::lockAggregateCatalogLocked(',
|
||||
'CloudUserIsoService::lockAggregateCatalogLocked(',
|
||||
"\$children = CloudJob::where('parent_job_id', \$parentId)",
|
||||
]), 'Aggregate recovery commit locks children before the catalog.');
|
||||
|
||||
$legacy = $method(
|
||||
$jobs,
|
||||
'public static function reconcileOneLegacyAggregateEffect(): bool',
|
||||
'private static function aggregateRelationshipConflict('
|
||||
);
|
||||
$assert($ordered($legacy, [
|
||||
'->lockForUpdate()',
|
||||
'CloudTemplateCatalogService::lockAggregateCatalogLocked(',
|
||||
'CloudUserIsoService::lockAggregateCatalogLocked(',
|
||||
'$children = CloudJob::where(',
|
||||
"'parent_job_id',",
|
||||
]), 'Legacy aggregate sweep locks children before the catalog.');
|
||||
|
||||
$templateMutation = $method(
|
||||
$templates,
|
||||
'private static function lockTemplateForMutation(',
|
||||
'private static function assertMutationBoundaryLocked('
|
||||
);
|
||||
$isoMutation = $method(
|
||||
$isos,
|
||||
'private static function lockIsoForMutation(',
|
||||
'private static function assertMutationBoundaryLocked('
|
||||
);
|
||||
$assert($ordered($templateMutation, [
|
||||
'$parentSnapshot = $jobId > 0',
|
||||
'self::isTemplateAggregateParent($parentSnapshot)',
|
||||
"? CloudJob::where('id', \$jobId)",
|
||||
"->where('execution_mode', 'aggregate')",
|
||||
"->whereNull('parent_job_id')",
|
||||
'->lockForUpdate()->first()',
|
||||
'$template = CloudTemplate::query()',
|
||||
'->lockForUpdate()->first();',
|
||||
'self::assertMutationBoundaryLocked(',
|
||||
]), 'Template mutation still locks the catalog before its prior parent.');
|
||||
$assert($ordered($isoMutation, [
|
||||
'$parentSnapshot = $jobId > 0',
|
||||
'self::isIsoAggregateParent($parentSnapshot)',
|
||||
"? CloudJob::where('id', \$jobId)",
|
||||
"->where('execution_mode', 'aggregate')",
|
||||
"->whereNull('parent_job_id')",
|
||||
'->lockForUpdate()->first()',
|
||||
'$iso = CloudUserIso::query()',
|
||||
'->lockForUpdate()->first();',
|
||||
'self::assertMutationBoundaryLocked(',
|
||||
]), 'ISO mutation still locks the catalog before its prior parent.');
|
||||
|
||||
$isoImportMutation = $method(
|
||||
$isos,
|
||||
'private static function lockIsoRowsForImport(',
|
||||
'private static function assertMutationBoundaryLocked('
|
||||
);
|
||||
$assert($ordered($isoImportMutation, [
|
||||
'$parentSnapshots =',
|
||||
'$parentIds =',
|
||||
'self::isIsoAggregateParent($job)',
|
||||
'$parents =',
|
||||
"->where('execution_mode', 'aggregate')",
|
||||
"->whereNull('parent_job_id')",
|
||||
"->orderBy('id')->lockForUpdate()->get()->keyBy('id')",
|
||||
'$rows = CloudUserIso::query()',
|
||||
'->lockForUpdate()->get();',
|
||||
]), 'ISO import locks an invalid pointer or locks catalogs before parents.');
|
||||
|
||||
$templateDelete = $method(
|
||||
$templates,
|
||||
'public static function delete(',
|
||||
'public static function finishJobLocked('
|
||||
);
|
||||
$assert($ordered($templateDelete, [
|
||||
'self::assertNoOrderReferencesLocked($id);',
|
||||
'self::lockTemplateForMutation($id);',
|
||||
'self::assertNoJobReferencesLocked($id);',
|
||||
]), 'Template deletion locks its catalog before pending orders.');
|
||||
|
||||
echo "Cloud catalog lock-order contract checks passed.\n";
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,223 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
/** Isolated encrypted envelope used only by this focused contract test. */
|
||||
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 'operation-recovery-policy-test:' . $key;
|
||||
}
|
||||
|
||||
public static function decrypt(string $value, string $purpose): array
|
||||
{
|
||||
$key = substr(
|
||||
$value,
|
||||
strlen('operation-recovery-policy-test:')
|
||||
);
|
||||
if (!array_key_exists($key, self::$values)) {
|
||||
throw new \RuntimeException('Missing recovery policy payload.');
|
||||
}
|
||||
return self::$values[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudAgentCompletionEvent;
|
||||
use App\Models\CloudJob;
|
||||
use App\Services\Cloud\CloudAgentError;
|
||||
use App\Services\Cloud\CloudAutomaticOperationRecoveryService;
|
||||
use App\Services\Cloud\CloudOperationCompletionService;
|
||||
use App\Services\Cloud\CloudOperationRecoveryPolicy;
|
||||
use App\Services\Cloud\CloudOperationRecoveryService;
|
||||
use App\Services\Cloud\CloudRecoveryInstanceStateConflict;
|
||||
use App\Services\Cloud\CloudSecrets;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$expectedKinds = [
|
||||
'action',
|
||||
'reinstall',
|
||||
'rescue',
|
||||
'delete',
|
||||
'delete_force',
|
||||
'expiry_delete',
|
||||
'network_change',
|
||||
'instance_settings',
|
||||
'snapshot_create',
|
||||
'snapshot_restore',
|
||||
'snapshot_delete',
|
||||
'firewall_apply',
|
||||
'service_suspend',
|
||||
'network_suspend',
|
||||
'network_resume',
|
||||
'template_import_replica',
|
||||
'template_metadata_replica',
|
||||
'template_delete_replica',
|
||||
'rescue_template_import',
|
||||
'rescue_template_delete',
|
||||
'user_iso_import_replica',
|
||||
'user_iso_delete_replica',
|
||||
];
|
||||
$assert(CloudOperationRecoveryPolicy::kinds() === $expectedKinds,
|
||||
'The Agent leaf recovery policy changed without updating its contract.');
|
||||
$assert(count(CloudOperationRecoveryPolicy::kinds()) === 22,
|
||||
'The recovery policy contract must contain exactly 22 Agent leaf kinds.');
|
||||
foreach ($expectedKinds as $kind) {
|
||||
$assert(CloudOperationRecoveryPolicy::supports($kind),
|
||||
'The recovery policy omitted ' . $kind . '.');
|
||||
}
|
||||
foreach ([
|
||||
// Provisioning is finalized through its paid-order cleanup contract.
|
||||
'create',
|
||||
// Aggregate parents never cross the Agent dispatch boundary.
|
||||
'template_import', 'template_metadata_sync', 'template_delete',
|
||||
'user_iso_import', 'user_iso_delete',
|
||||
// Payments and host storage have independent reconciliation rules.
|
||||
'payment_create', 'host_storage_configure',
|
||||
] as $kind) {
|
||||
$assert(!CloudOperationRecoveryPolicy::supports($kind),
|
||||
'An aggregate or separately finalized kind entered leaf recovery: '
|
||||
. $kind);
|
||||
}
|
||||
|
||||
$attemptState = new ReflectionMethod(
|
||||
CloudOperationRecoveryService::class,
|
||||
'automaticRecoveryState'
|
||||
);
|
||||
$state = $attemptState->invoke(
|
||||
null,
|
||||
'automatic_recovery:v1:1700000000:13:pending'
|
||||
);
|
||||
$assert(is_array($state) && ($state['attempts'] ?? null) === 13,
|
||||
'A recovery marker was still capped at twelve attempts.');
|
||||
$saturated = $attemptState->invoke(
|
||||
null,
|
||||
'automatic_recovery:v1:1700000000:' . str_repeat('9', 80)
|
||||
. ':pending'
|
||||
);
|
||||
$assert(is_array($saturated)
|
||||
&& ($saturated['attempts'] ?? null) === PHP_INT_MAX,
|
||||
'A durable saturated recovery attempt counter was rejected.');
|
||||
|
||||
$errorCode = new ReflectionMethod(
|
||||
CloudAutomaticOperationRecoveryService::class,
|
||||
'recoveryErrorCode'
|
||||
);
|
||||
$assert($errorCode->invoke(null, new CloudAgentError(
|
||||
'invalid inspection', 502, 'agent_invalid_inspection', false, 200
|
||||
)) === 'recovery_evidence_invalid'
|
||||
&& $errorCode->invoke(
|
||||
null,
|
||||
new CloudRecoveryInstanceStateConflict('state conflict', 409)
|
||||
) === 'recovery_instance_state_conflict',
|
||||
'Concrete evidence/state anomalies collapsed into a generic retry code.');
|
||||
|
||||
$operationId = str_repeat('a', 32);
|
||||
$identity = [
|
||||
'action' => 'change-network',
|
||||
'resource_id' => '11111111-1111-4111-8111-111111111111',
|
||||
'request_fingerprint' => str_repeat('f', 64),
|
||||
];
|
||||
$job = new CloudJob();
|
||||
$job->operation_id = $operationId;
|
||||
$job->kind = 'network_change';
|
||||
$job->phase = 'terminal';
|
||||
$job->effect_resolution = 'not_applied';
|
||||
$job->sealed_payload = CloudSecrets::encrypt([
|
||||
'_operation_identity' => ['version' => 1] + $identity,
|
||||
], 'job-payload');
|
||||
$notApplied = new ReflectionMethod(
|
||||
CloudOperationRecoveryService::class,
|
||||
'assertNotAppliedOperationIdentity'
|
||||
);
|
||||
$notApplied->invoke(null, $job, [
|
||||
'operation_id' => $operationId,
|
||||
'status' => 'failed',
|
||||
'effect_may_have_applied' => false,
|
||||
'safe_to_resubmit' => true,
|
||||
'error_code' => 'network_not_committed',
|
||||
'result' => null,
|
||||
] + $identity);
|
||||
|
||||
$event = new CloudAgentCompletionEvent();
|
||||
$event->operation_id = $operationId;
|
||||
$event->outcome = 'failed';
|
||||
$event->effect_may_have_applied = 0;
|
||||
$event->safe_to_resubmit = 1;
|
||||
$event->error_code = 'network_not_committed';
|
||||
$event->result_json = json_encode([
|
||||
'schema' => 'virt_cloud_completion_event',
|
||||
'version' => 1,
|
||||
'identity' => $identity,
|
||||
'result' => ['public_ip_cidr' => '203.0.113.10/24'],
|
||||
], JSON_THROW_ON_ERROR);
|
||||
$lateOperation = new ReflectionMethod(
|
||||
CloudOperationRecoveryService::class,
|
||||
'lateReceiptOperation'
|
||||
);
|
||||
$rebuilt = $lateOperation->invoke(null, $job, $event, 'not_applied');
|
||||
$assert($rebuilt === CloudOperationCompletionService::operation($event)
|
||||
&& ($rebuilt['safe_to_resubmit'] ?? null) === true
|
||||
&& ($rebuilt['error_code'] ?? null) === 'network_not_committed',
|
||||
'Late receipt recovery replaced the exact kind-specific Agent result.');
|
||||
|
||||
$preparedMarker = new ReflectionMethod(
|
||||
CloudOperationRecoveryService::class,
|
||||
'preparedMarker'
|
||||
);
|
||||
$baseOperation = [
|
||||
'operation_id' => $operationId,
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => false,
|
||||
'safe_to_resubmit' => false,
|
||||
'error_code' => '',
|
||||
'result' => ['snapshot_key' => str_repeat('b', 32), 'deleted' => true],
|
||||
];
|
||||
$otherOperation = $baseOperation;
|
||||
$otherOperation['result']['snapshot_key'] = str_repeat('c', 32);
|
||||
$source = 'automatic_applied_succeeded_nofence:' . str_repeat('d', 64);
|
||||
$assert($preparedMarker->invoke(null, $baseOperation, $source)
|
||||
!== $preparedMarker->invoke(null, $otherOperation, $source),
|
||||
'Prepared evidence ignored a non-settings ledger result field.');
|
||||
|
||||
$payloadJob = new CloudJob();
|
||||
$payloadJob->kind = 'network_change';
|
||||
$payloadJob->phase = 'terminal';
|
||||
$payloadJob->effect_resolution = 'applied';
|
||||
$payloadJob->sealed_payload = CloudSecrets::encrypt([
|
||||
'body' => ['hostname' => 'vm.example'],
|
||||
'credential' => ['password' => 'never-persist'],
|
||||
'_operation_identity' => ['version' => 1] + $identity,
|
||||
'_operation_recovery' => [
|
||||
'operation' => $baseOperation,
|
||||
'resolution' => 'applied',
|
||||
],
|
||||
], 'job-payload');
|
||||
$finalizedPayload = new ReflectionMethod(
|
||||
CloudOperationRecoveryService::class,
|
||||
'finalizedRecoveryPayload'
|
||||
);
|
||||
$clean = CloudSecrets::decrypt(
|
||||
$finalizedPayload->invoke(null, $payloadJob),
|
||||
'job-payload'
|
||||
);
|
||||
$assert(!array_key_exists('_operation_recovery', $clean)
|
||||
&& !array_key_exists('credential', $clean)
|
||||
&& ($clean['body']['hostname'] ?? null) === 'vm.example',
|
||||
'Recovery commit retained prepared evidence or a credential.');
|
||||
|
||||
echo "Cloud operation recovery policy contract passed.\n";
|
||||
}
|
||||
@ -0,0 +1,550 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
/** Isolated encrypted payload store for this SQLite contract test. */
|
||||
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 'rescue-template-retry-test:' . $key;
|
||||
}
|
||||
|
||||
public static function decrypt(string $value, string $purpose): array
|
||||
{
|
||||
$key = substr($value, strlen('rescue-template-retry-test:'));
|
||||
if (!array_key_exists($key, self::$values)) {
|
||||
throw new \RuntimeException('Missing test payload.');
|
||||
}
|
||||
return self::$values[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudJob;
|
||||
use App\Models\CloudRescueTemplateDeletion;
|
||||
use App\Models\CloudRescueTemplateImport;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudRescueTemplateDeletionService;
|
||||
use App\Services\Cloud\CloudRescueTemplateImportService;
|
||||
use App\Services\Cloud\CloudSecrets;
|
||||
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();
|
||||
|
||||
$capsule->schema('default')->create(
|
||||
'cloud_jobs',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('operation_id');
|
||||
$table->string('request_idempotency_key');
|
||||
$table->string('request_fingerprint', 64);
|
||||
$table->integer('parent_job_id')->nullable();
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('invoice_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->integer('attempts')->default(0);
|
||||
$table->integer('dispatch_attempts')->default(0);
|
||||
$table->integer('dispatch_deadline_at')->nullable();
|
||||
$table->integer('dispatch_started_at')->nullable();
|
||||
$table->integer('dispatched_at')->nullable();
|
||||
$table->integer('agent_accepted_at')->nullable();
|
||||
$table->integer('receipt_deadline_at')->nullable();
|
||||
$table->text('sealed_payload');
|
||||
$table->text('result_json')->nullable();
|
||||
$table->string('error_code')->nullable();
|
||||
$table->text('error_message')->nullable();
|
||||
$table->string('lease_token')->nullable();
|
||||
$table->integer('lease_until')->default(0);
|
||||
$table->integer('available_at')->default(0);
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
$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->boolean('finalization_incident')->default(0);
|
||||
$table->string('finalization_error_code')->nullable();
|
||||
$table->string('completion_event_id')->nullable();
|
||||
$table->integer('read_at')->nullable();
|
||||
}
|
||||
);
|
||||
$capsule->schema('default')->create(
|
||||
'cloud_rescue_template_imports',
|
||||
static function (Blueprint $table): void {
|
||||
$table->string('operation_id')->primary();
|
||||
$table->integer('host_id');
|
||||
$table->string('template_id', 32);
|
||||
$table->integer('job_id');
|
||||
$table->string('import_type');
|
||||
$table->string('name');
|
||||
$table->integer('size_bytes')->default(0);
|
||||
$table->string('sha256', 64)->default('');
|
||||
$table->string('state');
|
||||
$table->string('error_code')->default('');
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
}
|
||||
);
|
||||
$capsule->schema('default')->create(
|
||||
'cloud_rescue_template_deletions',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('host_id');
|
||||
$table->string('template_id', 32);
|
||||
$table->string('operation_id');
|
||||
$table->integer('job_id');
|
||||
$table->string('state');
|
||||
$table->string('error_code')->default('');
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
$table->primary(['host_id', 'template_id']);
|
||||
}
|
||||
);
|
||||
|
||||
$now = time();
|
||||
$actor = [
|
||||
'user_id' => 1,
|
||||
'is_admin' => true,
|
||||
'is_super_admin' => true,
|
||||
'can_manage' => true,
|
||||
];
|
||||
|
||||
$insertJob = static function (array $overrides) use ($now): int {
|
||||
$operationId = (string) ($overrides['operation_id']
|
||||
?? bin2hex(random_bytes(16)));
|
||||
$values = [
|
||||
'operation_id' => $operationId,
|
||||
'request_idempotency_key' => $operationId,
|
||||
'request_fingerprint' => hash('sha256', $operationId),
|
||||
'parent_job_id' => null,
|
||||
'instance_id' => null,
|
||||
'order_id' => null,
|
||||
'invoice_id' => null,
|
||||
'snapshot_id' => null,
|
||||
'user_id' => 1,
|
||||
'host_id' => 1,
|
||||
'kind' => 'rescue_template_import',
|
||||
'execution_mode' => 'agent',
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'attempts' => 1,
|
||||
'dispatch_attempts' => 1,
|
||||
'dispatch_deadline_at' => $now - 10,
|
||||
'dispatch_started_at' => $now - 9,
|
||||
'dispatched_at' => $now - 8,
|
||||
'agent_accepted_at' => $now - 7,
|
||||
'receipt_deadline_at' => $now - 1,
|
||||
'sealed_payload' => '',
|
||||
'result_json' => null,
|
||||
'error_code' => 'operation_failed',
|
||||
'error_message' => '',
|
||||
'lease_token' => null,
|
||||
'lease_until' => 0,
|
||||
'available_at' => 0,
|
||||
'created_at' => $now - 20,
|
||||
'updated_at' => $now - 1,
|
||||
'terminal_at' => $now - 1,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 1,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'effect_resolved_at' => $now - 1,
|
||||
'effect_resolved_by' => null,
|
||||
'effect_resolution_reason' => 'test',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
'completion_event_id' => null,
|
||||
'read_at' => null,
|
||||
];
|
||||
$values = array_replace($values, $overrides);
|
||||
return (int) Capsule::table('cloud_jobs')->insertGetId($values);
|
||||
};
|
||||
|
||||
$insertImport = static function (
|
||||
string $name,
|
||||
string $templateId,
|
||||
string $state,
|
||||
string $resolution,
|
||||
bool $incident = false
|
||||
) use ($insertJob, $now): array {
|
||||
$operationId = bin2hex(random_bytes(16));
|
||||
$payload = [
|
||||
'can_manage' => true,
|
||||
'rescue_template_id' => $templateId,
|
||||
'method' => 'POST',
|
||||
'request_target' => '/v1/rescue-templates',
|
||||
'body' => [
|
||||
'id' => $templateId,
|
||||
'name' => $name,
|
||||
'source_url' => 'https://example.invalid/rescue.qcow2',
|
||||
'sha256' => '',
|
||||
'operation_id' => $operationId,
|
||||
],
|
||||
'owner_id' => 1,
|
||||
];
|
||||
$jobId = $insertJob([
|
||||
'operation_id' => $operationId,
|
||||
'kind' => 'rescue_template_import',
|
||||
'outcome' => $resolution === 'applied' ? 'succeeded' : 'failed',
|
||||
'status' => $resolution === 'applied' ? 'succeeded' : 'failed',
|
||||
'effect_resolution' => $resolution,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => $resolution === 'applied' ? 0 : 1,
|
||||
'error_code' => $resolution === 'applied'
|
||||
? null : 'operation_failed',
|
||||
'sealed_payload' => CloudSecrets::encrypt(
|
||||
$payload,
|
||||
'job-payload'
|
||||
),
|
||||
'finalization_incident' => $incident ? 1 : 0,
|
||||
'finalization_error_code' => $incident
|
||||
? 'recovery_instance_state_conflict' : null,
|
||||
]);
|
||||
Capsule::table('cloud_rescue_template_imports')->insert([
|
||||
'operation_id' => $operationId,
|
||||
'host_id' => 1,
|
||||
'template_id' => $templateId,
|
||||
'job_id' => $jobId,
|
||||
'import_type' => 'remote',
|
||||
'name' => $name,
|
||||
'size_bytes' => $resolution === 'applied' ? 1024 : 0,
|
||||
'sha256' => '',
|
||||
'state' => $state,
|
||||
'error_code' => $state === 'failed' ? 'import_failed' : '',
|
||||
'created_at' => $now - 20,
|
||||
'updated_at' => $now - 1,
|
||||
]);
|
||||
return [$jobId, $operationId];
|
||||
};
|
||||
|
||||
$activeTemplateId = str_repeat('a', 32);
|
||||
[$activeImportJobId] = $insertImport(
|
||||
'active-rescue',
|
||||
$activeTemplateId,
|
||||
'active',
|
||||
'applied'
|
||||
);
|
||||
|
||||
$firstDelete = CloudRescueTemplateDeletionService::delete(
|
||||
1,
|
||||
$activeTemplateId,
|
||||
$actor
|
||||
);
|
||||
$firstDeleteJobId = (int) $firstDelete['task_id'];
|
||||
$firstDeleteJob = CloudJob::findOrFail($firstDeleteJobId);
|
||||
$firstDeleteOperation = (string) $firstDeleteJob->operation_id;
|
||||
Capsule::table('cloud_jobs')->where('id', $firstDeleteJobId)->update([
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'attempts' => 1,
|
||||
'dispatch_attempts' => 1,
|
||||
'dispatch_started_at' => $now,
|
||||
'dispatched_at' => $now,
|
||||
'agent_accepted_at' => $now,
|
||||
'receipt_deadline_at' => $now + 60,
|
||||
'terminal_at' => $now,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 1,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'effect_resolved_at' => $now,
|
||||
'effect_resolution_reason' => 'test_not_applied',
|
||||
'error_code' => 'delete_failed',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
Capsule::table('cloud_rescue_template_deletions')
|
||||
->where('host_id', 1)
|
||||
->where('template_id', $activeTemplateId)
|
||||
->update([
|
||||
'state' => 'failed',
|
||||
'error_code' => 'delete_failed',
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
$secondDelete = CloudRescueTemplateDeletionService::delete(
|
||||
1,
|
||||
$activeTemplateId,
|
||||
$actor
|
||||
);
|
||||
$secondDeleteJobId = (int) $secondDelete['task_id'];
|
||||
$secondDeleteRow = CloudRescueTemplateDeletion::query()
|
||||
->where('host_id', 1)
|
||||
->where('template_id', $activeTemplateId)
|
||||
->firstOrFail();
|
||||
$assert($secondDeleteJobId !== $firstDeleteJobId
|
||||
&& (int) $secondDeleteRow->job_id === $secondDeleteJobId
|
||||
&& !hash_equals(
|
||||
$firstDeleteOperation,
|
||||
(string) $secondDeleteRow->operation_id
|
||||
)
|
||||
&& (string) $secondDeleteRow->state === 'deleting'
|
||||
&& (string) CloudJob::findOrFail($firstDeleteJobId)->effect_resolution
|
||||
=== 'not_applied',
|
||||
'A proven not-applied rescue deletion did not admit one new generation.'
|
||||
);
|
||||
|
||||
Capsule::table('cloud_jobs')->where('id', $secondDeleteJobId)->update([
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'dispatch_attempts' => 1,
|
||||
'effect_may_have_applied' => 1,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
Capsule::table('cloud_rescue_template_deletions')
|
||||
->where('host_id', 1)
|
||||
->where('template_id', $activeTemplateId)
|
||||
->update(['state' => 'failed', 'error_code' => 'delete_failed']);
|
||||
$beforeBlockedDelete = CloudJob::count();
|
||||
try {
|
||||
CloudRescueTemplateDeletionService::delete(
|
||||
1,
|
||||
$activeTemplateId,
|
||||
$actor
|
||||
);
|
||||
throw new RuntimeException(
|
||||
'An applied rescue deletion was admitted as a new generation.'
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'An unsafe rescue deletion returned the wrong status.');
|
||||
}
|
||||
$assert(CloudJob::count() === $beforeBlockedDelete
|
||||
&& (int) CloudRescueTemplateDeletion::query()
|
||||
->where('host_id', 1)
|
||||
->where('template_id', $activeTemplateId)
|
||||
->value('job_id') === $secondDeleteJobId,
|
||||
'A blocked rescue deletion changed its job or durable slot.');
|
||||
|
||||
$retryTemplateId = str_repeat('b', 32);
|
||||
$insertImport(
|
||||
'retry-rescue',
|
||||
$retryTemplateId,
|
||||
'failed',
|
||||
'not_applied'
|
||||
);
|
||||
$retryImport = CloudRescueTemplateImportService::start(
|
||||
1,
|
||||
'remote',
|
||||
'retry-rescue',
|
||||
'https://example.invalid/new-rescue.qcow2',
|
||||
'',
|
||||
'',
|
||||
$actor
|
||||
);
|
||||
$retryImportJob = CloudJob::findOrFail((int) $retryImport['task_id']);
|
||||
$assert((string) $retryImportJob->kind === 'rescue_template_import'
|
||||
&& (string) $retryImportJob->phase === 'accepted'
|
||||
&& CloudRescueTemplateImport::query()
|
||||
->where('host_id', 1)
|
||||
->where('name', 'retry-rescue')
|
||||
->count() === 2,
|
||||
'A proven not-applied rescue import did not admit a new operation.');
|
||||
|
||||
foreach ([
|
||||
['applied-rescue', str_repeat('c', 32), 'applied', false],
|
||||
['incident-rescue', str_repeat('d', 32), 'not_applied', true],
|
||||
] as [$name, $templateId, $resolution, $incident]) {
|
||||
$insertImport($name, $templateId, 'failed', $resolution, $incident);
|
||||
$before = CloudJob::count();
|
||||
try {
|
||||
CloudRescueTemplateImportService::start(
|
||||
1,
|
||||
'remote',
|
||||
$name,
|
||||
'https://example.invalid/blocked-rescue.qcow2',
|
||||
'',
|
||||
'',
|
||||
$actor
|
||||
);
|
||||
throw new RuntimeException(
|
||||
'An unsafe same-name rescue import was admitted: ' . $name
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'An unsafe rescue import returned the wrong status.');
|
||||
}
|
||||
$assert(CloudJob::count() === $before,
|
||||
'A blocked rescue import persisted a new job: ' . $name);
|
||||
}
|
||||
|
||||
$tupleTemplateId = str_repeat('f', 32);
|
||||
[$tupleJobId] = $insertImport(
|
||||
'tuple-rescue',
|
||||
$tupleTemplateId,
|
||||
'failed',
|
||||
'not_applied'
|
||||
);
|
||||
Capsule::table('cloud_jobs')->where('id', $tupleJobId)->update([
|
||||
'effect_may_have_applied' => 1,
|
||||
'safe_to_resubmit' => 1,
|
||||
]);
|
||||
$beforeTupleConflict = CloudJob::count();
|
||||
try {
|
||||
CloudRescueTemplateImportService::start(
|
||||
1,
|
||||
'remote',
|
||||
'tuple-rescue',
|
||||
'https://example.invalid/tuple-rescue.qcow2',
|
||||
'',
|
||||
'',
|
||||
$actor
|
||||
);
|
||||
throw new RuntimeException(
|
||||
'A rescue import with a contradictory terminal tuple was admitted.'
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'A rescue import tuple conflict returned the wrong status.');
|
||||
}
|
||||
$assert(CloudJob::count() === $beforeTupleConflict,
|
||||
'A rescue import tuple conflict persisted a new job.');
|
||||
|
||||
$corruptActiveTemplateId = str_repeat('1', 32);
|
||||
[$corruptActiveJobId] = $insertImport(
|
||||
'corrupt-active-rescue',
|
||||
$corruptActiveTemplateId,
|
||||
'active',
|
||||
'applied'
|
||||
);
|
||||
Capsule::table('cloud_jobs')->where('id', $corruptActiveJobId)->update([
|
||||
'effect_may_have_applied' => 1,
|
||||
]);
|
||||
$beforeCorruptActiveDelete = CloudJob::count();
|
||||
try {
|
||||
CloudRescueTemplateDeletionService::delete(
|
||||
1,
|
||||
$corruptActiveTemplateId,
|
||||
$actor
|
||||
);
|
||||
throw new RuntimeException(
|
||||
'A deletion was admitted for a corrupt active import tuple.'
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'A corrupt active import tuple returned the wrong status.');
|
||||
}
|
||||
$assert(CloudJob::count() === $beforeCorruptActiveDelete,
|
||||
'A corrupt active import tuple persisted a deletion job.');
|
||||
|
||||
$tupleDeleteTemplateId = str_repeat('2', 32);
|
||||
$insertImport(
|
||||
'tuple-delete-rescue',
|
||||
$tupleDeleteTemplateId,
|
||||
'active',
|
||||
'applied'
|
||||
);
|
||||
$tupleDelete = CloudRescueTemplateDeletionService::delete(
|
||||
1,
|
||||
$tupleDeleteTemplateId,
|
||||
$actor
|
||||
);
|
||||
$tupleDeleteJobId = (int) $tupleDelete['task_id'];
|
||||
Capsule::table('cloud_jobs')->where('id', $tupleDeleteJobId)->update([
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'attempts' => 1,
|
||||
'dispatch_attempts' => 1,
|
||||
'dispatch_started_at' => $now,
|
||||
'dispatched_at' => $now,
|
||||
'agent_accepted_at' => $now,
|
||||
'terminal_at' => $now,
|
||||
'effect_may_have_applied' => 1,
|
||||
'safe_to_resubmit' => 1,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'effect_resolved_at' => $now,
|
||||
'effect_resolution_reason' => 'invalid_test_tuple',
|
||||
'error_code' => 'delete_failed',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
Capsule::table('cloud_rescue_template_deletions')
|
||||
->where('host_id', 1)
|
||||
->where('template_id', $tupleDeleteTemplateId)
|
||||
->update(['state' => 'failed', 'error_code' => 'delete_failed']);
|
||||
$beforeTupleDeleteRetry = CloudJob::count();
|
||||
try {
|
||||
CloudRescueTemplateDeletionService::delete(
|
||||
1,
|
||||
$tupleDeleteTemplateId,
|
||||
$actor
|
||||
);
|
||||
throw new RuntimeException(
|
||||
'A rescue deletion with a contradictory terminal tuple was admitted.'
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'A rescue deletion tuple conflict returned the wrong status.');
|
||||
}
|
||||
$assert(CloudJob::count() === $beforeTupleDeleteRetry,
|
||||
'A rescue deletion tuple conflict persisted a new job.');
|
||||
|
||||
$identityTemplateId = str_repeat('e', 32);
|
||||
[, $identityOperation] = $insertImport(
|
||||
'identity-rescue',
|
||||
$identityTemplateId,
|
||||
'failed',
|
||||
'not_applied'
|
||||
);
|
||||
Capsule::table('cloud_rescue_template_imports')
|
||||
->where('operation_id', $identityOperation)
|
||||
->update(['operation_id' => bin2hex(random_bytes(16))]);
|
||||
$beforeIdentityConflict = CloudJob::count();
|
||||
try {
|
||||
CloudRescueTemplateImportService::start(
|
||||
1,
|
||||
'remote',
|
||||
'identity-rescue',
|
||||
'https://example.invalid/identity-rescue.qcow2',
|
||||
'',
|
||||
'',
|
||||
$actor
|
||||
);
|
||||
throw new RuntimeException(
|
||||
'A rescue import with a corrupt durable identity was admitted.'
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'A rescue import identity conflict returned the wrong status.');
|
||||
}
|
||||
$assert(CloudJob::count() === $beforeIdentityConflict,
|
||||
'A rescue import identity conflict persisted a new job.');
|
||||
|
||||
echo "Cloud rescue-template retry boundary checks passed.\n";
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,746 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudJobService;
|
||||
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('cloud_jobs', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('operation_id');
|
||||
$table->string('request_idempotency_key');
|
||||
$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->integer('attempts')->default(0);
|
||||
$table->integer('dispatch_attempts')->nullable()->default(0);
|
||||
$table->integer('dispatch_deadline_at');
|
||||
$table->integer('dispatch_started_at')->nullable();
|
||||
$table->integer('agent_accepted_at')->nullable();
|
||||
$table->integer('dispatched_at')->nullable();
|
||||
$table->integer('receipt_deadline_at')->nullable();
|
||||
$table->integer('terminal_at')->nullable();
|
||||
$table->string('completion_event_id')->nullable();
|
||||
$table->boolean('effect_may_have_applied')->nullable();
|
||||
$table->boolean('safe_to_resubmit')->nullable();
|
||||
$table->string('effect_resolution');
|
||||
$table->boolean('finalization_incident')->default(0);
|
||||
$table->string('finalization_error_code')->nullable();
|
||||
$table->string('lease_token')->nullable();
|
||||
$table->integer('lease_until')->default(0);
|
||||
$table->integer('available_at')->default(0);
|
||||
$table->string('error_code')->nullable();
|
||||
$table->text('result_json')->nullable();
|
||||
$table->text('sealed_payload')->default('');
|
||||
$table->integer('read_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_templates', static function (Blueprint $table): void {
|
||||
$table->string('id')->primary();
|
||||
$table->integer('active_job_id')->nullable();
|
||||
$table->string('state')->default('active');
|
||||
});
|
||||
$schema->create('cloud_user_isos', static function (Blueprint $table): void {
|
||||
$table->string('id')->primary();
|
||||
$table->integer('active_job_id')->nullable();
|
||||
$table->string('state')->default('active');
|
||||
});
|
||||
$schema->create('cloud_template_replicas',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('host_id');
|
||||
$table->string('template_id');
|
||||
$table->integer('revision')->default(0);
|
||||
$table->string('generation_token')->default('');
|
||||
$table->string('state')->default('pending');
|
||||
$table->integer('image_bytes')->default(0);
|
||||
$table->string('sha256')->default('');
|
||||
$table->string('operation_id')->default('');
|
||||
$table->integer('job_id')->nullable();
|
||||
$table->string('error_code')->default('');
|
||||
$table->integer('created_at')->default(0);
|
||||
$table->integer('updated_at')->default(0);
|
||||
$table->primary(['host_id', 'template_id']);
|
||||
});
|
||||
$schema->create('cloud_user_iso_replicas',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('host_id');
|
||||
$table->string('user_iso_id');
|
||||
$table->integer('user_id');
|
||||
$table->string('state')->default('pending');
|
||||
$table->integer('size_bytes')->default(0);
|
||||
$table->string('sha256')->default('');
|
||||
$table->string('operation_id')->default('');
|
||||
$table->integer('job_id')->nullable();
|
||||
$table->string('error_code')->default('');
|
||||
$table->integer('created_at')->default(0);
|
||||
$table->integer('updated_at')->default(0);
|
||||
$table->primary(['host_id', 'user_iso_id']);
|
||||
});
|
||||
|
||||
$now = time();
|
||||
$insert = static function (int $id, array $overrides = []) use ($now): void {
|
||||
$values = array_replace([
|
||||
'id' => $id,
|
||||
'operation_id' => sprintf('%032x', $id),
|
||||
'request_idempotency_key' => sprintf('%032x', $id),
|
||||
'request_fingerprint' => hash('sha256', (string) $id),
|
||||
'parent_job_id' => null,
|
||||
'order_id' => null,
|
||||
'invoice_id' => null,
|
||||
'instance_id' => 10,
|
||||
'snapshot_id' => null,
|
||||
'user_id' => 7,
|
||||
'host_id' => 3,
|
||||
'kind' => 'instance_settings',
|
||||
'execution_mode' => 'agent',
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'attempts' => 1,
|
||||
'dispatch_attempts' => 1,
|
||||
'dispatch_deadline_at' => $now - 100,
|
||||
'dispatch_started_at' => $now - 95,
|
||||
'agent_accepted_at' => $now - 92,
|
||||
'dispatched_at' => $now - 90,
|
||||
'receipt_deadline_at' => $now - 60,
|
||||
'terminal_at' => $now - 30,
|
||||
'completion_event_id' => null,
|
||||
'effect_may_have_applied' => 1,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'unknown',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_evidence_conflict',
|
||||
'lease_until' => 0,
|
||||
'available_at' => $now + 30,
|
||||
'error_code' => 'operation_failed_effect_unknown',
|
||||
'created_at' => $now - 120,
|
||||
'updated_at' => $now,
|
||||
], $overrides);
|
||||
if (($values['execution_mode'] ?? '') === 'aggregate') {
|
||||
foreach ([
|
||||
'attempts' => 0,
|
||||
'dispatch_started_at' => null,
|
||||
'agent_accepted_at' => null,
|
||||
'dispatched_at' => null,
|
||||
'completion_event_id' => null,
|
||||
] as $field => $value) {
|
||||
if (!array_key_exists($field, $overrides)) {
|
||||
$values[$field] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (($values['execution_mode'] ?? '') === 'agent'
|
||||
&& (int) ($values['dispatch_attempts'] ?? -1) === 0) {
|
||||
foreach (['attempts' => 0, 'dispatch_started_at' => null,
|
||||
'agent_accepted_at' => null, 'dispatched_at' => null,
|
||||
'receipt_deadline_at' => null, 'completion_event_id' => null]
|
||||
as $field => $value) {
|
||||
if (!array_key_exists($field, $overrides)) {
|
||||
$values[$field] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (($values['outcome'] ?? null) === 'succeeded'
|
||||
&& !array_key_exists('error_code', $overrides)) {
|
||||
$values['error_code'] = null;
|
||||
}
|
||||
Capsule::table('cloud_jobs')->insert($values);
|
||||
};
|
||||
|
||||
$insert(1);
|
||||
$insert(2, [
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
'available_at' => 0,
|
||||
]);
|
||||
$insert(3, ['kind' => 'create']);
|
||||
$insert(4, [
|
||||
'phase' => 'accepted',
|
||||
'outcome' => null,
|
||||
'status' => 'queued',
|
||||
'dispatch_attempts' => 0,
|
||||
'dispatched_at' => null,
|
||||
'receipt_deadline_at' => null,
|
||||
'terminal_at' => null,
|
||||
'effect_may_have_applied' => null,
|
||||
'safe_to_resubmit' => null,
|
||||
'effect_resolution' => 'not_applicable',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
'dispatch_deadline_at' => $now + 300,
|
||||
'available_at' => $now,
|
||||
]);
|
||||
$insert(5, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(6, [
|
||||
'parent_job_id' => 5,
|
||||
'kind' => 'template_import_replica',
|
||||
'finalization_error_code' => 'recovery_operation_identity_conflict',
|
||||
'error_code' => 'raw-agent-secret-must-not-appear',
|
||||
'result_json' => json_encode([
|
||||
'message' => 'raw-agent-text-must-not-appear',
|
||||
], JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
$insert(7, [
|
||||
'parent_job_id' => 5,
|
||||
'kind' => 'template_import_replica',
|
||||
'finalization_error_code' => 'recovery_receipt_invalid',
|
||||
]);
|
||||
|
||||
$tasks = CloudJobService::tasks(['user_id' => 7, 'is_admin' => false],
|
||||
'completed');
|
||||
$assert(($tasks['active_count'] ?? null) === 1,
|
||||
'Task center active count changed while adding recovery polling.');
|
||||
$assert(($tasks['recovering_count'] ?? null) === 2,
|
||||
'Task center did not count visible terminal tasks that still converge.');
|
||||
$assert(array_map(static fn (array $item): string => $item['id'],
|
||||
$tasks['items']) === ['5', '3', '2', '1'],
|
||||
'Task center exposed hidden child work or changed terminal ordering.');
|
||||
$assert(($tasks['items'][0]['recovery']['pending'] ?? null) === true
|
||||
&& ($tasks['items'][3]['recovery']['pending'] ?? null) === true
|
||||
&& !isset($tasks['items'][1]['recovery'])
|
||||
&& !isset($tasks['items'][2]['recovery']),
|
||||
'Task recovery status did not match the visible recovery count.');
|
||||
$aggregateRecovery = $tasks['items'][0]['recovery'] ?? [];
|
||||
$adminAggregate = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(5),
|
||||
true
|
||||
);
|
||||
$assert(str_contains(
|
||||
(string) ($aggregateRecovery['message'] ?? ''),
|
||||
'操作、资源或请求指纹'
|
||||
)
|
||||
&& str_contains(
|
||||
(string) ($aggregateRecovery['message'] ?? ''),
|
||||
'另有 1 类子任务异常'
|
||||
)
|
||||
&& !array_key_exists('code', $aggregateRecovery)
|
||||
&& !str_contains(
|
||||
(string) ($aggregateRecovery['message'] ?? ''),
|
||||
'raw-agent'
|
||||
)
|
||||
&& ($adminAggregate['recovery']['code'] ?? null)
|
||||
=== 'recovery_operation_identity_conflict'
|
||||
&& ($adminAggregate['recovery']['affected_child_count'] ?? null) === 2
|
||||
&& ($adminAggregate['recovery']['additional_error_count'] ?? null) === 1,
|
||||
'Aggregate recovery did not safely expose the deterministic child anomaly.');
|
||||
|
||||
// A dispatch counter outside the durable 0/1 state machine is corruption,
|
||||
// not proof that the mutation stayed on the PHP side of the dispatch fence.
|
||||
// Keep both the leaf and its public aggregate parent visibly recovering with
|
||||
// one reviewed Chinese anomaly instead of hiding the child as undispatched.
|
||||
$insert(8, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(9, [
|
||||
'parent_job_id' => 8,
|
||||
'kind' => 'template_import_replica',
|
||||
'dispatch_attempts' => 2,
|
||||
'finalization_error_code' => 'recovery_dispatch_ledger_conflict',
|
||||
]);
|
||||
$invalidDispatchLeaf = CloudJobService::recoveryPresentation(
|
||||
\App\Models\CloudJob::findOrFail(9),
|
||||
true
|
||||
);
|
||||
$invalidDispatchParent = CloudJobService::recoveryPresentation(
|
||||
\App\Models\CloudJob::findOrFail(8),
|
||||
true
|
||||
);
|
||||
$assert(($invalidDispatchLeaf['code'] ?? null)
|
||||
=== 'recovery_dispatch_ledger_conflict'
|
||||
&& str_contains(
|
||||
(string) ($invalidDispatchLeaf['message'] ?? ''),
|
||||
'派发'
|
||||
)
|
||||
&& ($invalidDispatchParent['code'] ?? null)
|
||||
=== 'recovery_dispatch_ledger_conflict'
|
||||
&& ($invalidDispatchParent['affected_child_count'] ?? null) === 1
|
||||
&& str_contains(
|
||||
(string) ($invalidDispatchParent['message'] ?? ''),
|
||||
'派发'
|
||||
),
|
||||
'An invalid dispatch ledger was hidden from the task center or aggregate parent.');
|
||||
|
||||
// A historical row may still carry an immutable succeeded receipt while its
|
||||
// dispatch generation is corrupt. The public DTO must expose the concrete
|
||||
// recovery incident without rewriting that terminal receipt.
|
||||
$insert(10, [
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'dispatch_attempts' => 2,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$invalidSucceeded = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(10),
|
||||
false
|
||||
);
|
||||
$assert(($invalidSucceeded['status'] ?? null) === 'succeeded'
|
||||
&& ($invalidSucceeded['recovery']['pending'] ?? null) === true
|
||||
&& str_contains(
|
||||
(string) ($invalidSucceeded['recovery']['message'] ?? ''),
|
||||
'派发'
|
||||
),
|
||||
'A succeeded task with an invalid dispatch ledger hid its recovery incident.');
|
||||
|
||||
// Repairing the counter to a legal value must not create a brief unlock
|
||||
// window. The sticky repair incident remains visible until the coordinator
|
||||
// validates the immutable terminal receipt and explicitly clears it.
|
||||
$insert(11, [
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'dispatch_attempts' => 1,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_dispatch_repair_receipt_invalid',
|
||||
]);
|
||||
$stickySucceeded = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(11),
|
||||
true
|
||||
);
|
||||
$assert(($stickySucceeded['status'] ?? null) === 'succeeded'
|
||||
&& ($stickySucceeded['recovery']['code'] ?? null)
|
||||
=== 'recovery_dispatch_repair_receipt_invalid'
|
||||
&& str_contains(
|
||||
(string) ($stickySucceeded['recovery']['message'] ?? ''),
|
||||
'完整性校验'
|
||||
)
|
||||
&& CloudJobService::blockingQueryForInstance(10)
|
||||
->where('id', 11)->exists(),
|
||||
'A repaired succeeded task unlocked before its sticky incident was validated.');
|
||||
|
||||
// A zero counter proves the Agent was never contacted, but a failed PHP
|
||||
// business-ledger finalizer still owns the resource lock until local recovery
|
||||
// completes.
|
||||
$insert(12, [
|
||||
'dispatch_attempts' => 0,
|
||||
'dispatched_at' => null,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_ledger_conflict',
|
||||
]);
|
||||
$localFinalizer = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(12),
|
||||
true
|
||||
);
|
||||
$assert(($localFinalizer['recovery']['code'] ?? null)
|
||||
=== 'recovery_ledger_conflict'
|
||||
&& str_contains(
|
||||
(string) ($localFinalizer['recovery']['message'] ?? ''),
|
||||
'面板账本'
|
||||
)
|
||||
&& CloudJobService::blockingQueryForInstance(10)
|
||||
->where('id', 12)->exists(),
|
||||
'An undispatched local finalizer failure was hidden or unlocked.');
|
||||
|
||||
$insert(13, [
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'dispatch_attempts' => null,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$nullDispatch = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(13),
|
||||
true
|
||||
);
|
||||
$assert(($nullDispatch['status'] ?? null) === 'succeeded'
|
||||
&& ($nullDispatch['recovery']['code'] ?? null)
|
||||
=== 'recovery_dispatch_ledger_conflict'
|
||||
&& CloudJobService::blockingQueryForInstance(10)
|
||||
->where('id', 13)->exists(),
|
||||
'A NULL dispatch ledger was treated as undispatched and unlocked.');
|
||||
|
||||
// Aggregate parents must inherit a zero-dispatch child's unresolved local
|
||||
// finalizer instead of appearing complete while the child remains fenced.
|
||||
$insert(14, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 1,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(15, [
|
||||
'parent_job_id' => 14,
|
||||
'kind' => 'template_import_replica',
|
||||
'dispatch_attempts' => 0,
|
||||
'dispatched_at' => null,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_ledger_conflict',
|
||||
]);
|
||||
$localAggregate = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(14),
|
||||
true
|
||||
);
|
||||
$afterRepairCases = CloudJobService::tasks(
|
||||
['user_id' => 7, 'is_admin' => false],
|
||||
'completed'
|
||||
);
|
||||
$assert(($localAggregate['recovery']['code'] ?? null)
|
||||
=== 'recovery_ledger_conflict'
|
||||
&& ($localAggregate['recovery']['affected_child_count'] ?? null) === 1
|
||||
&& ($afterRepairCases['recovering_count'] ?? null) === 8,
|
||||
'Aggregate/recovering queries omitted sticky, local-finalizer, or NULL-ledger work.');
|
||||
|
||||
// A resource-projection validator records its bounded diagnosis on the parent
|
||||
// after every child is already resolved. The user must see that concrete
|
||||
// Chinese reason, and administrators must receive the reviewed code instead
|
||||
// of a misleading generic child-convergence status.
|
||||
$insert(16, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_instance_state_conflict',
|
||||
]);
|
||||
$insert(17, [
|
||||
'parent_job_id' => 16,
|
||||
'kind' => 'template_import_replica',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$projectionUser = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(16),
|
||||
false
|
||||
);
|
||||
$projectionAdmin = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(16),
|
||||
true
|
||||
);
|
||||
$assert(str_contains(
|
||||
(string) ($projectionUser['recovery']['message'] ?? ''),
|
||||
'实例状态与任务证据暂不一致'
|
||||
)
|
||||
&& !array_key_exists('code', $projectionUser['recovery'] ?? [])
|
||||
&& ($projectionAdmin['recovery']['code'] ?? null)
|
||||
=== 'recovery_instance_state_conflict'
|
||||
&& ($projectionAdmin['recovery']['affected_child_count'] ?? null) === 0
|
||||
&& ($projectionAdmin['recovery']['additional_error_count'] ?? null) === 0,
|
||||
'Aggregate parent projection anomaly was hidden as child convergence.');
|
||||
|
||||
// Damaged terminal safety tuples are neither resolved jobs nor trustworthy
|
||||
// Agent recovery candidates. They remain visibly fenced with one concrete
|
||||
// reviewed code, including when the valid dispatch generation is zero.
|
||||
$insert(18, [
|
||||
'safe_to_resubmit' => 1,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(19, [
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(20, [
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(21, [
|
||||
'dispatch_attempts' => 0,
|
||||
'dispatched_at' => null,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(26, [
|
||||
'dispatch_attempts' => 0,
|
||||
'dispatched_at' => null,
|
||||
'effect_may_have_applied' => 1,
|
||||
'safe_to_resubmit' => 0,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
foreach ([18, 19, 20, 21, 26] as $stateConflictId) {
|
||||
$stateConflict = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail($stateConflictId),
|
||||
true
|
||||
);
|
||||
$assert(($stateConflict['recovery']['code'] ?? null)
|
||||
=== 'recovery_instance_state_conflict'
|
||||
&& CloudJobService::blockingQueryForInstance(10)
|
||||
->where('id', $stateConflictId)->exists(),
|
||||
'A damaged leaf safety tuple left recovery or unlocked its instance.');
|
||||
}
|
||||
|
||||
$insert(22, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'safe_to_resubmit' => 1,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(23, [
|
||||
'parent_job_id' => 22,
|
||||
'kind' => 'template_import_replica',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$aggregateStateConflict = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(22),
|
||||
true
|
||||
);
|
||||
$assert(($aggregateStateConflict['recovery']['code'] ?? null)
|
||||
=== 'recovery_aggregate_state_conflict',
|
||||
'A damaged aggregate-parent safety tuple was hidden from administrators.');
|
||||
|
||||
$insert(24, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(25, [
|
||||
'parent_job_id' => 24,
|
||||
'kind' => 'template_import_replica',
|
||||
'safe_to_resubmit' => 1,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$childStateConflict = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(24),
|
||||
true
|
||||
);
|
||||
$assert(($childStateConflict['recovery']['code'] ?? null)
|
||||
=== 'recovery_instance_state_conflict'
|
||||
&& ($childStateConflict['recovery']['affected_child_count'] ?? null) === 1,
|
||||
'An anomalous aggregate child did not keep its parent visibly pending.');
|
||||
|
||||
// Every code that a published aggregate projection validator can persist must
|
||||
// remain selectable and visible. Missing codes here would leave the catalog
|
||||
// locked by finalization_incident while both task center and administrators
|
||||
// incorrectly report an ordinary completed task.
|
||||
$beforePublishedIncidents = CloudJobService::tasks(
|
||||
['user_id' => 7, 'is_admin' => false],
|
||||
'completed'
|
||||
)['recovering_count'];
|
||||
foreach ([
|
||||
27 => 'recovery_dispatch_ledger_conflict',
|
||||
29 => 'recovery_payload_unavailable',
|
||||
] as $parentId => $incidentCode) {
|
||||
$insert($parentId, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => $incidentCode,
|
||||
]);
|
||||
$insert($parentId + 1, [
|
||||
'parent_job_id' => $parentId,
|
||||
'kind' => 'template_import_replica',
|
||||
'outcome' => 'succeeded',
|
||||
'status' => 'succeeded',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$publishedIncident = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail($parentId),
|
||||
true
|
||||
);
|
||||
$assert(($publishedIncident['recovery']['code'] ?? null) === $incidentCode,
|
||||
'A published aggregate projection incident disappeared: '
|
||||
. $incidentCode);
|
||||
}
|
||||
$afterPublishedIncidents = CloudJobService::tasks(
|
||||
['user_id' => 7, 'is_admin' => false],
|
||||
'completed'
|
||||
)['recovering_count'];
|
||||
$assert($afterPublishedIncidents === $beforePublishedIncidents + 2,
|
||||
'Published aggregate projection incidents left the recovering filter.');
|
||||
|
||||
// A child cannot have a final effect while its task is still nonterminal. The
|
||||
// contradiction belongs to the PHP aggregate ledger and must be visible before
|
||||
// a worker has had a chance to persist the parent incident.
|
||||
$insert(31, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(32, [
|
||||
'parent_job_id' => 31,
|
||||
'kind' => 'template_import_replica',
|
||||
'phase' => 'awaiting_receipt',
|
||||
'outcome' => null,
|
||||
'status' => 'running',
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$nonterminalResolved = CloudJobService::display(
|
||||
\App\Models\CloudJob::findOrFail(31),
|
||||
true
|
||||
);
|
||||
$assert(($nonterminalResolved['recovery']['code'] ?? null)
|
||||
=== 'recovery_aggregate_state_conflict'
|
||||
&& ($nonterminalResolved['recovery']['affected_child_count'] ?? null) === 1,
|
||||
'A nonterminal child with a published effect concealed its aggregate conflict.');
|
||||
|
||||
// Immutable request-identity damage is more specific than the generic terminal
|
||||
// state conflict it also implies. Administrators need that concrete cause for
|
||||
// both a direct leaf and a leaf summarized through its aggregate parent.
|
||||
$insert(33, [
|
||||
'request_idempotency_key' => 'bad-key',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_operation_identity_conflict',
|
||||
]);
|
||||
$identityLeaf = CloudJobService::recoveryPresentation(
|
||||
\App\Models\CloudJob::findOrFail(33),
|
||||
true
|
||||
);
|
||||
$assert(($identityLeaf['code'] ?? null)
|
||||
=== 'recovery_operation_identity_conflict'
|
||||
&& str_contains(
|
||||
(string) ($identityLeaf['message'] ?? ''),
|
||||
'请求指纹'
|
||||
),
|
||||
'A damaged leaf request identity was generalized in the admin DTO.');
|
||||
|
||||
$insert(34, [
|
||||
'kind' => 'template_import',
|
||||
'execution_mode' => 'aggregate',
|
||||
'host_id' => null,
|
||||
'instance_id' => null,
|
||||
'dispatch_attempts' => 0,
|
||||
'finalization_incident' => 0,
|
||||
'finalization_error_code' => null,
|
||||
]);
|
||||
$insert(35, [
|
||||
'parent_job_id' => 34,
|
||||
'kind' => 'template_import_replica',
|
||||
'request_fingerprint' => 'bad-fingerprint',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_operation_identity_conflict',
|
||||
]);
|
||||
$identityAggregate = CloudJobService::recoveryPresentation(
|
||||
\App\Models\CloudJob::findOrFail(34),
|
||||
true
|
||||
);
|
||||
$assert(($identityAggregate['code'] ?? null)
|
||||
=== 'recovery_operation_identity_conflict'
|
||||
&& ($identityAggregate['affected_child_count'] ?? null) === 1,
|
||||
'An aggregate child request-identity conflict was generalized.');
|
||||
|
||||
// Sticky repair and data-integrity incidents retain their origin even if a
|
||||
// second malformed envelope field also satisfies the generic state predicate.
|
||||
$insert(36, [
|
||||
'receipt_deadline_at' => 0,
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' =>
|
||||
'recovery_dispatch_repair_instance_state_conflict',
|
||||
]);
|
||||
$repairSpecific = CloudJobService::recoveryPresentation(
|
||||
\App\Models\CloudJob::findOrFail(36),
|
||||
true
|
||||
);
|
||||
$assert(($repairSpecific['code'] ?? null)
|
||||
=== 'recovery_dispatch_repair_instance_state_conflict',
|
||||
'A sticky dispatch-repair cause was generalized in the admin DTO.');
|
||||
|
||||
$insert(37, [
|
||||
'receipt_deadline_at' => 0,
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_payload_unavailable',
|
||||
]);
|
||||
$payloadSpecific = CloudJobService::recoveryPresentation(
|
||||
\App\Models\CloudJob::findOrFail(37),
|
||||
true
|
||||
);
|
||||
$assert(($payloadSpecific['code'] ?? null)
|
||||
=== 'recovery_payload_unavailable',
|
||||
'A concrete recovery-data incident was generalized in the admin DTO.');
|
||||
|
||||
echo "Cloud task recovery presentation checks passed.\n";
|
||||
@ -0,0 +1,365 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
/** Isolated encrypted envelope for PHP-only finalizer 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 'undispatched-finalizer-test:' . $key;
|
||||
}
|
||||
|
||||
public static function decrypt(string $value, string $purpose): array
|
||||
{
|
||||
$key = substr(
|
||||
$value,
|
||||
strlen('undispatched-finalizer-test:')
|
||||
);
|
||||
if (!array_key_exists($key, self::$values)) {
|
||||
throw new \RuntimeException('Missing finalizer test payload.');
|
||||
}
|
||||
return self::$values[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudJob;
|
||||
use App\Services\Cloud\CloudAutomaticOperationRecoveryService;
|
||||
use App\Services\Cloud\CloudJobService;
|
||||
use App\Services\Cloud\CloudSecrets;
|
||||
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')->default(0);
|
||||
$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->string('name');
|
||||
$table->string('status');
|
||||
$table->string('service_status');
|
||||
$table->string('network_status');
|
||||
$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']);
|
||||
});
|
||||
$schema->create('cloud_templates',
|
||||
static function (Blueprint $table): void {
|
||||
$table->string('id')->primary();
|
||||
$table->integer('active_job_id')->nullable();
|
||||
$table->string('state')->default('active');
|
||||
});
|
||||
$schema->create('cloud_user_isos',
|
||||
static function (Blueprint $table): void {
|
||||
$table->string('id')->primary();
|
||||
$table->integer('active_job_id')->nullable();
|
||||
$table->string('state')->default('active');
|
||||
});
|
||||
$schema->create('cloud_template_replicas',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('host_id');
|
||||
$table->string('template_id');
|
||||
$table->integer('revision')->default(0);
|
||||
$table->string('generation_token')->default('');
|
||||
$table->string('state')->default('pending');
|
||||
$table->integer('image_bytes')->default(0);
|
||||
$table->string('sha256')->default('');
|
||||
$table->string('operation_id')->default('');
|
||||
$table->integer('job_id')->nullable();
|
||||
$table->string('error_code')->default('');
|
||||
$table->integer('created_at')->default(0);
|
||||
$table->integer('updated_at')->default(0);
|
||||
$table->primary(['host_id', 'template_id']);
|
||||
});
|
||||
$schema->create('cloud_user_iso_replicas',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('host_id');
|
||||
$table->string('user_iso_id');
|
||||
$table->integer('user_id');
|
||||
$table->string('state')->default('pending');
|
||||
$table->integer('size_bytes')->default(0);
|
||||
$table->string('sha256')->default('');
|
||||
$table->string('operation_id')->default('');
|
||||
$table->integer('job_id')->nullable();
|
||||
$table->string('error_code')->default('');
|
||||
$table->integer('created_at')->default(0);
|
||||
$table->integer('updated_at')->default(0);
|
||||
$table->primary(['host_id', 'user_iso_id']);
|
||||
});
|
||||
|
||||
$now = time();
|
||||
$operationId = str_repeat('ad', 16);
|
||||
$uuid = '00000000-0000-4000-8000-000000000501';
|
||||
$payload = [
|
||||
'method' => 'POST',
|
||||
'request_target' => '/v1/vms/' . $uuid . '/settings',
|
||||
'body' => [
|
||||
'hostname' => 'local-finalizer.example',
|
||||
'root_password' => 'Secret9!Password',
|
||||
'confirm_restart' => true,
|
||||
],
|
||||
'owner_id' => 1,
|
||||
'can_manage' => false,
|
||||
'credential' => [
|
||||
'password' => 'Secret9!Password',
|
||||
'login_name' => 'root',
|
||||
'auth_mode' => 'password',
|
||||
],
|
||||
'settings_fields' => ['hostname', 'password'],
|
||||
];
|
||||
Capsule::table('user')->insert([
|
||||
'id' => 1, 'enable' => 1, 'is_admin' => 0,
|
||||
]);
|
||||
Capsule::table('cloud_instances')->insert([
|
||||
'id' => 501,
|
||||
'uuid' => $uuid,
|
||||
'host_id' => 7,
|
||||
'user_id' => 1,
|
||||
'name' => 'local-finalizer',
|
||||
'status' => 'active',
|
||||
'service_status' => 'exempt',
|
||||
'network_status' => 'active',
|
||||
'spec_json' => json_encode(
|
||||
['managed' => true],
|
||||
JSON_THROW_ON_ERROR
|
||||
),
|
||||
'sealed_credential' => null,
|
||||
'created_at' => $now - 3600,
|
||||
'updated_at' => $now - 3600,
|
||||
]);
|
||||
$originalEnvelope = CloudSecrets::encrypt($payload, 'job-payload');
|
||||
$originalResult = json_encode(
|
||||
['cause_code' => 'local_finalization_failed'],
|
||||
JSON_THROW_ON_ERROR
|
||||
);
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => 501,
|
||||
'operation_id' => $operationId,
|
||||
'request_idempotency_key' => $operationId,
|
||||
'request_fingerprint' => hash('sha256', $operationId),
|
||||
'parent_job_id' => null,
|
||||
'order_id' => null,
|
||||
'invoice_id' => null,
|
||||
'instance_id' => 501,
|
||||
'snapshot_id' => null,
|
||||
'user_id' => 1,
|
||||
'host_id' => 7,
|
||||
'kind' => 'instance_settings',
|
||||
'execution_mode' => 'agent',
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'sealed_payload' => $originalEnvelope,
|
||||
'attempts' => 0,
|
||||
'dispatch_attempts' => 0,
|
||||
'dispatch_deadline_at' => $now - 30,
|
||||
'terminal_at' => $now - 20,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'effect_resolution_reason' => '',
|
||||
'lease_until' => 0,
|
||||
'available_at' => 0,
|
||||
'error_code' => 'local_finalization_failed',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_ledger_conflict',
|
||||
'result_json' => $originalResult,
|
||||
'created_at' => $now - 30,
|
||||
'updated_at' => $now - 20,
|
||||
]);
|
||||
|
||||
$before = CloudJob::findOrFail(501);
|
||||
$assert(CloudJobService::blockingQueryForInstance(501)->exists(),
|
||||
'An undispatched local finalizer incident did not block mutations.');
|
||||
$service = new CloudAutomaticOperationRecoveryService();
|
||||
$assert($service->tick(),
|
||||
'The undispatched PHP-only finalizer was not claimed.');
|
||||
$after = CloudJob::findOrFail(501);
|
||||
$scrubbed = CloudSecrets::decrypt(
|
||||
(string) $after->sealed_payload,
|
||||
'job-payload'
|
||||
);
|
||||
$assert((string) $after->phase === (string) $before->phase
|
||||
&& (string) $after->outcome === (string) $before->outcome
|
||||
&& (string) $after->status === (string) $before->status
|
||||
&& (int) $after->terminal_at === (int) $before->terminal_at
|
||||
&& (string) $after->error_code === (string) $before->error_code
|
||||
&& (string) $after->result_json === (string) $before->result_json
|
||||
&& $after->completion_event_id === $before->completion_event_id
|
||||
&& !(bool) $after->effect_may_have_applied
|
||||
&& (bool) $after->safe_to_resubmit
|
||||
&& (string) $after->effect_resolution === 'not_applied'
|
||||
&& (string) $after->effect_resolution_reason
|
||||
=== 'automatic_local_not_dispatched'
|
||||
&& (int) $after->effect_resolved_at > 0
|
||||
&& !(bool) $after->finalization_incident
|
||||
&& $after->finalization_error_code === null
|
||||
&& $after->lease_token === null
|
||||
&& (int) $after->lease_until === 0
|
||||
&& (int) $after->available_at === 0
|
||||
&& (string) $after->sealed_payload !== $originalEnvelope
|
||||
&& !isset($scrubbed['credential'])
|
||||
&& !isset($scrubbed['body']['root_password'])
|
||||
&& !CloudJobService::blockingQueryForInstance(501)->exists(),
|
||||
'The PHP-only finalizer changed terminal audit data or failed to converge safely.');
|
||||
$updatedAt = (int) $after->updated_at;
|
||||
$assert(!$service->tick(),
|
||||
'A converged PHP-only finalizer was claimed a second time.');
|
||||
$afterSecondTick = CloudJob::findOrFail(501);
|
||||
$assert((int) $afterSecondTick->updated_at === $updatedAt,
|
||||
'A converged PHP-only finalizer repeated its side effects.');
|
||||
|
||||
// A missing/corrupt encrypted escrow remains a concrete payload incident;
|
||||
// it must not degrade into a generic ledger-conflict message.
|
||||
Capsule::table('cloud_instances')->insert([
|
||||
'id' => 502,
|
||||
'uuid' => '00000000-0000-4000-8000-000000000502',
|
||||
'host_id' => 7,
|
||||
'user_id' => 1,
|
||||
'name' => 'local-finalizer-corrupt-payload',
|
||||
'status' => 'active',
|
||||
'service_status' => 'exempt',
|
||||
'network_status' => 'active',
|
||||
'spec_json' => json_encode(['managed' => true], JSON_THROW_ON_ERROR),
|
||||
'sealed_credential' => null,
|
||||
'created_at' => $now - 3600,
|
||||
'updated_at' => $now - 3600,
|
||||
]);
|
||||
$corruptOperationId = str_repeat('ae', 16);
|
||||
Capsule::table('cloud_jobs')->insert([
|
||||
'id' => 502,
|
||||
'operation_id' => $corruptOperationId,
|
||||
'request_idempotency_key' => $corruptOperationId,
|
||||
'request_fingerprint' => hash('sha256', $corruptOperationId),
|
||||
'parent_job_id' => null,
|
||||
'order_id' => null,
|
||||
'invoice_id' => null,
|
||||
'instance_id' => 502,
|
||||
'snapshot_id' => null,
|
||||
'user_id' => 1,
|
||||
'host_id' => 7,
|
||||
'kind' => 'instance_settings',
|
||||
'execution_mode' => 'agent',
|
||||
'phase' => 'terminal',
|
||||
'outcome' => 'failed',
|
||||
'status' => 'failed',
|
||||
'sealed_payload' => 'undispatched-finalizer-test:missing',
|
||||
'attempts' => 0,
|
||||
'dispatch_attempts' => 0,
|
||||
'dispatch_deadline_at' => $now - 30,
|
||||
'terminal_at' => $now - 20,
|
||||
'effect_may_have_applied' => 0,
|
||||
'safe_to_resubmit' => 0,
|
||||
'effect_resolution' => 'not_applied',
|
||||
'effect_resolution_reason' => '',
|
||||
'lease_until' => 0,
|
||||
'available_at' => 0,
|
||||
'error_code' => 'local_finalization_failed',
|
||||
'finalization_incident' => 1,
|
||||
'finalization_error_code' => 'recovery_payload_unavailable',
|
||||
'result_json' => $originalResult,
|
||||
'created_at' => $now - 30,
|
||||
'updated_at' => $now - 20,
|
||||
]);
|
||||
$assert($service->tick(),
|
||||
'The corrupt undispatched recovery payload was not checked.');
|
||||
$corruptPayloadJob = CloudJob::findOrFail(502);
|
||||
$assert((bool) $corruptPayloadJob->finalization_incident
|
||||
&& (string) $corruptPayloadJob->finalization_error_code
|
||||
=== 'recovery_payload_unavailable'
|
||||
&& (string) $corruptPayloadJob->sealed_payload
|
||||
=== 'undispatched-finalizer-test:missing'
|
||||
&& (int) $corruptPayloadJob->lease_until >= time() + 290
|
||||
&& (int) $corruptPayloadJob->available_at >= time() + 290
|
||||
&& CloudJobService::blockingQueryForInstance(502)->exists(),
|
||||
'A corrupt PHP-only recovery payload lost its concrete incident or resource fence.');
|
||||
|
||||
echo "Cloud undispatched finalizer recovery tests passed.\n";
|
||||
}
|
||||
Loading…
Reference in New Issue