diff --git a/docs/TRAFFIC_POOL.md b/docs/TRAFFIC_POOL.md index fa71c8fd..0b50c0f3 100644 --- a/docs/TRAFFIC_POOL.md +++ b/docs/TRAFFIC_POOL.md @@ -86,6 +86,11 @@ selects the first trustworthy observation after a service-period boundary, it freezes that cumulative total in a sparse immutable anchor keyed by the exact service period. The anchor, rather than an indefinitely retained hourly row, is the durable proof used after maintenance migration or later compaction. +Hourly checkpoints remain hot for at least 72 hours. Retention removes an old +row only when the matching daily first/last counters contain it, every open +service-period boundary that could depend on it has a persisted base or valid +anchor, and the pool cursor is not in attention. A missing proof retains the +hourly row and raises a retention warning; it never guesses a baseline. The policy state is one aggregate execution projection per instance; reason rows contain facts only. This avoids assigning one NIC mutation to an diff --git a/web/app/Services/Cloud/CloudLifecycleService.php b/web/app/Services/Cloud/CloudLifecycleService.php index cfb593d9..54e8894e 100644 --- a/web/app/Services/Cloud/CloudLifecycleService.php +++ b/web/app/Services/Cloud/CloudLifecycleService.php @@ -16,6 +16,7 @@ final class CloudLifecycleService private int $rescueReconcileCursor = 0; private int $trafficUsageScanCursor = 0; private int $trafficPeriodScanCursor = 0; + private int $trafficCheckpointRetentionCursor = 0; public function __construct(private ?CloudRuntimeHeartbeat $heartbeat = null) { @@ -253,6 +254,27 @@ final class CloudLifecycleService error_log('cloud traffic settlement retention unavailable: ' . get_class($error)); } + $this->heartbeat?->busy('traffic_checkpoint_compaction'); + try { + $checkpointRetention = CloudTrafficCheckpointRetention::prune( + $batchSize, + time(), + $this->trafficCheckpointRetentionCursor + ); + $this->trafficCheckpointRetentionCursor = max( + 0, + (int) ($checkpointRetention['next_cursor'] ?? 0) + ); + if ($checkpointRetention['blocked'] !== []) { + $this->observeFailure('traffic_retention_failed'); + } + } catch (\Throwable $error) { + $this->observeFailure('traffic_retention_failed'); + // Hourly history is retained on every ambiguity; compaction must + // never gate live accounting, billing or instance policy. + error_log('cloud traffic checkpoint retention unavailable: ' + . get_class($error)); + } // Power state is an observation cache, not a billing decision. Each // host is contacted through its own Agent settings, so one unavailable // host must not gate database-only billing or other hosts. diff --git a/web/app/Services/Cloud/CloudTrafficCheckpointRetention.php b/web/app/Services/Cloud/CloudTrafficCheckpointRetention.php new file mode 100644 index 00000000..f2ba4bd1 --- /dev/null +++ b/web/app/Services/Cloud/CloudTrafficCheckpointRetention.php @@ -0,0 +1,279 @@ + + * } + */ + public static function prune( + int $limit = 200, + ?int $now = null, + int $afterInstanceId = 0 + ): array { + $now ??= time(); + if ($now < self::RETENTION_SECONDS) { + throw new \InvalidArgumentException( + 'traffic_checkpoint_retention_clock_invalid' + ); + } + $limit = max(1, min(self::MAX_INSTANCE_BATCH, $limit)); + $afterInstanceId = max(0, $afterInstanceId); + $cutoff = $now - self::RETENTION_SECONDS; + $log = User::getConnectionResolver()->connection('log'); + foreach ([ + 'cloud_vm_traffic_checkpoints', + 'cloud_vm_traffic_daily_checkpoints', + 'cloud_vm_traffic_boundary_anchors', + ] as $table) { + if (!$log->getSchemaBuilder()->hasTable($table)) { + throw new \RuntimeException( + 'traffic_checkpoint_retention_schema_missing' + ); + } + } + $instanceIds = self::candidateInstanceIds( + $log, $cutoff, $afterInstanceId, $limit + ); + if ($instanceIds === [] && $afterInstanceId > 0) { + $instanceIds = self::candidateInstanceIds($log, $cutoff, 0, $limit); + } + $deleted = 0; + $skipped = 0; + $scannedRows = 0; + $blocked = []; + foreach ($instanceIds as $instanceId) { + try { + $result = self::pruneInstance( + $log, $instanceId, $cutoff + ); + $deleted += $result['deleted']; + $skipped += $result['skipped']; + $scannedRows += $result['scanned']; + foreach ($result['blocked'] as $code) { + $blocked[] = [ + 'instance_id' => $instanceId, + 'code' => $code, + ]; + } + } catch (\Throwable $error) { + $code = str_starts_with($error->getMessage(), 'traffic_') + ? $error->getMessage() + : 'traffic_checkpoint_retention_failed'; + $blocked[] = [ + 'instance_id' => $instanceId, + 'code' => $code, + ]; + } + } + return [ + 'scanned_instances' => count($instanceIds), + 'scanned_rows' => $scannedRows, + 'deleted' => $deleted, + 'skipped' => $skipped, + 'next_cursor' => count($instanceIds) < $limit + ? 0 : max($instanceIds), + 'blocked' => $blocked, + ]; + } + + /** @return list */ + private static function candidateInstanceIds($log, int $cutoff, + int $afterInstanceId, int $limit): array + { + return $log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', '>', $afterInstanceId) + ->where('first_observed_at', '<=', $cutoff) + ->distinct()->orderBy('instance_id')->limit($limit) + ->pluck('instance_id') + ->map(static fn ($id): int => (int) $id) + ->filter(static fn (int $id): bool => $id > 0) + ->values()->all(); + } + + /** + * @return array{scanned:int,deleted:int,skipped:int,blocked:list} + */ + private static function pruneInstance($log, int $instanceId, + int $cutoff): array + { + $connection = CloudInstance::query()->getConnection(); + return $connection->transaction(static function () use ( + $log, $instanceId, $cutoff + ): array { + $instance = CloudInstance::where('id', $instanceId) + ->lockForUpdate()->first([ + 'id', 'user_id', 'lifetime_download_bytes', + 'lifetime_upload_bytes', + ]); + if ($instance === null) { + return self::blockedResult( + 'traffic_checkpoint_instance_missing' + ); + } + $cursor = CloudTrafficInstanceCursor::where( + 'instance_id', $instanceId + )->lockForUpdate()->first(['instance_id', 'user_id', 'state']); + if ($cursor !== null + && ((int) $cursor->user_id !== (int) $instance->user_id + || (string) $cursor->state === 'attention')) { + return self::blockedResult( + 'traffic_checkpoint_cursor_attention' + ); + } + $periods = CloudServicePeriod::where('instance_id', $instanceId) + ->whereIn('status', ['scheduled', 'active', 'exhausted']) + ->where('starts_at', '<', $cutoff) + ->lockForUpdate()->get([ + 'id', 'instance_id', 'user_id', 'starts_at', + 'download_base_bytes', 'upload_base_bytes', 'status', + ]); + return $log->transaction(static function () use ( + $log, $instance, $instanceId, $cutoff, $periods + ): array { + $rows = $log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', $instanceId) + ->where('first_observed_at', '<=', $cutoff) + ->orderBy('first_observed_at') + ->limit(self::MAX_ROWS_PER_INSTANCE) + ->lockForUpdate()->get(); + if ($rows->isEmpty()) { + return [ + 'scanned' => 0, 'deleted' => 0, 'skipped' => 0, + 'blocked' => [], + ]; + } + $days = $rows->map(static fn ($row): int => + intdiv((int) $row->first_observed_at, 86400) * 86400 + )->unique()->values()->all(); + $dailyRows = $log->table( + 'cloud_vm_traffic_daily_checkpoints' + )->where('instance_id', $instanceId) + ->whereIn('checkpoint_day', $days) + ->lockForUpdate()->get()->keyBy('checkpoint_day'); + $periodIds = $periods->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $anchors = $periodIds === [] ? collect() : $log->table( + 'cloud_vm_traffic_boundary_anchors' + )->whereIn('service_period_id', $periodIds) + ->lockForUpdate()->get()->keyBy('service_period_id'); + $deleted = 0; + $skipped = 0; + $blocked = []; + foreach ($rows as $row) { + $code = self::rowBlocker( + $row, $instance, $dailyRows, $periods, $anchors + ); + if ($code !== null) { + $skipped++; + $blocked[$code] = true; + continue; + } + $removed = $log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', $instanceId) + ->where('host_id', (int) $row->host_id) + ->where('vm_uuid', $row->vm_uuid) + ->where('checkpoint_hour', + (int) $row->checkpoint_hour) + ->delete(); + if ($removed !== 1) { + throw new \RuntimeException( + 'traffic_checkpoint_delete_conflict' + ); + } + $deleted++; + } + return [ + 'scanned' => $rows->count(), + 'deleted' => $deleted, + 'skipped' => $skipped, + 'blocked' => array_keys($blocked), + ]; + }, 3); + }, 3); + } + + private static function rowBlocker($row, CloudInstance $instance, + $dailyRows, $periods, $anchors): ?string + { + if ((int) $row->user_id !== (int) $instance->user_id) { + return 'traffic_checkpoint_owner_mismatch'; + } + $observedAt = (int) $row->first_observed_at; + $download = (int) $row->download_rx_bytes; + $upload = (int) $row->upload_tx_bytes; + $day = intdiv($observedAt, 86400) * 86400; + $daily = $dailyRows->get($day); + if ($daily === null + || (int) $daily->user_id !== (int) $instance->user_id + || (int) $daily->first_observed_at > $observedAt + || (int) $daily->last_observed_at < $observedAt + || (int) $daily->first_download_rx_bytes > $download + || (int) $daily->last_download_rx_bytes < $download + || (int) $daily->first_upload_tx_bytes > $upload + || (int) $daily->last_upload_tx_bytes < $upload) { + return 'traffic_checkpoint_daily_evidence_missing'; + } + foreach ($periods as $period) { + if ((int) $period->starts_at >= $observedAt + || ($period->download_base_bytes !== null + && $period->upload_base_bytes !== null)) { + continue; + } + $anchor = $anchors->get((int) $period->id); + if ($anchor === null + || (int) $anchor->instance_id !== (int) $instance->id + || (int) $anchor->user_id !== (int) $instance->user_id + || (int) $anchor->boundary_at !== (int) $period->starts_at + || (int) $anchor->observed_at <= (int) $period->starts_at + || (int) $anchor->download_rx_bytes < 0 + || (int) $anchor->upload_tx_bytes < 0 + || (int) $anchor->download_rx_bytes + > (int) $instance->lifetime_download_bytes + || (int) $anchor->upload_tx_bytes + > (int) $instance->lifetime_upload_bytes + || !in_array((string) $anchor->source_kind, + ['hourly_checkpoint', 'metric_sample'], true)) { + return 'traffic_checkpoint_period_boundary_unfrozen'; + } + } + return null; + } + + /** @return array{scanned:int,deleted:int,skipped:int,blocked:list} */ + private static function blockedResult(string $code): array + { + return [ + 'scanned' => 0, + 'deleted' => 0, + 'skipped' => 1, + 'blocked' => [$code], + ]; + } +} diff --git a/web/tests/CloudTrafficCheckpointRetentionTest.php b/web/tests/CloudTrafficCheckpointRetentionTest.php new file mode 100644 index 00000000..32903ee4 --- /dev/null +++ b/web/tests/CloudTrafficCheckpointRetentionTest.php @@ -0,0 +1,211 @@ +addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'default'); +$capsule->addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'log'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); + +$main = $capsule->schema('default'); +$main->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('lifetime_download_bytes')->default(0); + $table->integer('lifetime_upload_bytes')->default(0); + $table->integer('traffic_synced_at')->default(0); +}); +$main->create('cloud_service_periods', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('user_id'); + $table->integer('starts_at'); + $table->integer('download_base_bytes')->nullable(); + $table->integer('upload_base_bytes')->nullable(); + $table->string('status'); +}); +$main->create('cloud_traffic_instance_cursors', + static function (Blueprint $table): void { + $table->integer('instance_id')->primary(); + $table->integer('user_id'); + $table->string('state'); + }); + +$logSchema = $capsule->schema('log'); +$logSchema->create('cloud_vm_traffic_checkpoints', + static function (Blueprint $table): void { + $table->integer('instance_id'); + $table->integer('host_id'); + $table->binary('vm_uuid'); + $table->integer('checkpoint_hour'); + $table->integer('user_id'); + $table->integer('first_observed_at'); + $table->integer('download_rx_bytes'); + $table->integer('upload_tx_bytes'); + $table->primary(['host_id', 'vm_uuid', 'checkpoint_hour']); + }); +$logSchema->create('cloud_vm_traffic_daily_checkpoints', + static function (Blueprint $table): void { + $table->integer('instance_id'); + $table->integer('user_id'); + $table->integer('checkpoint_day'); + $table->integer('first_observed_at'); + $table->integer('first_download_rx_bytes'); + $table->integer('first_upload_tx_bytes'); + $table->integer('last_observed_at'); + $table->integer('last_download_rx_bytes'); + $table->integer('last_upload_tx_bytes'); + $table->integer('sample_count'); + $table->primary(['instance_id', 'checkpoint_day']); + }); +$logSchema->create('cloud_vm_traffic_boundary_anchors', + static function (Blueprint $table): void { + $table->integer('service_period_id')->primary(); + $table->integer('instance_id'); + $table->integer('user_id'); + $table->integer('boundary_at'); + $table->integer('observed_at'); + $table->string('source_kind'); + $table->integer('download_rx_bytes'); + $table->integer('upload_tx_bytes'); + }); + +$now = 10 * 86400; +$cutoff = $now - CloudTrafficCheckpointRetention::RETENTION_SECONDS; +$uuid = CloudLogIdentity::uuid('11111111-1111-4111-8111-111111111111'); +$log = $capsule->connection('log'); + +$insertInstance = static function (int $id, string $cursorState = 'ready') + use ($capsule, $now): void { + $capsule->connection('default')->table('cloud_instances')->insert([ + 'id' => $id, + 'user_id' => 7, + 'lifetime_download_bytes' => 1000, + 'lifetime_upload_bytes' => 500, + 'traffic_synced_at' => $now, + ]); + $capsule->connection('default') + ->table('cloud_traffic_instance_cursors')->insert([ + 'instance_id' => $id, + 'user_id' => 7, + 'state' => $cursorState, + ]); +}; +$insertCheckpoint = static function (int $instanceId, int $observedAt, + bool $withDaily = true) use ($log, $uuid): void { + $day = intdiv($observedAt, 86400) * 86400; + $log->table('cloud_vm_traffic_checkpoints')->insert([ + 'instance_id' => $instanceId, + 'host_id' => $instanceId, + 'vm_uuid' => $uuid, + 'checkpoint_hour' => intdiv($observedAt, 3600) * 3600, + 'user_id' => 7, + 'first_observed_at' => $observedAt, + 'download_rx_bytes' => 400, + 'upload_tx_bytes' => 200, + ]); + if ($withDaily) { + $log->table('cloud_vm_traffic_daily_checkpoints')->insert([ + 'instance_id' => $instanceId, + 'user_id' => 7, + 'checkpoint_day' => $day, + 'first_observed_at' => $day + 60, + 'first_download_rx_bytes' => 300, + 'first_upload_tx_bytes' => 100, + 'last_observed_at' => $day + 23 * 3600, + 'last_download_rx_bytes' => 800, + 'last_upload_tx_bytes' => 400, + 'sample_count' => 10, + ]); + } +}; + +// Fully covered rows are safely removable and repeated cleanup is idempotent. +$insertInstance(1); +$insertCheckpoint(1, $cutoff - 3600); +$capsule->connection('default')->table('cloud_service_periods')->insert([ + 'id' => 1, 'instance_id' => 1, 'user_id' => 7, + 'starts_at' => $cutoff - 7200, + 'download_base_bytes' => 300, 'upload_base_bytes' => 100, + 'status' => 'active', +]); +$first = CloudTrafficCheckpointRetention::prune(20, $now); +$assert($first['deleted'] === 1 && $first['blocked'] === [] + && !$log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', 1)->exists(), + 'Verified hourly checkpoint was not pruned.'); +$repeat = CloudTrafficCheckpointRetention::prune(20, $now); +$assert($repeat['deleted'] === 0, + 'Repeated hourly checkpoint pruning was not idempotent.'); + +// Missing daily evidence is retained rather than guessed away. +$insertInstance(2); +$insertCheckpoint(2, $cutoff - 7200, false); +$missingDaily = CloudTrafficCheckpointRetention::prune(20, $now); +$assert($log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', 2)->exists() + && in_array('traffic_checkpoint_daily_evidence_missing', + array_column($missingDaily['blocked'], 'code'), true), + 'Checkpoint without daily evidence was deleted or not quarantined.'); + +// An unresolved service boundary blocks deletion until its immutable anchor +// exists; the anchor then makes the old hourly row disposable. +$insertInstance(3); +$observedAt = $cutoff - 10_800; +$insertCheckpoint(3, $observedAt); +$capsule->connection('default')->table('cloud_service_periods')->insert([ + 'id' => 3, 'instance_id' => 3, 'user_id' => 7, + 'starts_at' => $observedAt - 60, + 'download_base_bytes' => null, 'upload_base_bytes' => null, + 'status' => 'scheduled', +]); +$unfrozen = CloudTrafficCheckpointRetention::prune(20, $now); +$assert($log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', 3)->exists() + && in_array('traffic_checkpoint_period_boundary_unfrozen', + array_column($unfrozen['blocked'], 'code'), true), + 'Unfrozen service-period boundary did not retain its hourly evidence.'); +$log->table('cloud_vm_traffic_boundary_anchors')->insert([ + 'service_period_id' => 3, + 'instance_id' => 3, + 'user_id' => 7, + 'boundary_at' => $observedAt - 60, + 'observed_at' => $observedAt, + 'source_kind' => 'hourly_checkpoint', + 'download_rx_bytes' => 400, + 'upload_tx_bytes' => 200, +]); +$anchored = CloudTrafficCheckpointRetention::prune(20, $now); +$assert($anchored['deleted'] === 1 + && !$log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', 3)->exists(), + 'Frozen service-period boundary did not release old hourly evidence.'); + +// Attention is a fail-closed accounting state, so no historical evidence is +// removed until the original cursor is reconciled. +$insertInstance(4, 'attention'); +$insertCheckpoint(4, $cutoff - 14_400); +$attention = CloudTrafficCheckpointRetention::prune(20, $now); +$assert($log->table('cloud_vm_traffic_checkpoints') + ->where('instance_id', 4)->exists() + && in_array('traffic_checkpoint_cursor_attention', + array_column($attention['blocked'], 'code'), true), + 'Attention cursor did not retain its hourly checkpoint evidence.'); + +echo "Traffic checkpoint retention contracts passed.\n"; diff --git a/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php b/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php index 4f95e122..cba1be47 100644 --- a/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php +++ b/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php @@ -18,15 +18,18 @@ $settle = strpos($lifecycle, 'CloudTrafficPoolAccounting::settlePendingUsage('); $due = strpos($lifecycle, 'CloudTrafficPoolAccounting::reconcileDue('); $compact = strpos($lifecycle, 'CloudTrafficSettlementRetention::compact('); +$checkpointCompact = strpos( + $lifecycle, 'CloudTrafficCheckpointRetention::prune(' +); $runtime = strpos($lifecycle, '(new CloudInstanceRuntimeSyncService())->sync($batchSize)'); $instanceReconcile = strpos($lifecycle, "\$this->heartbeat?->busy('instance_reconcile')"); $assert($sync !== false && $settle !== false && $due !== false - && $compact !== false + && $compact !== false && $checkpointCompact !== false && $runtime !== false && $instanceReconcile !== false && $sync < $settle && $settle < $due && $due < $compact - && $compact < $runtime + && $compact < $checkpointCompact && $checkpointCompact < $runtime && $runtime < $instanceReconcile, 'Lifecycle must sync counters, settle usage, reconcile due periods, ' . 'compact verified history, then continue with runtime and '