From 5f0630840796754635d3849b1d34ca2868800310 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 16 Nov 2026 22:52:20 +0800 Subject: [PATCH] refactor(traffic): settle usage in daily UTC windows --- docs/DEPLOYMENT.md | 2 +- docs/SERVICE_COMPENSATION.md | 2 +- docs/TRAFFIC_POOL.md | 9 ++-- docs/TRAFFIC_POOL_ROLLOUT.md | 2 +- web/app/Command/CloudSetup.php | 9 ++-- .../CloudTrafficUsageSettlementBucket.php | 2 + .../Cloud/CloudTrafficPoolAccounting.php | 46 +++++++++++-------- web/sql/cloud.sql | 19 +++++--- ...CloudAbuseMonitoringSchemaContractTest.php | 2 +- .../CloudAbusePolicySchemaContractTest.php | 2 +- ...CloudAbuseProjectionLedgerContractTest.php | 2 +- .../CloudAdminTrafficPoolServiceTest.php | 5 +- ...blicationPreparationSchemaContractTest.php | 2 +- web/tests/CloudFreshSchemaContractTest.php | 6 +-- ...oudMaintenanceNoticeSchemaContractTest.php | 2 +- ...licIpPoolReplacementSchemaContractTest.php | 2 +- ...licNetworkTransitionSchemaContractTest.php | 2 +- .../CloudRescueCatalogSchemaContractTest.php | 2 +- ...loudRestoreMigrationLedgerContractTest.php | 2 +- ...dServiceCompensationSchemaContractTest.php | 2 +- ...udStoragePublicationSchemaContractTest.php | 2 +- .../CloudTemplateImportIntentContractTest.php | 2 +- web/tests/CloudTrafficPoolAccountingTest.php | 30 ++++++++---- ...oudTrafficPoolAttentionIntegrationTest.php | 5 +- .../CloudTrafficPoolSchemaContractTest.php | 6 ++- web/tests/CloudVpcSchemaContractTest.php | 2 +- web/tests/UiCopyCatalogSchemaContractTest.php | 2 +- 27 files changed, 104 insertions(+), 67 deletions(-) diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index e53efb48..9d33702b 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-v51-compact-telemetry-storage`。v48 将滥用监测拆分为 72 小时原始证据、短期终态投影、7 天去重凭据以及 5 分钟/小时趋势汇总;v49 为实例性能图表增加 5 分钟和小时汇总,并将一分钟原始点限制为 24 小时;v50 保持分钟级 FEFO 扣减和游标更新不变,将同一小时、实例和额度的用量累积到持久结算桶,小时结束、额度耗尽、到期、债务结算或异常栅栏时再生成不可变账本事件。迟到采样使用新的桶修订,绝不改写已封存事件;v51 将性能历史改为逻辑实例主键,删除每行重复的宿主机 hash 和文本 UUID,将永久流量总数/检查点的 UUID 与 hash 改为二进制并删除未被读取路径使用的宽索引。部署既有数据库时必须先停止生命周期与滥用监测 worker,按当前 `cloud.sql`、`cloud_log.sql` 的新增表和字段制作一次性迁移并完成回填,再启动新代码;v51 涉及日志表主键与二进制身份重建,不能在采集 worker 运行时原地改列,也不能让 v50 代码与 v51 日志表混跑。不得让缺少汇总表、结算桶或 `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-v52-daily-traffic-settlement`。v48 将滥用监测拆分为 72 小时原始证据、短期终态投影、7 天去重凭据以及 5 分钟/小时趋势汇总;v49 为实例性能图表增加 5 分钟和小时汇总,并将一分钟原始点限制为 24 小时;v50 保持分钟级 FEFO 扣减和游标更新不变,将同一小时、实例和额度的用量累积到持久结算桶,小时结束、额度耗尽、到期、债务结算或异常栅栏时再生成不可变账本事件。迟到采样使用新的桶修订,绝不改写已封存事件;v51 将性能历史改为逻辑实例主键,删除每行重复的宿主机 hash 和文本 UUID,将永久流量总数/检查点的 UUID 与 hash 改为二进制并删除未被读取路径使用的宽索引;v52 保持实时 FEFO 扣减不变,将新用量累积到 UTC 每日结算窗口,并通过 `bucket_seconds` 与 `seal_at` 继续识别和封存升级前的小时窗口。部署既有数据库时必须先停止生命周期与滥用监测 worker,按当前 `cloud.sql`、`cloud_log.sql` 的新增表和字段制作一次性迁移并完成回填,再启动新代码;v51 涉及日志表主键与二进制身份重建,不能在采集 worker 运行时原地改列,也不能让 v50 代码与 v51 日志表混跑;v52 必须先为既有结算桶回填 `bucket_seconds = 3600` 与 `seal_at = bucket_start + 3600`,再替换唯一索引、到期索引和检查约束。不得让缺少汇总表、结算桶窗口字段或 `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 bc343a98..9792f782 100644 --- a/docs/SERVICE_COMPENSATION.md +++ b/docs/SERVICE_COMPENSATION.md @@ -47,7 +47,7 @@ ## 部署 -全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v51-compact-telemetry-storage` 完整 schema;其中补偿模块包括: +全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v52-daily-traffic-settlement` 完整 schema;其中补偿模块包括: - `cloud_service_compensations`; - `cloud_service_compensation_items`; diff --git a/docs/TRAFFIC_POOL.md b/docs/TRAFFIC_POOL.md index d057fbc9..d40397c2 100644 --- a/docs/TRAFFIC_POOL.md +++ b/docs/TRAFFIC_POOL.md @@ -65,10 +65,11 @@ pool -> instance cursor -> entitlements ``` The accounting transaction advances the instance cursor, updates entitlement -and pool projections, and accumulates the exact allocation in a durable hourly -settlement bucket atomically. A completed hour, entitlement exhaustion, -expiry, overage settlement or attention transition seals the bucket into one -immutable ledger event. Late observations start a new revision instead of +and pool projections, and accumulates the exact allocation in a durable UTC +daily settlement bucket atomically. A completed UTC day, entitlement +exhaustion, expiry, overage settlement or attention transition seals the +bucket into one immutable ledger event. Legacy hourly buckets remain sealable +during the clean upgrade. Late observations start a new revision instead of rewriting an already sealed event. This reduces permanent ledger growth while preserving minute-level FEFO allocation and exact RX/TX attribution. It never locks instances, writes network restrictions, or calls an Agent. A diff --git a/docs/TRAFFIC_POOL_ROLLOUT.md b/docs/TRAFFIC_POOL_ROLLOUT.md index a2e52125..ece0c8f4 100644 --- a/docs/TRAFFIC_POOL_ROLLOUT.md +++ b/docs/TRAFFIC_POOL_ROLLOUT.md @@ -131,7 +131,7 @@ Advance the group to `shadow`. The lifecycle process then performs, in order: 3. activation, expiry and closing of entitlements; 4. ordinary runtime and per-instance lifecycle reconciliation. -Shadow mode creates the real pool, entitlement, cursor, durable hourly +Shadow mode creates the real pool, entitlement, cursor, durable UTC daily settlement buckets and immutable sealed ledger records, but it does not add or remove the `traffic_pool_exhausted` network restriction. Open buckets are part of projection verification until sealed; they are not permission to replay a diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index a52e8f32..a993e97f 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-v51-compact-telemetry-storage'; + private const SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'; /** 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', @@ -580,7 +580,8 @@ final class CloudSetup 'cloud_traffic_usage_settlement_buckets' => [ 'id', 'pool_id', 'user_id', 'instance_id', 'service_period_id', 'entitlement_id', 'allocation_kind', 'allocation_target_id', - 'bucket_start', 'bucket_revision', 'amount_bytes', + 'bucket_start', 'bucket_seconds', 'seal_at', 'bucket_revision', + 'amount_bytes', 'download_bytes', 'upload_bytes', 'sample_count', 'first_observed_at', 'last_observed_at', 'state', 'sealed_event_id', 'created_at', 'updated_at', @@ -1625,12 +1626,12 @@ final class CloudSetup 'columns' => [ 'pool_id', 'instance_id', 'service_period_id', 'allocation_kind', 'allocation_target_id', - 'bucket_start', 'bucket_revision', + 'bucket_start', 'bucket_seconds', 'bucket_revision', ], ], 'cloud_traffic_settlement_due' => [ 'non_unique' => 1, - 'columns' => ['state', 'bucket_start', 'id'], + 'columns' => ['state', 'seal_at', 'id'], ], ], 'cloud_instance_backups' => [ diff --git a/web/app/Models/CloudTrafficUsageSettlementBucket.php b/web/app/Models/CloudTrafficUsageSettlementBucket.php index 121e7392..39a1f3d6 100644 --- a/web/app/Models/CloudTrafficUsageSettlementBucket.php +++ b/web/app/Models/CloudTrafficUsageSettlementBucket.php @@ -16,6 +16,8 @@ final class CloudTrafficUsageSettlementBucket extends Model 'entitlement_id' => 'int', 'allocation_target_id' => 'int', 'bucket_start' => 'int', + 'bucket_seconds' => 'int', + 'seal_at' => 'int', 'bucket_revision' => 'int', 'amount_bytes' => 'int', 'download_bytes' => 'int', diff --git a/web/app/Services/Cloud/CloudTrafficPoolAccounting.php b/web/app/Services/Cloud/CloudTrafficPoolAccounting.php index 3577f2ba..ffe734a9 100644 --- a/web/app/Services/Cloud/CloudTrafficPoolAccounting.php +++ b/web/app/Services/Cloud/CloudTrafficPoolAccounting.php @@ -23,6 +23,7 @@ use App\Models\CloudTrafficUsageSettlementBucket; final class CloudTrafficPoolAccounting { public const CLOSING_SECONDS = 90; + public const SETTLEMENT_WINDOW_SECONDS = 86400; /** Reconcile one service period into its one entitlement. */ public static function reconcileServicePeriod( @@ -1260,11 +1261,14 @@ final class CloudTrafficPoolAccounting } $instanceId = (int) $instance->id; - $bucketStart = intdiv($observedAt, 3600) * 3600; + $bucketStart = intdiv( + $observedAt, + self::SETTLEMENT_WINDOW_SECONDS + ) * self::SETTLEMENT_WINDOW_SECONDS; $lastEventId = self::sealOpenUsageBucketsLocked( $pool, $instanceId, - $bucketStart + $observedAt ); if ((string) $period->traffic_quota_mode !== 'unlimited') { $remaining = $delta; @@ -1381,17 +1385,16 @@ final class CloudTrafficPoolAccounting return self::resultLocked($pool, true, null); } - /** Seal a bounded set of completed hourly usage accumulators. */ + /** Seal a bounded set of completed usage accumulators. */ public static function sealDueUsageBuckets( int $limit = 200, ?int $now = null ): int { $now ??= time(); $limit = max(1, min(2000, $limit)); - $currentHour = intdiv($now, 3600) * 3600; $ids = CloudTrafficUsageSettlementBucket::where('state', 'open') - ->where('bucket_start', '<', $currentHour) - ->orderBy('bucket_start')->orderBy('id') + ->where('seal_at', '<=', $now) + ->orderBy('seal_at')->orderBy('id') ->limit($limit)->pluck('id') ->map(static fn ($id): int => (int) $id)->all(); $sealed = 0; @@ -1402,10 +1405,10 @@ final class CloudTrafficPoolAccounting } $connection = $hint->getConnection(); $sealed += $connection->transaction( - static function () use ($id, $currentHour): int { + static function () use ($id, $now): int { $hint = CloudTrafficUsageSettlementBucket::find($id); if ($hint === null || (string) $hint->state !== 'open' - || (int) $hint->bucket_start >= $currentHour) { + || (int) $hint->seal_at > $now) { return 0; } $pool = CloudTrafficPool::where( @@ -1419,7 +1422,7 @@ final class CloudTrafficPoolAccounting $eventId = self::sealOpenUsageBucketsLocked( $pool, (int) $hint->instance_id, - $currentHour, + null, $hint->entitlement_id === null ? null : (int) $hint->entitlement_id, (string) $hint->allocation_kind, @@ -1449,9 +1452,10 @@ final class CloudTrafficPoolAccounting if (!in_array($kind, ['entitlement', 'overage'], true) || $amount < 1 || $download < 0 || $upload < 0 || $download + $upload !== $amount - || $bucketStart % 3600 !== 0 + || $bucketStart % self::SETTLEMENT_WINDOW_SECONDS !== 0 || $observedAt < $bucketStart - || $observedAt >= $bucketStart + 3600 + || $observedAt >= $bucketStart + + self::SETTLEMENT_WINDOW_SECONDS || ($kind === 'entitlement' && ($entitlementId ?? 0) < 1) || ($kind === 'overage' && $entitlementId !== null)) { throw new \RuntimeException( @@ -1459,19 +1463,22 @@ final class CloudTrafficPoolAccounting ); } $targetId = $entitlementId ?? 0; + $bucketSeconds = self::SETTLEMENT_WINDOW_SECONDS; + $sealAt = $bucketStart + $bucketSeconds; $identity = CloudTrafficUsageSettlementBucket::where( 'pool_id', (int) $pool->id )->where('instance_id', $instanceId) ->where('service_period_id', $servicePeriodId) ->where('allocation_kind', $kind) ->where('allocation_target_id', $targetId) - ->where('bucket_start', $bucketStart); + ->where('bucket_start', $bucketStart) + ->where('bucket_seconds', $bucketSeconds); $bucket = (clone $identity)->where('state', 'open') ->orderByDesc('bucket_revision')->lockForUpdate()->first(); if ($bucket === null) { - // A late counter sample may arrive after the hour was sealed, or + // A late counter sample may arrive after the window was sealed, or // an attention/overage transition may have sealed the current - // hour early. Preserve the immutable event and start a new + // window early. Preserve the immutable event and start a new // revision for the remaining delta. $lastRevision = (int) (clone $identity) ->lockForUpdate()->max('bucket_revision'); @@ -1484,6 +1491,8 @@ final class CloudTrafficPoolAccounting $bucket->allocation_kind = $kind; $bucket->allocation_target_id = $targetId; $bucket->bucket_start = $bucketStart; + $bucket->bucket_seconds = $bucketSeconds; + $bucket->seal_at = $sealAt; $bucket->bucket_revision = $lastRevision + 1; $bucket->amount_bytes = $amount; $bucket->download_bytes = $download; @@ -1540,7 +1549,7 @@ final class CloudTrafficPoolAccounting private static function sealOpenUsageBucketsLocked( CloudTrafficPool $pool, ?int $instanceId = null, - ?int $beforeBucket = null, + ?int $dueAt = null, ?int $entitlementId = null, ?string $kind = null, ?int $onlyBucketId = null @@ -1551,8 +1560,8 @@ final class CloudTrafficPoolAccounting if ($instanceId !== null) { $query->where('instance_id', $instanceId); } - if ($beforeBucket !== null) { - $query->where('bucket_start', '<', $beforeBucket); + if ($dueAt !== null) { + $query->where('seal_at', '<=', $dueAt); } if ($entitlementId !== null) { $query->where('entitlement_id', $entitlementId); @@ -1626,7 +1635,8 @@ final class CloudTrafficPoolAccounting 'payload' => [ 'bucket_start' => (int) $bucket->bucket_start, 'bucket_revision' => (int) $bucket->bucket_revision, - 'bucket_seconds' => 3600, + '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, diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 2997668b..28081647 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -2311,9 +2311,9 @@ CREATE TABLE cloud_traffic_ledger_events ( KEY cloud_traffic_ledger_pool_time (pool_id, effective_at, id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; --- Durable hourly settlement accumulator. Mutable prepaid projections are --- updated on every observation; only sealed buckets become immutable ledger --- events, reducing permanent event volume without weakening FEFO accounting. +-- Durable settlement accumulator. Mutable prepaid projections are updated on +-- every observation; new buckets use UTC-day windows while legacy hourly +-- windows remain readable and sealable during the clean upgrade. CREATE TABLE cloud_traffic_usage_settlement_buckets ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, pool_id BIGINT UNSIGNED NOT NULL, @@ -2324,6 +2324,8 @@ CREATE TABLE cloud_traffic_usage_settlement_buckets ( allocation_kind VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, allocation_target_id BIGINT UNSIGNED NOT NULL, bucket_start BIGINT UNSIGNED NOT NULL, + bucket_seconds INT UNSIGNED NOT NULL, + seal_at BIGINT UNSIGNED NOT NULL, bucket_revision INT UNSIGNED NOT NULL, amount_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, download_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, @@ -2337,9 +2339,10 @@ CREATE TABLE cloud_traffic_usage_settlement_buckets ( updated_at BIGINT UNSIGNED NOT NULL, UNIQUE KEY cloud_traffic_settlement_identity ( pool_id, instance_id, service_period_id, - allocation_kind, allocation_target_id, bucket_start, bucket_revision + allocation_kind, allocation_target_id, bucket_start, bucket_seconds, + bucket_revision ), - KEY cloud_traffic_settlement_due (state, bucket_start, id), + KEY cloud_traffic_settlement_due (state, seal_at, id), KEY cloud_traffic_settlement_entitlement ( entitlement_id, state, bucket_start, id ), @@ -2353,11 +2356,13 @@ CREATE TABLE cloud_traffic_usage_settlement_buckets ( AND entitlement_id IS NULL AND allocation_target_id = 0) ), CONSTRAINT chk_cloud_traffic_settlement_bucket CHECK ( - bucket_start % 3600 = 0 + bucket_seconds IN (3600, 86400) + AND bucket_start % bucket_seconds = 0 + AND seal_at = bucket_start + bucket_seconds AND bucket_revision > 0 AND first_observed_at >= bucket_start AND last_observed_at >= first_observed_at - AND last_observed_at < bucket_start + 3600 + AND last_observed_at < seal_at ), CONSTRAINT chk_cloud_traffic_settlement_amount CHECK ( amount_bytes = download_bytes + upload_bytes diff --git a/web/tests/CloudAbuseMonitoringSchemaContractTest.php b/web/tests/CloudAbuseMonitoringSchemaContractTest.php index 0299abc1..154b01bb 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-v51-compact-telemetry-storage'" + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'" ), '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 6c399c94..37da1a51 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && 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 c480de12..e375d820 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-v51-compact-telemetry-storage`') + '`go-agent-wss-v52-daily-traffic-settlement`') && str_contains($deployment, '`occurrence_generation = 1` 与 `transition_revision = 1`') && str_contains($deployment, diff --git a/web/tests/CloudAdminTrafficPoolServiceTest.php b/web/tests/CloudAdminTrafficPoolServiceTest.php index f4cd4be2..e3e3e0aa 100644 --- a/web/tests/CloudAdminTrafficPoolServiceTest.php +++ b/web/tests/CloudAdminTrafficPoolServiceTest.php @@ -146,6 +146,8 @@ $schema->create('cloud_traffic_usage_settlement_buckets', static function (Bluep $t->string('allocation_kind'); $t->integer('allocation_target_id'); $t->integer('bucket_start'); + $t->integer('bucket_seconds'); + $t->integer('seal_at'); $t->integer('bucket_revision'); $t->integer('amount_bytes'); $t->integer('download_bytes'); @@ -159,7 +161,8 @@ $schema->create('cloud_traffic_usage_settlement_buckets', static function (Bluep $t->integer('updated_at'); $t->unique([ 'pool_id', 'instance_id', 'service_period_id', 'allocation_kind', - 'allocation_target_id', 'bucket_start', 'bucket_revision', + 'allocation_target_id', 'bucket_start', 'bucket_seconds', + 'bucket_revision', ], 'traffic_settlement_identity'); }); $schema->create('cloud_traffic_instance_cursors', static function (Blueprint $t): void { diff --git a/web/tests/CloudBackupPublicationPreparationSchemaContractTest.php b/web/tests/CloudBackupPublicationPreparationSchemaContractTest.php index 21e06b05..a5bbf195 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && 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 9d43d597..b62eac91 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && !str_contains($setup, "SCHEMA_VERSION = 'go-v1'") - && str_contains($deployment, '`go-agent-wss-v51-compact-telemetry-storage`') - && str_contains($compensation, '`go-agent-wss-v51-compact-telemetry-storage`'), + && str_contains($deployment, '`go-agent-wss-v52-daily-traffic-settlement`') + && str_contains($compensation, '`go-agent-wss-v52-daily-traffic-settlement`'), '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 1fe73f96..6edc6419 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-v51-compact-telemetry-storage'"), + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'"), '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 ef29032f..1995b59a 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && 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 913e53cf..6e91c78b 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && 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 614abe19..91a809ae 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && 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 a13949e6..7f827600 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && str_contains($attemptModel, "protected \$table = 'cloud_backup_restore_attempts';") && str_contains($attemptModel, "'active_attempt' => 'int'") diff --git a/web/tests/CloudServiceCompensationSchemaContractTest.php b/web/tests/CloudServiceCompensationSchemaContractTest.php index 2b60fdfa..0126743b 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-v51-compact-telemetry-storage'"), + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'"), '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 00383040..bd5c29ba 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-v51-compact-telemetry-storage'"), + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'"), '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 163d9d35..2d062084 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-v51-compact-telemetry-storage'"), + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'"), '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 d613d6b3..a29db9f3 100644 --- a/web/tests/CloudTrafficPoolAccountingTest.php +++ b/web/tests/CloudTrafficPoolAccountingTest.php @@ -134,6 +134,8 @@ $schema->create('cloud_traffic_usage_settlement_buckets', static function (Bluep $table->string('allocation_kind'); $table->integer('allocation_target_id'); $table->integer('bucket_start'); + $table->integer('bucket_seconds')->default(86400); + $table->integer('seal_at'); $table->integer('bucket_revision'); $table->integer('amount_bytes'); $table->integer('download_bytes'); @@ -147,7 +149,8 @@ $schema->create('cloud_traffic_usage_settlement_buckets', static function (Bluep $table->integer('updated_at'); $table->unique([ 'pool_id', 'instance_id', 'service_period_id', 'allocation_kind', - 'allocation_target_id', 'bucket_start', 'bucket_revision', + 'allocation_target_id', 'bucket_start', 'bucket_seconds', + 'bucket_revision', ], 'traffic_settlement_identity'); }); $schema->create('cloud_traffic_instance_cursors', static function (Blueprint $table): void { @@ -735,27 +738,27 @@ $assert($snapshotBucket !== null && (int) $snapshotBucket->last_observed_at === $base + 10, 'Counters were paired with a stale observation timestamp.'); -$settlementHour = intdiv($base, 3600) * 3600; +$settlementDay = intdiv($base, 86400) * 86400; $bucketedInstance = $newInstance(72, 22); $bucketedPeriod = $newPeriod( $bucketedInstance, 800, 1, 1_000, - $settlementHour, - $base + 7_200 + $settlementDay, + $settlementDay + 172_800 ); CloudTrafficPoolAccounting::reconcileServicePeriod( 800, 'test-bucketed-settlement:initial', $base ); $bucketedInstance->lifetime_download_bytes = 10; $bucketedInstance->lifetime_upload_bytes = 5; -$bucketedInstance->traffic_synced_at = $settlementHour + 10; +$bucketedInstance->traffic_synced_at = $settlementDay + 10; $bucketedInstance->save(); CloudTrafficPoolAccounting::settleInstanceUsage(72, $base); $bucketedInstance->lifetime_download_bytes = 25; $bucketedInstance->lifetime_upload_bytes = 8; -$bucketedInstance->traffic_synced_at = $settlementHour + 20; +$bucketedInstance->traffic_synced_at = $settlementDay + 3_620; $bucketedInstance->save(); CloudTrafficPoolAccounting::settleInstanceUsage(72, $base); $bucketedPool = CloudTrafficPool::where('user_id', 22) @@ -763,6 +766,9 @@ $bucketedPool = CloudTrafficPool::where('user_id', 22) $openBucket = Capsule::table('cloud_traffic_usage_settlement_buckets') ->where('instance_id', 72)->where('state', 'open')->first(); $assert($openBucket !== null + && (int) $openBucket->bucket_start === $settlementDay + && (int) $openBucket->bucket_seconds === 86_400 + && (int) $openBucket->seal_at === $settlementDay + 86_400 && (int) $openBucket->amount_bytes === 33 && (int) $openBucket->download_bytes === 25 && (int) $openBucket->upload_bytes === 8 @@ -772,13 +778,17 @@ $assert($openBucket !== null && CloudTrafficPoolAccounting::verifyProjection( (int) $bucketedPool->id )['valid'] === true, - 'Within-hour traffic did not remain a verifiable durable accumulator.'); + 'Within-day traffic did not remain a verifiable durable accumulator.'); +$assert(CloudTrafficPoolAccounting::sealDueUsageBuckets( + 200, $settlementDay + 3_600 + ) === 0, + 'A daily settlement bucket was sealed at the former hourly boundary.'); $sealedBucketCount = CloudTrafficPoolAccounting::sealDueUsageBuckets( - 200, $settlementHour + 3600 + 200, $settlementDay + 86_400 ); $assert($sealedBucketCount >= 1 && CloudTrafficPoolAccounting::sealDueUsageBuckets( - 200, $settlementHour + 3600 + 200, $settlementDay + 86_400 ) === 0 && Capsule::table('cloud_traffic_usage_settlement_buckets') ->where('instance_id', 72)->where('state', 'sealed')->count() === 1 @@ -787,7 +797,7 @@ $assert($sealedBucketCount >= 1 'Completed settlement buckets were not sealed exactly once.'); $bucketedInstance->lifetime_download_bytes = 30; $bucketedInstance->lifetime_upload_bytes = 10; -$bucketedInstance->traffic_synced_at = $settlementHour + 30; +$bucketedInstance->traffic_synced_at = $settlementDay + 7_230; $bucketedInstance->save(); CloudTrafficPoolAccounting::settleInstanceUsage(72, $base); $lateBucket = Capsule::table('cloud_traffic_usage_settlement_buckets') diff --git a/web/tests/CloudTrafficPoolAttentionIntegrationTest.php b/web/tests/CloudTrafficPoolAttentionIntegrationTest.php index f0b7fee8..09a99994 100644 --- a/web/tests/CloudTrafficPoolAttentionIntegrationTest.php +++ b/web/tests/CloudTrafficPoolAttentionIntegrationTest.php @@ -130,6 +130,8 @@ $schema->create('cloud_traffic_usage_settlement_buckets', static function (Bluep $table->string('allocation_kind'); $table->integer('allocation_target_id'); $table->integer('bucket_start'); + $table->integer('bucket_seconds'); + $table->integer('seal_at'); $table->integer('bucket_revision'); $table->integer('amount_bytes'); $table->integer('download_bytes'); @@ -143,7 +145,8 @@ $schema->create('cloud_traffic_usage_settlement_buckets', static function (Bluep $table->integer('updated_at'); $table->unique([ 'pool_id', 'instance_id', 'service_period_id', 'allocation_kind', - 'allocation_target_id', 'bucket_start', 'bucket_revision', + 'allocation_target_id', 'bucket_start', 'bucket_seconds', + 'bucket_revision', ], 'traffic_settlement_identity'); }); $schema->create('cloud_traffic_instance_cursors', static function (Blueprint $table): void { diff --git a/web/tests/CloudTrafficPoolSchemaContractTest.php b/web/tests/CloudTrafficPoolSchemaContractTest.php index 1de8fb8d..97d944ba 100644 --- a/web/tests/CloudTrafficPoolSchemaContractTest.php +++ b/web/tests/CloudTrafficPoolSchemaContractTest.php @@ -48,7 +48,9 @@ $assert(str_contains($schema, && str_contains($schema, 'UNIQUE KEY cloud_traffic_settlement_identity (') && str_contains($schema, - 'allocation_kind, allocation_target_id, bucket_start, bucket_revision') + 'allocation_kind, allocation_target_id, bucket_start, bucket_seconds,') + && str_contains($schema, + 'KEY cloud_traffic_settlement_due (state, seal_at, id)') && str_contains($schema, 'UNIQUE KEY cloud_traffic_scan_failure_subject (scan_kind, subject_id)'), 'Traffic-pool identity, FEFO or immutable ledger indexes are incomplete.'); @@ -76,7 +78,7 @@ $assert(str_contains($schema, 'Service-period traffic-pool identity is not frozen or indexed.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && 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 c8f32b9e..ca2d1680 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-v51-compact-telemetry-storage'") + "private const SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && 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 b40dea69..b989564a 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-v51-compact-telemetry-storage'") + "SCHEMA_VERSION = 'go-agent-wss-v52-daily-traffic-settlement'") && str_contains($setup, "self::schema('ss.sql') . \"\\0\" . self::schema('cloud.sql')") && str_contains($setup,