这里只配置宿主机默认网桥;公网 CIDR 在左侧宿主机的“公网地址池”抽屉中独立管理。
填写宿主机 Agent network_selectors 中预先配置的稳定 key;公网 CIDR 在“公网地址池”抽屉中管理。
public。实际 br0 或 libvirt network 只在 Agent 配置中映射;这里不能填写 bridge:br0。bridge:br0'),
+ 'Host network input must use the stable public Agent selector instead of a raw bridge name.');
$legacyPublicInputs = [
'host-public-pool', 'host-gateway', 'host-dns', 'host-reserved',
'host-vm-prefix',
diff --git a/web/tests/CloudInstanceMetadataTest.php b/web/tests/CloudInstanceMetadataTest.php
index 5726e2d3..f8686dba 100644
--- a/web/tests/CloudInstanceMetadataTest.php
+++ b/web/tests/CloudInstanceMetadataTest.php
@@ -15,7 +15,9 @@ $assert = static function ($condition, string $message): void {
};
$assert(CloudInstanceMetadata::state('shutdown') === 'shutdown'
- && CloudInstanceRuntimeService::normalizeState('shutdown') === 'shutdown',
+ && CloudInstanceRuntimeService::normalizeState('shutdown') === 'shutdown'
+ && CloudInstanceMetadata::state('pmsuspended') === 'pmsuspended'
+ && CloudInstanceRuntimeService::normalizeState('pmsuspended') === 'pmsuspended',
'Graceful shutdown was collapsed into an unknown or terminal state.');
$assert(CloudInstanceRuntimeService::stateAfterSuccessfulAction('running', 'shutdown')
=== 'shutdown'
diff --git a/web/tests/CloudProtocolTest.php b/web/tests/CloudProtocolTest.php
index f508e1a7..395b2e6b 100644
--- a/web/tests/CloudProtocolTest.php
+++ b/web/tests/CloudProtocolTest.php
@@ -5,6 +5,8 @@ namespace {
use App\Services\Cloud\CloudMoney;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudOperationErrorCatalog;
+ use App\Services\Cloud\CloudAgentError;
+ use App\Services\Cloud\CloudAgentOperationReconciler;
use App\Services\Cloud\CloudWorkerService;
$assert = function ($condition, $message) { if (!$condition) { throw new RuntimeException($message); } };
$assert(CloudMoney::cents('9.99') + CloudMoney::cents('0.01') === 1000, 'Money arithmetic must be exact.');
@@ -14,7 +16,20 @@ namespace {
}
$assert(CloudWorkerService::disposition(['status' => 'failed'], true) === 'uncertain', 'Unknown creation failure must not refund.');
$assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => false], true) === 'uncertain', 'Explicitly unsafe creation failure must not refund.');
- $assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => true], true) === 'failed', 'Confirmed absent creation must refund.');
+ $assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => true], true) === 'uncertain', 'A legacy refund hint bypassed managed-artifact absence evidence.');
+ $assert(CloudWorkerService::disposition([
+ 'status' => 'failed',
+ 'result' => ['creation_absent' => true],
+ ], true) === 'uncertain',
+ 'Create failure without managed-artifact evidence was refundable.');
+ $assert(CloudWorkerService::disposition([
+ 'status' => 'failed',
+ 'result' => [
+ 'creation_absent' => true,
+ 'managed_artifacts_absent' => true,
+ ],
+ ], true) === 'failed',
+ 'Confirmed create absence did not become a terminal failure.');
$assert(CloudWorkerService::disposition([
'status' => 'succeeded', 'error_code' => 'reinstall_cleanup_pending',
'result' => ['reinstall_committed' => true, 'cleanup_pending' => true],
@@ -24,12 +39,47 @@ namespace {
'status' => 'succeeded', 'result' => ['vm' => ['state' => 'running']],
], false, 'reinstall') === 'succeeded',
'A normal reinstall was changed to uncertain.');
+ $assert(CloudWorkerService::disposition([
+ 'status' => 'succeeded',
+ 'result' => [
+ 'reinstall_committed' => true,
+ 'cleanup_pending' => false,
+ ],
+ ], false, 'reinstall') === 'succeeded',
+ 'A clean Agent reinstall result was changed to uncertain.');
$assert(CloudWorkerService::disposition([
'status' => 'failed',
'error_code' => 'reinstall_cleanup_pending',
'result' => ['reinstall_committed' => true, 'cleanup_pending' => true],
], false, 'reinstall') === 'uncertain',
'A failed envelope with a committed reinstall marker was replayable.');
+ $uncertainOperation = [
+ 'operation_id' => 'operation-reconcile-failure',
+ 'status' => 'uncertain',
+ ];
+ $failingReconcilerClient = new class {
+ public function request(): array
+ {
+ throw new CloudAgentError(
+ 'reconcile unavailable', 503, 'agent_disconnected', true, 503
+ );
+ }
+ };
+ $assert(CloudAgentOperationReconciler::ifUncertain(
+ $failingReconcilerClient,
+ 'operation-reconcile-failure',
+ ['user_id' => 1],
+ $uncertainOperation
+ ) === $uncertainOperation,
+ 'A failed reconciliation request downgraded an uncertain operation.');
+ foreach (['delete', 'reinstall', 'instance_settings',
+ 'network_change', 'firewall_apply'] as $uncertainKind) {
+ $assert(CloudWorkerService::disposition([
+ 'status' => 'uncertain', 'safe_to_refund' => true,
+ ], false, $uncertainKind) === 'uncertain',
+ 'An ambiguous ' . $uncertainKind
+ . ' operation was converted to a terminal failure.');
+ }
foreach (['shortA1!', 'longwithoutupper1!', 'ALLUPPERCASE!123', 'LongWithoutSymbol123',
'NoDigitsLong!Aa', "StrongPassword!1\n", 'Strong Password!123',
'StrongPassword!123含中文', str_repeat('a', 126) . 'A1!'] as $bad) {
diff --git a/web/tests/CloudRescueTemplateImportStateMachineTest.php b/web/tests/CloudRescueTemplateImportStateMachineTest.php
index baf79512..6c0ac359 100644
--- a/web/tests/CloudRescueTemplateImportStateMachineTest.php
+++ b/web/tests/CloudRescueTemplateImportStateMachineTest.php
@@ -8,6 +8,7 @@ namespace App\Services\Cloud {
public array $requests = [];
public array $operations = [];
public string $mode = 'running';
+ public ?array $reconcileResponse = null;
public $onRequest = null;
public function request(string $method, string $target, array $actor,
@@ -27,6 +28,10 @@ namespace App\Services\Cloud {
'agent_busy', true, 503, false, true);
}
$this->operations[$operationId] = $templateId;
+ if ($this->mode === 'ambiguous_replay') {
+ throw new CloudAgentError('nonce may have dispatched', 502,
+ 'replayed_request', false, 401);
+ }
if ($this->mode === 'transport') {
throw new CloudAgentError('transport uncertain', 502,
'agent_transport_error', true);
@@ -44,6 +49,21 @@ namespace App\Services\Cloud {
throw new CloudAgentError('transport uncertain', 502,
'agent_transport_error', true);
}
+ } elseif ($method === 'POST'
+ && preg_match(
+ '#^/v1/operations/([A-Za-z0-9_-]+)/reconcile$#D',
+ $target, $match)) {
+ $operationId = rawurldecode($match[1]);
+ $templateId = $this->operations[$operationId] ?? '';
+ if ($templateId === '') {
+ throw new CloudAgentError('operation missing', 404,
+ 'operation_not_found', false, 404);
+ }
+ return ['operation_id' => $operationId]
+ + ($this->reconcileResponse ?? [
+ 'status' => 'uncertain',
+ 'error' => ['code' => 'operation_uncertain'],
+ ]);
} else {
throw new \RuntimeException('Unexpected fake Agent request: '
. $method . ' ' . $target);
@@ -69,6 +89,13 @@ namespace App\Services\Cloud {
],
];
}
+ if ($this->mode === 'uncertain') {
+ return [
+ 'operation_id' => $operationId,
+ 'status' => 'uncertain',
+ 'error' => ['code' => 'operation_uncertain'],
+ ];
+ }
return ['operation_id' => $operationId, 'status' => 'running'];
}
}
@@ -189,6 +216,28 @@ namespace {
&& $busyAgent->operations === [],
'Definitive pre-dispatch rescue import was left for impossible reconciliation.');
+ $replayedAgent = new RescueImportFakeAgent();
+ $replayedAgent->mode = 'ambiguous_replay';
+ CloudAgentSettingsService::$clients[14] = $replayedAgent;
+ $replayed = CloudRescueTemplateImportService::start(
+ 14, 'remote', 'Replay ambiguous rescue',
+ 'https://images.example.com/replay-ambiguous.iso', '', '', $actor
+ );
+ $replayedRow = CloudRescueTemplateImport::query()
+ ->where('operation_id', (string) $replayed['operation_id'])->first();
+ $assert($replayed['status'] === 'running'
+ && (string) $replayedRow->state === 'running'
+ && (string) $replayedRow->error_code === 'replayed_request'
+ && $requestCount($replayedAgent, 'POST') === 1,
+ 'Ambiguous non-retryable rescue import was made terminal.');
+ $replayedAgent->mode = 'success';
+ $replayedCompleted = CloudRescueTemplateImportService::job(
+ 14, (string) $replayed['operation_id'], $actor
+ );
+ $assert($replayedCompleted['status'] === 'succeeded'
+ && $requestCount($replayedAgent, 'POST') === 1,
+ 'Ambiguous rescue import was replayed instead of polled by operation ID.');
+
// Reconciliation uses the exact saved operation and terminal rows are
// read-only; no later call is allowed to issue another import POST.
$remoteAgent->mode = 'success';
@@ -209,6 +258,72 @@ namespace {
. $remote['operation_id'],
'Rescue import reconciliation changed or replayed its operation.');
+ // GET uncertainty is resolved only through POST /reconcile for the same
+ // operation. The original rescue import POST remains single-shot.
+ $reconcileAgent = new RescueImportFakeAgent();
+ CloudAgentSettingsService::$clients[12] = $reconcileAgent;
+ $reconcileImport = CloudRescueTemplateImportService::start(
+ 12, 'remote', 'Reconcile rescue',
+ 'https://images.example.com/reconcile.iso', '', '', $actor
+ );
+ $reconcileAgent->mode = 'uncertain';
+ $reconcileAgent->reconcileResponse = [
+ 'status' => 'succeeded',
+ 'result' => [
+ 'id' => (string) $reconcileImport['template_id'],
+ 'name' => 'Reconcile rescue',
+ 'size_bytes' => 1048576,
+ 'sha256' => str_repeat('a', 64),
+ ],
+ ];
+ $beforeReconcilePoll = count($reconcileAgent->requests);
+ $reconcileCompleted = CloudRescueTemplateImportService::job(
+ 12, (string) $reconcileImport['operation_id'], $actor
+ );
+ $reconcileRequests = array_slice(
+ $reconcileAgent->requests, $beforeReconcilePoll
+ );
+ $importPosts = array_filter($reconcileAgent->requests,
+ static fn (array $request): bool => $request['method'] === 'POST'
+ && $request['target'] === '/v1/rescue-templates');
+ $assert($reconcileCompleted['status'] === 'succeeded'
+ && count($importPosts) === 1
+ && count($reconcileRequests) === 2
+ && $reconcileRequests[0]['method'] === 'GET'
+ && $reconcileRequests[0]['target'] === '/v1/operations/'
+ . $reconcileImport['operation_id']
+ && $reconcileRequests[1]['method'] === 'POST'
+ && $reconcileRequests[1]['target'] === '/v1/operations/'
+ . $reconcileImport['operation_id'] . '/reconcile',
+ 'Rescue import uncertainty was replayed or reconciled under another operation.');
+
+ $trueUncertainAgent = new RescueImportFakeAgent();
+ CloudAgentSettingsService::$clients[13] = $trueUncertainAgent;
+ $trueUncertainImport = CloudRescueTemplateImportService::start(
+ 13, 'remote', 'Uncertain rescue',
+ 'https://images.example.com/uncertain.iso', '', '', $actor
+ );
+ $trueUncertainAgent->mode = 'uncertain';
+ $trueUncertainAgent->reconcileResponse = [
+ 'status' => 'uncertain',
+ 'error' => ['code' => 'operation_uncertain'],
+ ];
+ $trueUncertain = CloudRescueTemplateImportService::job(
+ 13, (string) $trueUncertainImport['operation_id'], $actor
+ );
+ $requestsAtUncertain = count($trueUncertainAgent->requests);
+ $trueUncertainAgain = CloudRescueTemplateImportService::job(
+ 13, (string) $trueUncertainImport['operation_id'], $actor
+ );
+ $trueUncertainPosts = array_filter($trueUncertainAgent->requests,
+ static fn (array $request): bool => $request['method'] === 'POST'
+ && $request['target'] === '/v1/rescue-templates');
+ $assert($trueUncertain['status'] === 'uncertain'
+ && $trueUncertainAgain['status'] === 'uncertain'
+ && count($trueUncertainPosts) === 1
+ && count($trueUncertainAgent->requests) === $requestsAtUncertain,
+ 'A genuinely uncertain rescue import was retried or left pollable.');
+
// A retryable transport failure may have crossed the boundary. Preserve
// the upload operation, then lock it uncertain if Agent has no record.
$uploadAgent = new RescueImportFakeAgent();
@@ -289,9 +404,13 @@ namespace {
40, $staleOperation, $actor
);
$assert($stale['status'] === 'uncertain'
- && $stale['error_code'] === 'import_dispatch_unconfirmed'
- && $staleAgent->requests === [],
- 'Stale dispatch boundary caused an unsafe import replay.');
+ && $stale['error_code'] === 'operation_not_found'
+ && count($staleAgent->requests) === 1
+ && $staleAgent->requests[0]['method'] === 'GET'
+ && $staleAgent->requests[0]['target']
+ === '/v1/operations/' . $staleOperation
+ && $requestCount($staleAgent, 'POST') === 0,
+ 'Stale sending boundary was not checked by operation ID without replay.');
// A response produced from a stale concurrent poll must not overwrite a
// terminal state committed while that request was in flight.
diff --git a/web/tests/CloudRuntimeHeartbeatTest.php b/web/tests/CloudRuntimeHeartbeatTest.php
index 06c9e99d..904b882e 100644
--- a/web/tests/CloudRuntimeHeartbeatTest.php
+++ b/web/tests/CloudRuntimeHeartbeatTest.php
@@ -80,7 +80,7 @@ try {
'Expired policy observations must request investigation without claiming a live process.');
$now += 700;
$assert($checks($directory)['worker']['status'] === 'busy',
- 'A normal 900-second Agent call was incorrectly declared stopped.');
+ 'A normal long PHP-to-Agent request was incorrectly declared stopped.');
$normal->busy('notification');
$now += 300;
$assert(str_contains($checks($directory)['worker']['message'], '邮件通知'),
diff --git a/web/tests/CloudTemplateErrorContractTest.php b/web/tests/CloudTemplateErrorContractTest.php
index f5000a12..bfd9a901 100644
--- a/web/tests/CloudTemplateErrorContractTest.php
+++ b/web/tests/CloudTemplateErrorContractTest.php
@@ -32,7 +32,7 @@ $assert(is_string($catalog)
&& str_contains($catalog, 'public static function deleteJob(')
&& str_contains($catalog, "->where('state', 'delete_dispatch')")
&& str_contains($catalog, "'state' => 'delete_sending'")
- && str_contains($catalog, "->whereIn('state', ['delete_dispatch', 'delete_sending'])")
+ && str_contains($catalog, "->where('state', 'delete_sending')")
&& str_contains($catalog, "'error_code' => 'delete_dispatch_unconfirmed'")
&& str_contains($catalog, "->where('state', 'delete_running')")
&& str_contains($catalog, 'CloudAgentCatalogDeletion::confirms(')
diff --git a/web/tests/CloudTemplateMetadataSyncStateMachineTest.php b/web/tests/CloudTemplateMetadataSyncStateMachineTest.php
new file mode 100644
index 00000000..7fa7a89a
--- /dev/null
+++ b/web/tests/CloudTemplateMetadataSyncStateMachineTest.php
@@ -0,0 +1,193 @@
+requests[] = compact('method', 'target', 'actor', 'payload');
+ if (is_callable($this->beforeResponse)) {
+ ($this->beforeResponse)($method, $target, $actor, $payload);
+ }
+ $operationId = (string) ($payload['operation_id']
+ ?? $actor['operation_id'] ?? basename($target));
+ if ($method === 'POST') {
+ return ['operation_id' => basename(dirname($target)),
+ 'status' => 'succeeded', 'result' => $this->result];
+ }
+ if ($this->mode === 'wrong_operation') {
+ $operationId = 'wrong-operation-id';
+ }
+ return [
+ 'operation_id' => $operationId,
+ 'status' => $this->mode === 'uncertain'
+ ? 'uncertain' : 'succeeded',
+ 'result' => $this->result,
+ ];
+ }
+
+ public array $result = [];
+ }
+
+ final class CloudAgentSettingsService
+ {
+ public static ?TemplateMetadataSyncFakeAgent $client = null;
+
+ public static function clientForHost(int $hostId,
+ float $timeoutSeconds = 20.0): TemplateMetadataSyncFakeAgent
+ {
+ if ($hostId !== 7 || self::$client === null) {
+ throw new \RuntimeException('Missing fake Agent');
+ }
+ return self::$client;
+ }
+ }
+}
+
+namespace {
+ require dirname(__DIR__) . '/vendor/autoload.php';
+
+ use App\Models\CloudTemplateReplica;
+ use App\Services\Cloud\CloudAgentSettingsService;
+ use App\Services\Cloud\CloudTemplateCatalogService;
+ use App\Services\Cloud\TemplateMetadataSyncFakeAgent;
+ 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_template_replicas',
+ static function (Blueprint $table): void {
+ $table->integer('host_id');
+ $table->string('template_id');
+ $table->integer('revision');
+ $table->string('generation_token');
+ $table->string('state');
+ $table->integer('image_bytes')->default(0);
+ $table->string('sha256')->default('');
+ $table->string('operation_id')->default('');
+ $table->string('error_code')->default('');
+ $table->integer('created_at');
+ $table->integer('updated_at');
+ $table->primary(['host_id', 'template_id']);
+ });
+
+ $generation = str_repeat('a', 32);
+ $id = 'debian-13-metadata-sync';
+ $now = time();
+ Capsule::table('cloud_template_replicas')->insert([
+ 'host_id' => 7,
+ 'template_id' => $id,
+ 'revision' => 1,
+ 'generation_token' => $generation,
+ 'state' => 'active',
+ 'image_bytes' => 4096,
+ 'sha256' => str_repeat('b', 64),
+ 'operation_id' => bin2hex(random_bytes(16)),
+ 'error_code' => '',
+ 'created_at' => $now,
+ 'updated_at' => $now,
+ ]);
+
+ $snapshot = static fn (int $revision, string $name): array => [
+ 'id' => $id,
+ 'name' => $name,
+ 'revision' => $revision,
+ 'generation_token' => $generation,
+ ];
+ $result = static fn (int $revision, string $name): array => [
+ 'id' => $id,
+ 'name' => $name,
+ 'revision' => $revision,
+ 'generation_token' => $generation,
+ ];
+ $actor = ['user_id' => 1, 'can_manage' => true];
+ $agent = new TemplateMetadataSyncFakeAgent();
+ CloudAgentSettingsService::$client = $agent;
+
+ $agent->result = $result(2, 'Debian 13 renamed');
+ $synced = CloudTemplateCatalogService::synchronizeMetadata(
+ $snapshot(2, 'Debian 13 renamed'), $actor
+ );
+ $row = CloudTemplateReplica::query()->where('host_id', 7)
+ ->where('template_id', $id)->first();
+ $operationId = (string) $row->operation_id;
+ $assert($synced['replication_pending'] === false
+ && (int) $row->revision === 2
+ && (string) $row->state === 'active'
+ && ($agent->requests[0]['actor']['operation_id'] ?? null)
+ === $operationId
+ && ($agent->requests[0]['payload']['operation_id'] ?? null)
+ === $operationId,
+ 'Metadata synchronization did not bind success to its operation ID.');
+
+ $agent->mode = 'wrong_operation';
+ $agent->result = $result(3, 'Debian 13 wrong operation');
+ $mismatch = CloudTemplateCatalogService::synchronizeMetadata(
+ $snapshot(3, 'Debian 13 wrong operation'), $actor
+ );
+ $row->refresh();
+ $assert($mismatch['replication_pending'] === true
+ && (int) $row->revision === 2
+ && (string) $row->state === 'stale'
+ && (string) $row->error_code === 'agent_sync_failed',
+ 'Mismatched metadata operation was accepted as a successful replica.');
+
+ // A later revision may commit while an older request is still in flight.
+ // Neither its late failure nor late success may regress that newer row.
+ $agent->beforeResponse = static function () use ($id, $generation): void {
+ Capsule::table('cloud_template_replicas')->where('host_id', 7)
+ ->where('template_id', $id)->update([
+ 'revision' => 5,
+ 'generation_token' => $generation,
+ 'state' => 'active',
+ 'operation_id' => 'newer-operation-id',
+ 'error_code' => '',
+ 'updated_at' => time(),
+ ]);
+ };
+ $agent->result = $result(4, 'Debian 13 older response');
+ CloudTemplateCatalogService::synchronizeMetadata(
+ $snapshot(4, 'Debian 13 older response'), $actor
+ );
+ $row->refresh();
+ $assert((int) $row->revision === 5
+ && (string) $row->state === 'active'
+ && (string) $row->operation_id === 'newer-operation-id',
+ 'Late metadata failure regressed a newer replica revision.');
+
+ $agent->mode = 'uncertain';
+ $agent->beforeResponse = null;
+ $agent->result = $result(6, 'Debian 13 reconciled');
+ $before = count($agent->requests);
+ $reconciled = CloudTemplateCatalogService::synchronizeMetadata(
+ $snapshot(6, 'Debian 13 reconciled'), $actor
+ );
+ $requests = array_slice($agent->requests, $before);
+ $row->refresh();
+ $assert($reconciled['replication_pending'] === false
+ && (int) $row->revision === 6
+ && count($requests) === 2
+ && $requests[0]['method'] === 'PATCH'
+ && $requests[1]['method'] === 'POST'
+ && str_ends_with($requests[1]['target'], '/reconcile'),
+ 'Uncertain metadata synchronization was replayed or not reconciled.');
+
+ echo "Template metadata operation binding and CAS tests passed.\n";
+}
diff --git a/web/tests/CloudTrafficCollectionTest.php b/web/tests/CloudTrafficCollectionTest.php
index a4fd1a3b..7e03bdaf 100644
--- a/web/tests/CloudTrafficCollectionTest.php
+++ b/web/tests/CloudTrafficCollectionTest.php
@@ -148,7 +148,7 @@ namespace {
$instance->created_at = $instance->updated_at = $now;
$instance->save();
- $metrics = static function (int $timestamp, int $cpu, int $memory,
+ $metrics = static function (int $timestamp, int $cpu, ?int $memory,
int $read, int $write, int $rx, int $tx) use ($uuid): array {
return [
'uuid' => $uuid,
@@ -167,6 +167,10 @@ namespace {
106_000, 53_000, 112_000, 56_000);
$resetMetrics = $metrics($resetAt, 100_000_000, 524_288,
100, 50, 1_000, 500);
+ $unavailableMemoryAt = $resetAt + 1;
+ $unavailableMemoryMetrics = $metrics(
+ $unavailableMemoryAt, 100_000_000, null, 100, 50, 1_000, 500
+ );
$log = $capsule->connection('log');
$log->table('cloud_vm_metric_samples')->insert([
@@ -256,14 +260,62 @@ namespace {
&& $resetSample->network_tx_bps === null,
'Raw Agent counter reset lowered PHP billing totals or emitted a false rate spike.');
+ $store->invoke(null, $log, $instance, $unavailableMemoryMetrics);
+ $unavailableMemorySample = $log->table('cloud_vm_metric_samples')
+ ->where('sampled_at', $unavailableMemoryAt)->first();
+ $total = $log->table('cloud_vm_traffic_totals')->first();
+ $assert($unavailableMemorySample !== null
+ && $unavailableMemorySample->memory_used_mib === null
+ && (int) $total->download_rx_bytes === 113_000
+ && (int) $total->upload_tx_bytes === 56_500,
+ 'Unavailable balloon statistics fabricated memory usage or disrupted traffic totals.');
+
$duplicate = $metrics($resetAt, 999_000_000, 999_999,
- 999_999, 999_999, 999_999, 999_999);
+ 999_999, 999_999, 1_000, 500);
$store->invoke(null, $log, $instance, $duplicate);
$total = $log->table('cloud_vm_traffic_totals')->first();
$assert((int) $total->download_rx_bytes === 113_000
&& (int) $total->upload_tx_bytes === 56_500
- && $log->table('cloud_vm_metric_samples')->count() === 3,
- 'Duplicate or older collected_at data overwrote the durable totals.');
+ && $log->table('cloud_vm_metric_samples')->count() === 4,
+ 'A repeated durable Agent counter was charged twice.');
+
+ $futureObservedAt = $now + 120;
+ $log->table('cloud_vm_traffic_totals')->update([
+ 'last_observed_at' => $futureObservedAt,
+ ]);
+ $rollbackMetrics = $metrics($now, 1_000_000_000, 786_432,
+ 1_000, 500, 1_500, 700);
+ $rollbackHistory = [];
+ $rollbackMock = new MockHandler([
+ new Response(200, ['Content-Type' => 'application/json'],
+ json_encode($rollbackMetrics, JSON_THROW_ON_ERROR)),
+ new Response(200, ['Content-Type' => 'application/json'],
+ json_encode($rollbackMetrics, JSON_THROW_ON_ERROR)),
+ ]);
+ $rollbackStack = HandlerStack::create($rollbackMock);
+ $rollbackStack->push(Middleware::history($rollbackHistory));
+ $rollbackAgent = new CloudAgentClient('7',
+ 'metric-test-secret-at-least-32-bytes', new Client([
+ 'handler' => $rollbackStack, 'http_errors' => false,
+ ]), 20.0, 'http://127.0.0.1:8001/internal/agent/request',
+ 'test-gateway-secret-at-least-32-bytes');
+ $rollbackFirst = CloudTrafficService::collect(1, $rollbackAgent);
+ $rollbackSecond = CloudTrafficService::collect(1, $rollbackAgent);
+ $total = $log->table('cloud_vm_traffic_totals')->first();
+ $rollbackBaseline = json_decode(
+ (string) $total->network_baseline_json, true,
+ flags: JSON_THROW_ON_ERROR
+ );
+ $assert($rollbackFirst['observed'] === 1
+ && $rollbackSecond['observed'] === 1
+ && count($rollbackHistory) === 2
+ && (int) $total->download_rx_bytes === 113_500
+ && (int) $total->upload_tx_bytes === 56_700
+ && (int) $total->last_observed_at === $futureObservedAt
+ && ($rollbackBaseline['last_agent_rx_bytes'] ?? null) === 1_500
+ && ($rollbackBaseline['last_agent_tx_bytes'] ?? null) === 700
+ && $log->table('cloud_vm_metric_samples')->count() === 4,
+ 'A future observation blocked clock-rollback collection, duplicated billing, or inserted an out-of-order chart point.');
$wrongUuid = $resetMetrics;
$wrongUuid['uuid'] = '22222222-2222-4222-8222-222222222222';
@@ -272,7 +324,7 @@ namespace {
), 502, 'Metrics for another VM UUID were accepted.');
$log->table('cloud_vm_traffic_totals')->update(['user_id' => 18]);
$newer = $resetMetrics;
- $newer['collected_at'] = gmdate('Y-m-d\TH:i:s\Z', $resetAt + 1);
+ $newer['collected_at'] = gmdate('Y-m-d\TH:i:s\Z', $resetAt + 2);
$expect(static fn () => $store->invoke(
null, $log, $instance, $newer
), 409, 'A traffic total owned by another user was overwritten.');
@@ -299,8 +351,8 @@ namespace {
$instance->traffic_synced_at = 0;
$instance->save();
$assert(CloudTrafficService::sync(10) === 1
- && (int) $instance->fresh()->lifetime_download_bytes === 113_000
- && (int) $instance->fresh()->lifetime_upload_bytes === 56_500,
+ && (int) $instance->fresh()->lifetime_download_bytes === 113_500
+ && (int) $instance->fresh()->lifetime_upload_bytes === 56_700,
'Owner/host/UUID-bound PHP totals were not synchronized to billing state.');
$log->table('cloud_vm_metric_samples')->insert([
diff --git a/web/tests/CloudUserISOContractTest.php b/web/tests/CloudUserISOContractTest.php
index 940999ff..ea182759 100644
--- a/web/tests/CloudUserISOContractTest.php
+++ b/web/tests/CloudUserISOContractTest.php
@@ -67,10 +67,10 @@ $assert(str_contains($service, 'final class CloudUserIsoService')
&& str_contains($service, 'CloudAgentSettingsService::enabledHostIds()')
&& str_contains($service, "->request('POST', '/v1/user-isos'")
&& str_contains($service, "->request('GET', '/v1/operations/'")
- && str_contains($service, "->request('DELETE', '/v1/user-isos/'")
+ && str_contains($service, "'DELETE', '/v1/user-isos/'")
&& str_contains($service, "->where('state', 'delete_dispatch')")
&& str_contains($service, "'state' => 'delete_sending'")
- && str_contains($service, "->whereIn('state', ['delete_dispatch', 'delete_sending'])")
+ && str_contains($service, "->where('state', 'delete_sending')")
&& str_contains($service, "'error_code' => 'delete_dispatch_unconfirmed'")
&& str_contains($service, "->where('state', 'delete_running')")
&& str_contains($service, "CloudAgentCatalogDeletion::confirms(")