From 44d1a6344a91ffa5dfc51e3ad1db3d3c2f0dc684 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 16 Nov 2026 23:02:07 +0800 Subject: [PATCH] refactor(traffic): prune verified settlement buckets --- docs/DEPLOYMENT.md | 2 +- docs/SERVICE_COMPENSATION.md | 2 +- web/app/Command/CloudSetup.php | 7 +- .../Services/Cloud/CloudLifecycleService.php | 16 + .../Services/Cloud/CloudRuntimeHeartbeat.php | 1 + .../Cloud/CloudTrafficSettlementRetention.php | 307 ++++++++++++++++++ web/sql/cloud.sql | 1 + ...CloudAbuseMonitoringSchemaContractTest.php | 2 +- .../CloudAbusePolicySchemaContractTest.php | 2 +- ...CloudAbuseProjectionLedgerContractTest.php | 2 +- ...blicationPreparationSchemaContractTest.php | 2 +- web/tests/CloudFreshSchemaContractTest.php | 6 +- ...oudMaintenanceNoticeSchemaContractTest.php | 2 +- ...licIpPoolReplacementSchemaContractTest.php | 2 +- ...licNetworkTransitionSchemaContractTest.php | 2 +- .../CloudRescueCatalogSchemaContractTest.php | 2 +- ...loudRestoreMigrationLedgerContractTest.php | 2 +- web/tests/CloudRuntimeHeartbeatTest.php | 3 +- ...dServiceCompensationSchemaContractTest.php | 2 +- ...udStoragePublicationSchemaContractTest.php | 2 +- .../CloudTemplateImportIntentContractTest.php | 2 +- web/tests/CloudTrafficPoolAccountingTest.php | 67 ++-- ...fficPoolLifecycleSchedulerContractTest.php | 10 +- .../CloudTrafficPoolSchemaContractTest.php | 4 +- web/tests/CloudVpcSchemaContractTest.php | 2 +- web/tests/UiCopyCatalogSchemaContractTest.php | 2 +- 26 files changed, 409 insertions(+), 45 deletions(-) create mode 100644 web/app/Services/Cloud/CloudTrafficSettlementRetention.php diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 56fb2314..999ee3be 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -160,7 +160,7 @@ libvirt 的持久 pool 定义就是 Agent 后续使用的映射,不另写存 公网网络接入在宿主机的“网络接入”中按资源池线路独立配置,可使用 `bridge:br0`、其他 Linux 网桥或 `network:default` 这样的 libvirt network。名称以字母或数字开头,后续只能包含字母、数字、点、下划线和短横线,bridge 名称为 1~15 字符,libvirt network 名称为 1~64 字符。宿主机上的公网网桥或 libvirt network 必须由运维预先准备。Agent 只发现、验证和使用现有公网网络,不创建公网网桥、不启动 libvirt network,也不修改公网地址、上游网关或挂载。`cloud_hosts.default_network` 仅保留为兼容展示值,不参与 Agent 就绪、调度、恢复、迁移或换 IP 决策;真正的运行时权威是资源池线路、当前 Agent 代次已验证的网络接入,以及绑定该接入的公网地址池。VPC 使用下述独立的 Agent 受管 bridge 和 L3 路由,不改变这一公网边界。 -当前完整 schema 版本为 `go-agent-wss-v53-traffic-settlement-receipts`。v48 将滥用监测拆分为 72 小时原始证据、短期终态投影、7 天去重凭据以及 5 分钟/小时趋势汇总;v49 为实例性能图表增加 5 分钟和小时汇总,并将一分钟原始点限制为 24 小时;v50 保持分钟级 FEFO 扣减和游标更新不变,将同一小时、实例和额度的用量累积到持久结算桶,小时结束、额度耗尽、到期、债务结算或异常栅栏时再生成不可变账本事件。迟到采样使用新的桶修订,绝不改写已封存事件;v51 将性能历史改为逻辑实例主键,删除每行重复的宿主机 hash 和文本 UUID,将永久流量总数/检查点的 UUID 与 hash 改为二进制并删除未被读取路径使用的宽索引;v52 保持实时 FEFO 扣减不变,将新用量累积到 UTC 每日结算窗口,并通过 `bucket_seconds` 与 `seal_at` 继续识别和封存升级前的小时窗口;v53 增加紧凑结算凭据,冻结已经安全压缩的窗口身份、最大修订、账本事件和载荷哈希,让迟到采样无需依赖完整旧桶也能从下一修订继续。部署既有数据库时必须先停止生命周期与滥用监测 worker,按当前 `cloud.sql`、`cloud_log.sql` 的新增表和字段制作一次性迁移并完成回填,再启动新代码;v51 涉及日志表主键与二进制身份重建,不能在采集 worker 运行时原地改列,也不能让 v50 代码与 v51 日志表混跑;v52 必须先为既有结算桶回填 `bucket_seconds = 3600` 与 `seal_at = bucket_start + 3600`,再替换唯一索引、到期索引和检查约束;v53 必须先创建 `cloud_traffic_settlement_receipts`,本阶段不删除既有完整桶。不得让缺少汇总表、结算桶窗口字段、紧凑凭据表或 `instance_id` 的旧数据库直接进入采集或流量结算。v47 为 `cloud_offers` 增加季度、年度及对应自动备份价格;既有方案升级时必须在恢复销售前显式回填 90/365 天价格,不能让数据库默认零价进入购买目录。从 v44 升级时,必须先停止滥用观测与投影 worker,为既有 finding 回填 `occurrence_generation = 1` 与 `transition_revision = 1`,再创建 `cloud_abuse_alert_events` 和 `cloud_abuse_alert_event_items`;从 v45 升级还必须停止通知 worker,创建 `cloud_abuse_alert_deliveries`、`administrator_telegram_delivery_gate` 并写入唯一 gate 行。历史 finding 不反向合成事件;事件只从升级后主库事务内真实发生的 `opened`、`escalated` 和 `evidence_clear` 解决转移产生。完成列、约束、索引、外键和 gate 核对后,先恢复滥用观测,再恢复通知 worker。 +当前完整 schema 版本为 `go-agent-wss-v54-traffic-settlement-compaction`。v48 将滥用监测拆分为 72 小时原始证据、短期终态投影、7 天去重凭据以及 5 分钟/小时趋势汇总;v49 为实例性能图表增加 5 分钟和小时汇总,并将一分钟原始点限制为 24 小时;v50 保持分钟级 FEFO 扣减和游标更新不变,将同一小时、实例和额度的用量累积到持久结算桶,小时结束、额度耗尽、到期、债务结算或异常栅栏时再生成不可变账本事件。迟到采样使用新的桶修订,绝不改写已封存事件;v51 将性能历史改为逻辑实例主键,删除每行重复的宿主机 hash 和文本 UUID,将永久流量总数/检查点的 UUID 与 hash 改为二进制并删除未被读取路径使用的宽索引;v52 保持实时 FEFO 扣减不变,将新用量累积到 UTC 每日结算窗口,并通过 `bucket_seconds` 与 `seal_at` 继续识别和封存升级前的小时窗口;v53 增加紧凑结算凭据,冻结已经安全压缩的窗口身份、最大修订、账本事件和载荷哈希,让迟到采样无需依赖完整旧桶也能从下一修订继续;v54 启用7天安全窗后的完整桶压缩,只有账本身份、金额、载荷和哈希全部吻合时,才在同一主库事务中更新凭据并删除完整桶。部署既有数据库时必须先停止生命周期与滥用监测 worker,按当前 `cloud.sql`、`cloud_log.sql` 的新增表和字段制作一次性迁移并完成回填,再启动新代码;v51 涉及日志表主键与二进制身份重建,不能在采集 worker 运行时原地改列,也不能让 v50 代码与 v51 日志表混跑;v52 必须先为既有结算桶回填 `bucket_seconds = 3600` 与 `seal_at = bucket_start + 3600`,再替换唯一索引、到期索引和检查约束;v53 必须先创建 `cloud_traffic_settlement_receipts`;v54 必须增加 `cloud_traffic_settlement_retention` 索引后才能启动清理,验证失败的桶保持原样且不得人工跳过。不得让缺少汇总表、结算桶窗口字段、紧凑凭据表或 `instance_id` 的旧数据库直接进入采集或流量结算。v47 为 `cloud_offers` 增加季度、年度及对应自动备份价格;既有方案升级时必须在恢复销售前显式回填 90/365 天价格,不能让数据库默认零价进入购买目录。从 v44 升级时,必须先停止滥用观测与投影 worker,为既有 finding 回填 `occurrence_generation = 1` 与 `transition_revision = 1`,再创建 `cloud_abuse_alert_events` 和 `cloud_abuse_alert_event_items`;从 v45 升级还必须停止通知 worker,创建 `cloud_abuse_alert_deliveries`、`administrator_telegram_delivery_gate` 并写入唯一 gate 行。历史 finding 不反向合成事件;事件只从升级后主库事务内真实发生的 `opened`、`escalated` 和 `evidence_clear` 解决转移产生。完成列、约束、索引、外键和 gate 核对后,先恢复滥用观测,再恢复通知 worker。 事件 header 与 projection receipt 在同一个主库事务中写入,且事件先于 receipt;同一实例同一采样桶的多规则、双协议族转移合并为一个 header 和多个 item。`continued` 不产生事件,`policy_replaced` 与 `owner_changed` 只关闭 finding,不能伪造“恢复”事件。item 已冻结当时的聚合 evidence、规则身份和 finding 代次,后续投递不得回读会变化的 finding。v46 为每个事件建立至多一条 Telegram 投递决策;远端调用开始后的中断或回执不确定统一进入 `unknown`,禁止自动重放。删除用户时按事件冻结的 `user_id` 显式删除 header,item 与投递账本按当前外键和账户清理规则收敛,避免实例转交后遗留原租户数据。 diff --git a/docs/SERVICE_COMPENSATION.md b/docs/SERVICE_COMPENSATION.md index 412268f4..65b6384a 100644 --- a/docs/SERVICE_COMPENSATION.md +++ b/docs/SERVICE_COMPENSATION.md @@ -47,7 +47,7 @@ ## 部署 -全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v53-traffic-settlement-receipts` 完整 schema;其中补偿模块包括: +全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v54-traffic-settlement-compaction` 完整 schema;其中补偿模块包括: - `cloud_service_compensations`; - `cloud_service_compensation_items`; diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index 557fa159..4176db1e 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'; + private const SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'; /** Tables installed by ss.sql before cloudInit and owned by this schema. */ private const PREINSTALLED_MAIN_TABLES = [ 'ui_copy_locales', 'ui_copy_entries', 'ui_copy_drafts', @@ -1201,6 +1201,7 @@ final class CloudSetup 'cloud_traffic_usage_settlement_buckets' => [ 'PRIMARY', 'cloud_traffic_settlement_identity', 'cloud_traffic_settlement_due', + 'cloud_traffic_settlement_retention', 'cloud_traffic_settlement_entitlement', 'cloud_traffic_settlement_owner', 'cloud_traffic_settlement_event', @@ -1653,6 +1654,10 @@ final class CloudSetup 'non_unique' => 1, 'columns' => ['state', 'seal_at', 'id'], ], + 'cloud_traffic_settlement_retention' => [ + 'non_unique' => 1, + 'columns' => ['state', 'updated_at', 'id'], + ], ], 'cloud_traffic_settlement_receipts' => [ 'cloud_traffic_settlement_receipt_identity' => [ diff --git a/web/app/Services/Cloud/CloudLifecycleService.php b/web/app/Services/Cloud/CloudLifecycleService.php index 0777dc7d..7f38e748 100644 --- a/web/app/Services/Cloud/CloudLifecycleService.php +++ b/web/app/Services/Cloud/CloudLifecycleService.php @@ -237,6 +237,22 @@ final class CloudLifecycleService error_log('cloud traffic-pool accounting unavailable: ' . get_class($error)); } + $this->heartbeat?->busy('traffic_settlement_compaction'); + try { + $compaction = CloudTrafficSettlementRetention::compact( + $batchSize, + time() + ); + if ($compaction['blocked'] !== []) { + $this->observeFailure('traffic_retention_failed'); + } + } catch (\Throwable $error) { + $this->observeFailure('traffic_retention_failed'); + // Retention is never allowed to block current accounting or + // instance policy. Full buckets remain intact for a later retry. + error_log('cloud traffic settlement 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/CloudRuntimeHeartbeat.php b/web/app/Services/Cloud/CloudRuntimeHeartbeat.php index bf800f58..d0d8ca67 100644 --- a/web/app/Services/Cloud/CloudRuntimeHeartbeat.php +++ b/web/app/Services/Cloud/CloudRuntimeHeartbeat.php @@ -34,6 +34,7 @@ final class CloudRuntimeHeartbeat 'abuse_monitor_projection' => '网络风险投影', 'abuse_monitor_retention' => '网络观测保留清理', 'traffic_sync' => '流量同步', + 'traffic_settlement_compaction' => '流量结算压缩', 'runtime_status_sync' => '实例状态同步', 'instance_reconcile' => '实例策略核对', 'idle' => '等待下一轮', 'stopped' => '已退出']; diff --git a/web/app/Services/Cloud/CloudTrafficSettlementRetention.php b/web/app/Services/Cloud/CloudTrafficSettlementRetention.php new file mode 100644 index 00000000..00ac627c --- /dev/null +++ b/web/app/Services/Cloud/CloudTrafficSettlementRetention.php @@ -0,0 +1,307 @@ + + * } + */ + public static function compact( + int $limit = 200, + ?int $now = null + ): array { + $now ??= time(); + if ($now < self::RETENTION_SECONDS) { + throw new \InvalidArgumentException( + 'traffic_settlement_retention_clock_invalid' + ); + } + $limit = max(1, min(self::MAX_BATCH, $limit)); + $cutoff = $now - self::RETENTION_SECONDS; + $ids = CloudTrafficUsageSettlementBucket::where('state', 'sealed') + ->where('updated_at', '<=', $cutoff) + ->orderBy('updated_at')->orderBy('id')->limit($limit) + ->pluck('id')->map(static fn ($id): int => (int) $id)->all(); + $compacted = 0; + $skipped = 0; + $blocked = []; + foreach ($ids as $id) { + try { + if (self::compactOne($id, $cutoff, $now)) { + $compacted++; + } else { + $skipped++; + } + } catch (\Throwable $error) { + $code = str_starts_with($error->getMessage(), 'traffic_') + ? $error->getMessage() + : 'traffic_settlement_compaction_failed'; + $blocked[] = ['bucket_id' => $id, 'code' => $code]; + error_log('cloud traffic settlement compaction blocked: ' + . $id . ':' . $code); + } + } + return [ + 'scanned' => count($ids), + 'compacted' => $compacted, + 'skipped' => $skipped, + 'blocked' => $blocked, + ]; + } + + private static function compactOne( + int $bucketId, + int $cutoff, + int $now + ): bool { + $hint = CloudTrafficUsageSettlementBucket::find($bucketId); + if ($hint === null) { + return false; + } + $connection = $hint->getConnection(); + return $connection->transaction(static function () use ( + $bucketId, + $cutoff, + $now + ): bool { + $poolId = (int) (CloudTrafficUsageSettlementBucket::where( + 'id', $bucketId + )->value('pool_id') ?? 0); + if ($poolId < 1) { + return false; + } + $pool = CloudTrafficPool::where('id', $poolId) + ->lockForUpdate()->first(); + if ($pool === null) { + throw new \RuntimeException( + 'traffic_settlement_compaction_pool_missing' + ); + } + $bucket = CloudTrafficUsageSettlementBucket::where( + 'id', $bucketId + )->lockForUpdate()->first(); + if ($bucket === null || (string) $bucket->state !== 'sealed' + || (int) $bucket->updated_at > $cutoff) { + return false; + } + $eventId = (int) ($bucket->sealed_event_id ?? 0); + $event = $eventId > 0 + ? CloudTrafficLedgerEvent::where('id', $eventId) + ->lockForUpdate()->first() + : null; + if ($event === null) { + throw new \RuntimeException( + 'traffic_settlement_compaction_event_missing' + ); + } + self::assertEventMatches($pool, $bucket, $event); + $receiptQuery = CloudTrafficSettlementReceipt::where( + 'pool_id', (int) $bucket->pool_id + )->where('instance_id', (int) $bucket->instance_id) + ->where('service_period_id', (int) $bucket->service_period_id) + ->where('allocation_kind', (string) $bucket->allocation_kind) + ->where('allocation_target_id', + (int) $bucket->allocation_target_id) + ->where('bucket_start', (int) $bucket->bucket_start) + ->where('bucket_seconds', (int) $bucket->bucket_seconds); + $receipt = (clone $receiptQuery)->lockForUpdate()->first(); + if ($receipt === null) { + $receipt = new CloudTrafficSettlementReceipt(); + $receipt->pool_id = (int) $bucket->pool_id; + $receipt->user_id = (int) $bucket->user_id; + $receipt->instance_id = (int) $bucket->instance_id; + $receipt->service_period_id = (int) $bucket->service_period_id; + $receipt->entitlement_id = $bucket->entitlement_id === null + ? null : (int) $bucket->entitlement_id; + $receipt->allocation_kind = (string) $bucket->allocation_kind; + $receipt->allocation_target_id = + (int) $bucket->allocation_target_id; + $receipt->bucket_start = (int) $bucket->bucket_start; + $receipt->bucket_seconds = (int) $bucket->bucket_seconds; + $receipt->max_revision = 0; + $receipt->last_event_id = 0; + $receipt->compacted_amount_bytes = 0; + $receipt->compacted_event_count = 0; + $receipt->last_payload_hash = str_repeat('0', 64); + $receipt->compacted_at = $now; + $receipt->updated_at = $now; + } + self::applyReceipt($receipt, $bucket, $event, $now); + $receipt->save(); + $deleted = CloudTrafficUsageSettlementBucket::where( + 'id', $bucketId + )->where('state', 'sealed') + ->where('sealed_event_id', (int) $event->id)->delete(); + if ($deleted !== 1) { + throw new \RuntimeException( + 'traffic_settlement_compaction_delete_conflict' + ); + } + return true; + }, 3); + } + + private static function applyReceipt( + CloudTrafficSettlementReceipt $receipt, + CloudTrafficUsageSettlementBucket $bucket, + CloudTrafficLedgerEvent $event, + int $now + ): void { + foreach ([ + 'user_id', 'instance_id', 'service_period_id', + 'allocation_target_id', 'bucket_start', 'bucket_seconds', + ] as $field) { + if ((int) $receipt->{$field} !== (int) $bucket->{$field}) { + throw new \RuntimeException( + 'traffic_settlement_compaction_receipt_conflict' + ); + } + } + if ((string) $receipt->allocation_kind + !== (string) $bucket->allocation_kind + || (int) ($receipt->entitlement_id ?? 0) + !== (int) ($bucket->entitlement_id ?? 0)) { + throw new \RuntimeException( + 'traffic_settlement_compaction_receipt_conflict' + ); + } + $revision = (int) $bucket->bucket_revision; + $knownRevision = (int) $receipt->max_revision; + if ($revision < $knownRevision + || ($revision === $knownRevision + && ((int) $receipt->last_event_id !== (int) $event->id + || !hash_equals( + (string) $receipt->last_payload_hash, + (string) $event->payload_hash + )))) { + throw new \RuntimeException( + 'traffic_settlement_compaction_receipt_conflict' + ); + } + if ($revision > $knownRevision) { + $amount = (int) $bucket->amount_bytes; + if ($amount > PHP_INT_MAX + - (int) $receipt->compacted_amount_bytes + || (int) $receipt->compacted_event_count === PHP_INT_MAX) { + throw new \OverflowException( + 'traffic_settlement_compaction_receipt_overflow' + ); + } + $receipt->max_revision = $revision; + $receipt->last_event_id = (int) $event->id; + $receipt->compacted_amount_bytes = + (int) $receipt->compacted_amount_bytes + $amount; + $receipt->compacted_event_count = + (int) $receipt->compacted_event_count + 1; + $receipt->last_payload_hash = (string) $event->payload_hash; + } + $receipt->compacted_at = $now; + $receipt->updated_at = $now; + } + + private static function assertEventMatches( + CloudTrafficPool $pool, + CloudTrafficUsageSettlementBucket $bucket, + CloudTrafficLedgerEvent $event + ): void { + $kind = (string) $bucket->allocation_kind; + $eventType = $kind === 'entitlement' + ? 'usage_allocated' : 'overage_recorded'; + if ((int) $bucket->pool_id !== (int) $pool->id + || (int) $bucket->user_id !== (int) $pool->user_id + || (int) $event->pool_id !== (int) $bucket->pool_id + || (int) $event->user_id !== (int) $bucket->user_id + || (string) $event->event_type !== $eventType + || (string) $event->source_type !== 'traffic_settlement' + || (string) $event->source_id !== (string) $bucket->id + || (int) $event->source_revision !== 1 + || (int) ($event->instance_id ?? 0) + !== (int) $bucket->instance_id + || (int) ($event->service_period_id ?? 0) + !== (int) $bucket->service_period_id + || (int) ($event->entitlement_id ?? 0) + !== (int) ($bucket->entitlement_id ?? 0) + || (int) $event->amount_bytes !== (int) $bucket->amount_bytes + || (int) $event->effective_at !== (int) $bucket->bucket_start + || (int) ($event->observed_at ?? 0) + !== (int) $bucket->last_observed_at) { + throw new \RuntimeException( + 'traffic_settlement_compaction_event_identity_mismatch' + ); + } + $payload = [ + 'bucket_start' => (int) $bucket->bucket_start, + 'bucket_revision' => (int) $bucket->bucket_revision, + 'bucket_seconds' => (int) $bucket->bucket_seconds, + 'seal_at' => (int) $bucket->seal_at, + 'download_bytes' => (int) $bucket->download_bytes, + 'upload_bytes' => (int) $bucket->upload_bytes, + 'sample_count' => (int) $bucket->sample_count, + 'first_observed_at' => (int) $bucket->first_observed_at, + 'last_observed_at' => (int) $bucket->last_observed_at, + ]; + try { + $storedPayload = json_decode( + (string) $event->payload_json, + true, + 512, + JSON_THROW_ON_ERROR + ); + } catch (\JsonException) { + throw new \RuntimeException( + 'traffic_settlement_compaction_payload_invalid' + ); + } + if ($storedPayload !== $payload) { + throw new \RuntimeException( + 'traffic_settlement_compaction_payload_mismatch' + ); + } + $envelope = [ + 'pool_id' => (int) $pool->id, + 'event_type' => $eventType, + 'source_type' => 'traffic_settlement', + 'source_id' => (string) $bucket->id, + 'source_revision' => 1, + 'instance_id' => (int) $bucket->instance_id, + 'service_period_id' => (int) $bucket->service_period_id, + 'entitlement_id' => $bucket->entitlement_id === null + ? null : (int) $bucket->entitlement_id, + 'amount_bytes' => (int) $bucket->amount_bytes, + 'effective_at' => (int) $bucket->bucket_start, + 'observed_at' => (int) $bucket->last_observed_at, + 'payload' => $payload, + ]; + $expectedHash = hash('sha256', json_encode( + $envelope, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + )); + if (!hash_equals((string) $event->payload_hash, $expectedHash)) { + throw new \RuntimeException( + 'traffic_settlement_compaction_payload_hash_mismatch' + ); + } + } +} diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index ac8d3a09..d83ff558 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -2343,6 +2343,7 @@ CREATE TABLE cloud_traffic_usage_settlement_buckets ( bucket_revision ), KEY cloud_traffic_settlement_due (state, seal_at, id), + KEY cloud_traffic_settlement_retention (state, updated_at, id), KEY cloud_traffic_settlement_entitlement ( entitlement_id, state, bucket_start, id ), diff --git a/web/tests/CloudAbuseMonitoringSchemaContractTest.php b/web/tests/CloudAbuseMonitoringSchemaContractTest.php index d84e3db9..d8538415 100644 --- a/web/tests/CloudAbuseMonitoringSchemaContractTest.php +++ b/web/tests/CloudAbuseMonitoringSchemaContractTest.php @@ -415,7 +415,7 @@ $assert(str_contains( $assert(str_contains( $setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'" + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'" ), 'CloudSetup schema version was not advanced for abuse observation.'); foreach (array_keys($mainTables + $logTables) as $table) { diff --git a/web/tests/CloudAbusePolicySchemaContractTest.php b/web/tests/CloudAbusePolicySchemaContractTest.php index 8e858e26..bb8ec5c8 100644 --- a/web/tests/CloudAbusePolicySchemaContractTest.php +++ b/web/tests/CloudAbusePolicySchemaContractTest.php @@ -96,7 +96,7 @@ foreach ($defaults->rules() as $code => $rule) { 'The fresh schema rule seed drifted from PHP: ' . $code); } $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($service, "->where('active_slot', 1)->lockForUpdate()") && str_contains($service, "->where('active_slot', 1)->update") && str_contains($service, 'insertGetId'), diff --git a/web/tests/CloudAbuseProjectionLedgerContractTest.php b/web/tests/CloudAbuseProjectionLedgerContractTest.php index 7eb200ef..8504f1b7 100644 --- a/web/tests/CloudAbuseProjectionLedgerContractTest.php +++ b/web/tests/CloudAbuseProjectionLedgerContractTest.php @@ -260,7 +260,7 @@ $assert(str_contains($projection, '->snapshotByIdentity($revision, $hash)') && !str_contains($projection, '->activeSnapshot()'), 'Projection can drift from the outbox identity to the current policy.'); $assert(str_contains($deployment, - '`go-agent-wss-v53-traffic-settlement-receipts`') + '`go-agent-wss-v54-traffic-settlement-compaction`') && str_contains($deployment, '`occurrence_generation = 1` 与 `transition_revision = 1`') && str_contains($deployment, diff --git a/web/tests/CloudBackupPublicationPreparationSchemaContractTest.php b/web/tests/CloudBackupPublicationPreparationSchemaContractTest.php index e88701e8..e2d10b37 100644 --- a/web/tests/CloudBackupPublicationPreparationSchemaContractTest.php +++ b/web/tests/CloudBackupPublicationPreparationSchemaContractTest.php @@ -64,7 +64,7 @@ foreach ([ 'CloudSetup omits backup preparation contract: ' . $required); } $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($setup, "'columns' => [\n 'create_request_actor_id',\n 'create_request_idempotency_key',") && str_contains($setup, "'non_unique' => 0"), diff --git a/web/tests/CloudFreshSchemaContractTest.php b/web/tests/CloudFreshSchemaContractTest.php index 11e81cc9..595ce894 100644 --- a/web/tests/CloudFreshSchemaContractTest.php +++ b/web/tests/CloudFreshSchemaContractTest.php @@ -27,10 +27,10 @@ $assert(stripos($schema, 'compatibility import') === false $assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema), 'cloud.sql retained an engine-prefixed identifier.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && !str_contains($setup, "SCHEMA_VERSION = 'go-v1'") - && str_contains($deployment, '`go-agent-wss-v53-traffic-settlement-receipts`') - && str_contains($compensation, '`go-agent-wss-v53-traffic-settlement-receipts`'), + && str_contains($deployment, '`go-agent-wss-v54-traffic-settlement-compaction`') + && str_contains($compensation, '`go-agent-wss-v54-traffic-settlement-compaction`'), 'Outbound Agent schema must reject the incompatible earlier Go database.'); $assert(str_contains($schema, "timezone VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'UTC'") diff --git a/web/tests/CloudMaintenanceNoticeSchemaContractTest.php b/web/tests/CloudMaintenanceNoticeSchemaContractTest.php index 14c12df3..51f98245 100644 --- a/web/tests/CloudMaintenanceNoticeSchemaContractTest.php +++ b/web/tests/CloudMaintenanceNoticeSchemaContractTest.php @@ -56,7 +56,7 @@ foreach ([ } $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'"), + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'"), 'CloudSetup schema version was not advanced for maintenance notices.'); echo "Maintenance notice schema contracts passed.\n"; diff --git a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php index 7badf2cf..05dacc2e 100644 --- a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php +++ b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php @@ -53,7 +53,7 @@ $assert(is_string($schema) 'Public-pool replacement lacks durable batch, child, or claim schema.'); $assert(is_string($setup) && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($setup, "'cloud_public_ip_pool_replacement_batches'") && str_contains($setup, diff --git a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php index 33e54227..1eb739be 100644 --- a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php @@ -170,7 +170,7 @@ $assert(str_contains($setup, 'CloudSetup does not verify index uniqueness and ordered columns.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($setup, "'cloud_public_network_transitions'") && str_contains($setup, "'cloud_public_network_transition_ips'") && str_contains($setup, "'reservation_ip_claim_id'") diff --git a/web/tests/CloudRescueCatalogSchemaContractTest.php b/web/tests/CloudRescueCatalogSchemaContractTest.php index 586f83b8..746c66ef 100644 --- a/web/tests/CloudRescueCatalogSchemaContractTest.php +++ b/web/tests/CloudRescueCatalogSchemaContractTest.php @@ -57,7 +57,7 @@ $assert($replica !== '' && str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'), 'Rescue replica cannot prove exact identity or retain cleanup debt.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($setup, "'cloud_rescue_artifact_delete_due'") && str_contains($setup, "'cloud_rescue_replica_cleanup'"), 'CloudSetup version or rescue catalog indexes are incomplete.'); diff --git a/web/tests/CloudRestoreMigrationLedgerContractTest.php b/web/tests/CloudRestoreMigrationLedgerContractTest.php index 2bb7e1ae..5ce0fb11 100644 --- a/web/tests/CloudRestoreMigrationLedgerContractTest.php +++ b/web/tests/CloudRestoreMigrationLedgerContractTest.php @@ -218,7 +218,7 @@ foreach ([ 'CloudSetup omits restore/migration ledger contract: ' . $required); } $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($attemptModel, "protected \$table = 'cloud_backup_restore_attempts';") && str_contains($attemptModel, "'active_attempt' => 'int'") diff --git a/web/tests/CloudRuntimeHeartbeatTest.php b/web/tests/CloudRuntimeHeartbeatTest.php index c51d2e55..cd3c8427 100644 --- a/web/tests/CloudRuntimeHeartbeatTest.php +++ b/web/tests/CloudRuntimeHeartbeatTest.php @@ -633,7 +633,7 @@ try { $assert($lifecycle->tick() === 0 && $lifecycle->observationErrors() === ['provision_expiry_failed', 'invoice_generation_failed', 'traffic_sync_failed', - 'traffic_pool_accounting_failed'] + 'traffic_pool_accounting_failed', 'traffic_retention_failed'] && $checks($partialDirectory)['lifecycle']['status'] === 'warning' && $checks($partialDirectory)['lifecycle']['last_success_at'] === null, 'Lifecycle swallowed sub-stage failures and falsely reported normal operation: ' @@ -648,6 +648,7 @@ try { $assert($lifecycle->tick() === 0 && $lifecycle->observationErrors() === ['provision_expiry_failed', 'invoice_generation_failed', 'traffic_sync_failed', 'traffic_pool_accounting_failed', + 'traffic_retention_failed', 'instance_reconcile_failed'] && $checks($partialDirectory)['lifecycle']['status'] === 'warning', 'All internally caught lifecycle stages failed without an unhealthy observation: ' diff --git a/web/tests/CloudServiceCompensationSchemaContractTest.php b/web/tests/CloudServiceCompensationSchemaContractTest.php index 77fafde3..eee21389 100644 --- a/web/tests/CloudServiceCompensationSchemaContractTest.php +++ b/web/tests/CloudServiceCompensationSchemaContractTest.php @@ -105,7 +105,7 @@ $assert(str_contains($setup, 'CloudSetup lost the open-compensation fence index contract.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'"), + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'"), 'CloudSetup schema version was not advanced for service compensation.'); $appliedShape = preg_match( diff --git a/web/tests/CloudStoragePublicationSchemaContractTest.php b/web/tests/CloudStoragePublicationSchemaContractTest.php index 747fc8c3..f6202c50 100644 --- a/web/tests/CloudStoragePublicationSchemaContractTest.php +++ b/web/tests/CloudStoragePublicationSchemaContractTest.php @@ -138,7 +138,7 @@ $assert(is_string($publicationModel) && str_contains($artifactModel, "'maximum_size_bytes' => 'int'"), 'Storage publication/artifact model contracts are incomplete.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'"), + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'"), 'CloudSetup schema version was not advanced for durable publications.'); echo "Storage publication schema contracts passed.\n"; diff --git a/web/tests/CloudTemplateImportIntentContractTest.php b/web/tests/CloudTemplateImportIntentContractTest.php index 8b79ed72..33091d48 100644 --- a/web/tests/CloudTemplateImportIntentContractTest.php +++ b/web/tests/CloudTemplateImportIntentContractTest.php @@ -63,7 +63,7 @@ $assert(str_contains($schema, && str_contains($schema, 'CONSTRAINT chk_cloud_template_import_completion CHECK (') && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'"), + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'"), 'Template imports are missing durable identity or terminal-state constraints.'); $assert(str_contains($routes, "'/admin/cloud-template-imports'") && str_contains($routes, "'/admin/cloud-template-imports/{id}'") diff --git a/web/tests/CloudTrafficPoolAccountingTest.php b/web/tests/CloudTrafficPoolAccountingTest.php index 39e52cfc..506fae1f 100644 --- a/web/tests/CloudTrafficPoolAccountingTest.php +++ b/web/tests/CloudTrafficPoolAccountingTest.php @@ -9,6 +9,7 @@ use App\Models\CloudTrafficInstanceCursor; use App\Models\CloudTrafficLedgerEvent; use App\Models\CloudTrafficPool; use App\Services\Cloud\CloudTrafficPoolAccounting; +use App\Services\Cloud\CloudTrafficSettlementRetention; use App\Services\Cloud\CloudError; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -824,26 +825,29 @@ $sealedEvent = $sealedBucket === null ? null : CloudTrafficLedgerEvent::find((int) $sealedBucket->sealed_event_id); $assert($sealedBucket !== null && $sealedEvent !== null, 'Sealed settlement fixture is incomplete.'); -Capsule::table('cloud_traffic_settlement_receipts')->insert([ - 'pool_id' => (int) $sealedBucket->pool_id, - 'user_id' => (int) $sealedBucket->user_id, - 'instance_id' => (int) $sealedBucket->instance_id, - 'service_period_id' => (int) $sealedBucket->service_period_id, - 'entitlement_id' => (int) $sealedBucket->entitlement_id, - 'allocation_kind' => (string) $sealedBucket->allocation_kind, - 'allocation_target_id' => (int) $sealedBucket->allocation_target_id, - 'bucket_start' => (int) $sealedBucket->bucket_start, - 'bucket_seconds' => (int) $sealedBucket->bucket_seconds, - 'max_revision' => (int) $sealedBucket->bucket_revision, - 'last_event_id' => (int) $sealedEvent->id, - 'compacted_amount_bytes' => (int) $sealedBucket->amount_bytes, - 'compacted_event_count' => 1, - 'last_payload_hash' => (string) $sealedEvent->payload_hash, - 'compacted_at' => $settlementDay + 86_400, - 'updated_at' => $settlementDay + 86_400, -]); -Capsule::table('cloud_traffic_usage_settlement_buckets') - ->where('id', (int) $sealedBucket->id)->delete(); +$compaction = CloudTrafficSettlementRetention::compact( + 200, + (int) $sealedBucket->updated_at + + CloudTrafficSettlementRetention::RETENTION_SECONDS + 1 +); +$receipt = Capsule::table('cloud_traffic_settlement_receipts') + ->where('instance_id', 72)->first(); +$repeatCompaction = CloudTrafficSettlementRetention::compact( + 200, + (int) $sealedBucket->updated_at + + CloudTrafficSettlementRetention::RETENTION_SECONDS + 1 +); +$assert($compaction['compacted'] >= 1 + && $compaction['compacted'] === $compaction['scanned'] + && $compaction['blocked'] === [] + && $receipt !== null + && (int) $receipt->max_revision === 1 + && (int) $receipt->last_event_id === (int) $sealedEvent->id + && $repeatCompaction['scanned'] === 0 + && !Capsule::table('cloud_traffic_usage_settlement_buckets') + ->where('id', (int) $sealedBucket->id)->exists(), + 'Verified sealed settlement was not compacted atomically: ' + . json_encode($compaction, JSON_THROW_ON_ERROR)); $bucketedInstance->lifetime_download_bytes = 30; $bucketedInstance->lifetime_upload_bytes = 10; $bucketedInstance->traffic_synced_at = $settlementDay + 7_230; @@ -858,6 +862,29 @@ $assert($lateBucket !== null (int) $bucketedPool->id )['valid'] === true, 'A late observation could not create a new immutable bucket revision.'); +$assert(CloudTrafficPoolAccounting::sealDueUsageBuckets( + 200, $settlementDay + 86_400 + ) === 1, + 'Late settlement revision did not become sealable.'); +$lateSealedBucket = Capsule::table('cloud_traffic_usage_settlement_buckets') + ->where('instance_id', 72)->where('bucket_revision', 2)->first(); +$lateSealedEvent = $lateSealedBucket === null ? null + : CloudTrafficLedgerEvent::find((int) $lateSealedBucket->sealed_event_id); +$assert($lateSealedBucket !== null && $lateSealedEvent !== null, + 'Late sealed settlement fixture is incomplete.'); +$lateSealedEvent->amount_bytes = (int) $lateSealedEvent->amount_bytes + 1; +$lateSealedEvent->save(); +$blockedCompaction = CloudTrafficSettlementRetention::compact( + 200, + (int) $lateSealedBucket->updated_at + + CloudTrafficSettlementRetention::RETENTION_SECONDS + 1 +); +$assert(count($blockedCompaction['blocked']) === 1 + && Capsule::table('cloud_traffic_usage_settlement_buckets') + ->where('id', (int) $lateSealedBucket->id)->exists(), + 'Mismatched immutable evidence was deleted during compaction.'); +$lateSealedEvent->amount_bytes = (int) $lateSealedEvent->amount_bytes - 1; +$lateSealedEvent->save(); $scanInstanceA = $newInstance(57, 15); $scanPeriodA = $newPeriod( diff --git a/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php b/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php index 60c2c741..4f95e122 100644 --- a/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php +++ b/web/tests/CloudTrafficPoolLifecycleSchedulerContractTest.php @@ -17,16 +17,20 @@ $sync = strpos($lifecycle, 'CloudTrafficService::sync($batchSize)'); $settle = strpos($lifecycle, 'CloudTrafficPoolAccounting::settlePendingUsage('); $due = strpos($lifecycle, 'CloudTrafficPoolAccounting::reconcileDue('); +$compact = strpos($lifecycle, 'CloudTrafficSettlementRetention::compact('); $runtime = strpos($lifecycle, '(new CloudInstanceRuntimeSyncService())->sync($batchSize)'); $instanceReconcile = strpos($lifecycle, "\$this->heartbeat?->busy('instance_reconcile')"); $assert($sync !== false && $settle !== false && $due !== false + && $compact !== false && $runtime !== false && $instanceReconcile !== false - && $sync < $settle && $settle < $due && $due < $runtime + && $sync < $settle && $settle < $due && $due < $compact + && $compact < $runtime && $runtime < $instanceReconcile, - 'Lifecycle must sync counters, settle usage, reconcile due periods, then ' - . 'continue with runtime and per-instance reconciliation.'); + 'Lifecycle must sync counters, settle usage, reconcile due periods, ' + . 'compact verified history, then continue with runtime and ' + . 'per-instance reconciliation.'); $assert(str_contains($lifecycle, 'trafficUsageScanCursor') && str_contains($lifecycle, 'trafficPeriodScanCursor') && substr_count($lifecycle, "['next_cursor']") >= 2, diff --git a/web/tests/CloudTrafficPoolSchemaContractTest.php b/web/tests/CloudTrafficPoolSchemaContractTest.php index f89982a6..30034ba6 100644 --- a/web/tests/CloudTrafficPoolSchemaContractTest.php +++ b/web/tests/CloudTrafficPoolSchemaContractTest.php @@ -52,6 +52,8 @@ $assert(str_contains($schema, 'allocation_kind, allocation_target_id, bucket_start, bucket_seconds,') && str_contains($schema, 'KEY cloud_traffic_settlement_due (state, seal_at, id)') + && str_contains($schema, + 'KEY cloud_traffic_settlement_retention (state, updated_at, id)') && str_contains($schema, 'UNIQUE KEY cloud_traffic_settlement_receipt_identity (') && str_contains($schema, @@ -81,7 +83,7 @@ $assert(str_contains($schema, 'Service-period traffic-pool identity is not frozen or indexed.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($setup, "'chk_cloud_traffic_entitlement_balance'") && str_contains($setup, "'cloud_traffic_ledger_sequence'") && str_contains($setup, "'chk_cloud_traffic_settlement_state'") diff --git a/web/tests/CloudVpcSchemaContractTest.php b/web/tests/CloudVpcSchemaContractTest.php index f28a7658..d1fe2a0d 100644 --- a/web/tests/CloudVpcSchemaContractTest.php +++ b/web/tests/CloudVpcSchemaContractTest.php @@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL') 'Cloud jobs cannot be correlated to VPC or VPC-port work.'); $assert(str_contains($setup, - "private const SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "private const SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($setup, "'name' => 'cloud_vpc_enabled'") && str_contains($setup, "'value' => 'false'") && str_contains($setup, diff --git a/web/tests/UiCopyCatalogSchemaContractTest.php b/web/tests/UiCopyCatalogSchemaContractTest.php index d2b77c10..fa923445 100644 --- a/web/tests/UiCopyCatalogSchemaContractTest.php +++ b/web/tests/UiCopyCatalogSchemaContractTest.php @@ -104,7 +104,7 @@ foreach ($models as $class => $modelTable) { } $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v53-traffic-settlement-receipts'") + "SCHEMA_VERSION = 'go-agent-wss-v54-traffic-settlement-compaction'") && str_contains($setup, "self::schema('ss.sql') . \"\\0\" . self::schema('cloud.sql')") && str_contains($setup,