diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 5272a72e..640ff044 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,40 @@ # 本版验证记录 +## 2026-10-14:VPC 配置完成与成员运行健康解耦 + +- 现场三条“待回读”并非同一种故障。VPC `5518137d9479fc40bf153c26a3f4c350` + 和 `2e0fcb4554a8f1d95b1e47841a7e5c93` 的当前 operation 已为 + `succeeded`,根 revision/digest 已相等;停机或未完成 QGA 核验的成员把旧聚合 + 状态重新降为 `degraded/waiting`,worker 因而持续领取已经成功的 operation。 + VPC `d04477f7186cc741083ef762e0dfbd61` 的 operation + `48c697995efe24559011c26cb950449f` 则仍缺两台宿主的配置证明,属于真实配置门禁, + 不能用本次状态拆分冒充成功。 +- `recordObserved()` 现在以每台宿主的 exact configuration receipt 决定 operation、 + host deployment 和 VPC 根状态。实例停机、暂停、QGA 不可用或来宾地址/路由不匹配 + 只更新 member/private-IP 健康,不再撤销已经确认的宿主配置。API 新增唯一根字段 + `configured`;旧 `usable` 保留为所有成员运行态聚合,页面使用 `configured` 判断 + VPC 是否仍在等待配置,并在成员区单独显示运行健康。 +- VPC worker 不再因 stopped/suspended/QGA 等来宾状态重放 succeeded operation; + 只有宿主配置证明后来变为 waiting/uncertain 时,才允许原 operation 进入配置回读。 + 电源工作流在配置确认后暂停时只记录自身错误,不覆盖 VPC 根后来出现的真实配置漂移。 + 删除、成员退出、IP/CIDR 释放和 tombstone absence proof 门槛未放宽。 +- 曾评估用数据库摘要自动提升旧 `degraded/applied` 行,但独立审查发现精简实现无法 + 完整复用 deleted-host removal proof 和 operation host closed set,因此没有合入。 + 升级不会凭旧摘要猜测成功;现有 waiting/uncertain 行仍按原 operation 走严格 + `recordObserved()`,paused 行仍需同 ID 的只读 Engine 证据和显式核对。 +- Mac 本机使用 PHP 8.5 WASM 项目运行时执行全部 12 个 `CloudVpc*Test.php`,并使用 + bundled Node 执行两个 `CloudVpc*Test.mjs`,全部通过;七个修改后的 PHP 文件 lint、 + 两个修改后的 JavaScript 文件 `node --check` 和 `git diff --check` 通过。项目 + `engine/.venv`(Python 3.12.14)执行六个 VPC 核心模块为 **405 passed**,保留 + 39 条既有 XML truthiness 弃用警告。本轮未修改 Engine,也未重复全量 Engine; + 上一轮全量基线仍为 **3,975 passed、24 skipped、6 failed**。六项既有失败中三项 + 是旧测试/fixture 漂移,三项是公网池地址占用/耗尽缺陷;公网池缺陷会影响创建新实例 + 的公网 IP 分配,但不是已有实例加入 VPC 私网的本次状态耦合根因。 +- `docs/VPC_V2_SIMPLIFICATION.md` 记录后续单一路线:保留 PHP 业务/IPAM 和 + WireGuard + L3 保证,把宿主写入逐台迁移到单 writer Agent;首版删除自动电源耦合、 + QGA 成功门槛以及自定义 subnet/route/ACL。该文档是迁移边界,不表示 Agent 或 v2 + 已部署;AlmaLinux、Debian、跨宿主流量、重启和故障注入仍须真实宿主验收。 + ## 2026-10-14:新 VPC 加入回滚与原 operation 显式恢复 - 现场固定 operation `708fa7c660383d7ee945d1543de1e0a8`、VPC diff --git a/docs/VPC_V2_SIMPLIFICATION.md b/docs/VPC_V2_SIMPLIFICATION.md new file mode 100644 index 00000000..fe839f9b --- /dev/null +++ b/docs/VPC_V2_SIMPLIFICATION.md @@ -0,0 +1,409 @@ +# VPC v2 简化架构与迁移边界 + +状态:设计提案,尚未实现。 + +审查基线:`venix` `86fa8f60865b37fa0f45cf620eedd453dcaa0494`。 + +适用范围:同地区、跨宿主机的 WireGuard + L3 私网。 + +## 结论 + +VPC v2 不再扩展当前 v1 状态机。目标只有一条路线:保留 PHP 业务控制面和 +WireGuard + L3 数据面,把宿主机写入收敛到每台宿主机上的固定版本 Agent;租户 +VPC 只提供自动 `/24`、隐式单子网、每实例一个 `/32`、同 VPC 默认互通和跨 VPC +默认隔离。 + +这是一项迁移设计,不表示 Go Agent、v2 schema、v2 API 或迁移工具已经存在。 +生产环境在完成本文各阶段门槛前仍运行 v1。迁移过程中,一个宿主机只能有一个 +写入后端;不能让 Python/SSH 与 Agent 同时修改相同的 libvirt、seed、WireGuard、 +route 或 nftables 资源。 + +## 为什么停止继续修补 v1 + +审查基线中,仅以下三个引擎文件已有 23,179 行: + +- `engine/virsh_panel/fabric.py` +- `engine/virsh_panel/vpc.py` +- `engine/virsh_panel/vpc_dataplane.py` + +PHP 的 `CloudVpc*` 核心文件合计 7,841 行;相关 Engine/PHP 测试约 39,542 行。 +从 `887072ac61` 到审查基线共有 86 个提交、277 个文件变化和 113,920 行新增。 +这些数字只用于说明当前维护面,不作为按行删除代码的目标。 + +复杂度主要来自多套正确性机制互相组合: + +- PHP 同时维护 VPC、子网、私网 IP、成员、route、ACL、宿主部署和 operation, + 各层又有 desired/observed revision、digest、状态和 tombstone。 +- Fabric、VPC、实例电源和来宾 QGA 各有独立状态,随后通过专用 worker、lease、 + 自动关机/开机工作流和周期 reconcile 互相推进。 +- 每次成员变更既要处理宿主 bridge、route、WireGuard AllowedIPs、nftables、 + proxy ARP、邻居、seed、persistent/live XML,又要适配 NetworkManager 与 + ifupdown 的持久化和恢复差异。 +- operation 的宿主配置完成、HTTP 回执、实例电源状态和来宾网络可用是四种事实, + 当前页面和 worker 仍需要大量分支才能把它们收敛。 + +`docs/VALIDATION.md` 在 2026-10-14 的连续现场记录进一步显示,合法的多 VPC state +曾因重复 Fabric peer、route 校验范围、bridge 恢复顺序、helper 契约版本和旧 +coordination claim 分别失败。同一数据面连续修复仍会产生新的状态组合,说明问题 +已经超出单个条件判断或单次回读修复的范围。 + +## v2 保留的保证 + +简化不能以放弃以下保证为代价: + +1. PHP 仍是账户、授权、VPC/IPAM、实例归属和 operation 的业务事实源。 +2. VPC 仍限制为同地区、全局不重叠的 RFC1918 `/24`;一个实例最多加入一个 + VPC,每个成员只有一个唯一 `/32` 地址。 +3. 每个写请求都有稳定 `operation_id`、幂等键、目标 generation 和摘要。响应丢失 + 时只查询同一 operation,不能用新 ID 猜测性重放。 +4. 跨 VPC 默认拒绝;同 VPC 默认互通。宿主继续执行源 MAC/IP 反欺骗、IPv6 和 + 未登记目标隔离,公网 `public0/br0` 不被私网操作改写。 +5. Agent 只管理带明确 owner 的 `wg-fabric0`、VPC bridge、route 和 nftables + 对象。未知同名资源或外部漂移必须停止写入,不能自动接管或清空。 +6. 成员加入必须精确回读 persistent XML、私网 MAC/bridge、宿主 route、 + WireGuard AllowedIPs 和 nftables;HTTP 2xx 本身不代表配置成功。 +7. 成员退出和 VPC 删除必须先取得所有受影响宿主的不存在性证明,再释放私网 IP + 或 CIDR。超时和未知结果保留占用。 +8. Fabric 是地区基础设施。宿主未完成 enrollment、握手、路由和重启恢复验收时, + 不能承载新的租户私网。 +9. 生产环境始终只有一个宿主写入者。切换后端本身也必须有持久 fence 和审计记录。 + +## v2 删除或延期的机制 + +以下机制不进入 v2 首版: + +| 机制 | v2 处理 | +| --- | --- | +| 用户自定义 subnet CRUD | 删除;一个 VPC 只有一个与根 CIDR 相同的隐式子网 | +| 用户自定义 route | 延期;首版只生成成员 `/32` 路由 | +| 用户自定义 ACL | 延期;固定为同 VPC 双向允许、跨 VPC 默认拒绝 | +| 自动关机、配置、自动开机 | 删除;加入和退出前要求实例已经完全关机 | +| `CloudVpcPowerWorkflow` 多阶段 JSON | 删除;电源操作与 VPC operation 完全分离 | +| QGA 作为 operation 成功门槛 | 删除;QGA 仅更新独立的 guest health | +| `waiting_observed` 周期重试 | 删除;宿主结果在有界期限内进入成功、失败或 uncertain | +| 每个子资源的 revision/digest/tombstone | 删除;根 generation、成员/IP tombstone 和 operation receipt 足够 | +| 每个 VPC state 复制全 Fabric peer union | 删除;每台宿主只保存一份完整 host manifest | +| 租户请求动态升级 Fabric/helper | 删除;Fabric/Agent 升级是管理员维护操作 | +| NetworkManager/ifupdown 在线接管与 shadow 恢复 | 删除;Agent 只操作预先声明的自有对象 | +| 多 Engine writer 或自动接管其他 writer | 延期;先保持单 writer,再单独设计分布式 fencing | + +旧的自定义 route、ACL 或多子网不能通过兼容分支永久带入 v2。迁移审计发现这些 +对象时,该 VPC 保持 v1 只读;管理员先将其收敛为 v2 固定能力,随后再迁移。 + +## 单一路线目标架构 + +```text +浏览器 + -> PHP HTTPS/API + - 账户、授权、IPAM + - VPC/member desired state + - operation 与 per-host receipt + - 持久 worker + -> mTLS -> Host Agent (AlmaLinux) + -> mTLS -> Host Agent (Debian) + +Host Agent + - 本机 durable operation receipt + - 本机完整 desired manifest + - libvirt persistent XML / private0 + - wg-fabric0、精确 route/AllowedIPs + - 单一 Agent-owned nftables table + - 原子 apply、精确 observe、开机恢复 +``` + +浏览器不直接访问 Agent,也不生成宿主命令。PHP worker 发送的是有界、带版本的 +typed manifest,不发送 shell、raw nft 或任意 libvirt XML。Agent 根据固定产品合同 +生成本机配置。 + +Fabric 在宿主 enrollment 或维护窗口中建立。每台宿主只有一个 `wg-fabric0`,peer、 +endpoint、overlay `/32` 和密钥不随租户 VPC 操作变化。租户成员变更只更新完整 host +manifest 中的 VPC bridge、成员 `/32`、peer tenant AllowedIPs 和固定隔离规则。 + +每份 host manifest 包含该宿主的全部有效 VPC,而不是一组互相聚合的 per-VPC state +文件。manifest 以单调 generation 和 digest 标识;Agent 只接受更高 generation,或 +相同 generation、相同 digest 的幂等查询。相同 generation、不同 digest 必须拒绝。 + +### 成员加入 + +1. PHP 确认实例完全关机,并锁定 VPC、实例和私网地址账本。 +2. PHP 分配 `/32`,写入成员 desired state 和唯一 operation。 +3. PHP worker 为所有受影响宿主生成完整 manifest,并使用同一 operation ID 派发。 +4. Agent 原子应用并回读自己的 manifest,持久保存回执。 +5. 所有受影响宿主 exact 后,operation 进入 `succeeded`,成员进入 `configured`。 +6. 用户使用独立电源操作启动实例。QGA 可更新 `guest_state`,但不能把已经确认的 + 宿主配置重新变成“待回读”。 + +### 成员退出 + +1. PHP 确认实例完全关机,成员进入单一 `removing` tombstone。 +2. Agent 从受影响宿主的完整 manifest 移除成员,并移除 persistent `private0`。 +3. 全部宿主证明 XML、route、AllowedIPs 和 nft 集合中均不存在该成员后,PHP 才把 + 私网 IP 标为可复用。 +4. 任一宿主不可达或回执未知时,operation 为 `uncertain`,成员/IP 保持占用;不创建 + 第二个退出 operation。 + +### 状态边界 + +v2 operation 只使用五种状态: + +- `queued` +- `applying` +- `succeeded` +- `failed` +- `uncertain` + +成员把宿主配置和来宾健康分开: + +- `host_state`: `pending | configured | removing | uncertain | error` +- `guest_state`: `unknown | stopped | online | mismatch` + +`guest_state` 是健康信息,不参与 IP 释放、隔离和 operation 成功判断。VPC 聚合页面 +分别展示配置状态与来宾状态,不能再用一个“待回读”同时表示宿主未配置、实例未启动、 +QGA 不可用和 HTTP 回执未知。 + +## Host executor 单写边界 + +只把 VPC 网络交给 Agent、同时让 Python 继续直接修改同一宿主的 domain XML 或 seed, +会产生两个写入者,不能接受。v2 必须按宿主迁移完整 executor 边界。 + +建议为宿主增加: + +- `executor_backend`: `python_ssh | agent_v1` +- `executor_epoch`: 单调 fencing generation +- Agent identity 和证书指纹 + +当宿主为 `python_ssh` 时,Agent 只能 observe,不能 apply。当宿主切换为 `agent_v1` +后,所有可能修改 libvirt、domain XML、cloud-init seed、磁盘、快照、实例电源和本地 +网络的操作都必须经 Agent。Python 可以在迁移期作为协议代理或只读兼容层,但不能绕过 +Agent 直接写宿主。 + +executor 切换必须满足: + +1. 该宿主没有 queued/running/uncertain 的 VM、VPC、删除、重装、快照或更新操作。 +2. Python 协调锁和远端 systemd operation 均已取得终态证据。 +3. Agent observe 与 PHP 实例/网络账本一致。 +4. 持久写入新的 `executor_epoch`,旧 backend 收到旧 epoch 后拒绝写入。 +5. 完成一次创建、开关机、重装、删除和 VPC 加入/退出的 canary 验收后,才开放该 + 宿主的新任务。 + +切换完成后不自动回退为 `python_ssh`。需要回退时先冻结宿主、证明 Agent 没有在途 +写入,再以新的 epoch 执行独立迁移。 + +## 立即止血 + +在 v2 可用前,先阻止 v1 继续产生新的状态组合: + +1. 关闭新建 VPC、成员加入、成员退出、route/ACL 变更和 VPC 删除入口;保留现有 + 私网流量、只读页面和管理员证据读取。 +2. VPC worker 停止领取新的 mutation,只允许对已经存在的 operation 做同 ID 只读 + 核对。不能批量点击“重新核对”制造并发任务。 +3. 对当前三个“待回读” VPC 分别保存 operation ID、revision/digest、成员、宿主集合、 + Engine receipt、远端 operation 和当前 XML/route/WG/nft 证据。 +4. persistent XML 与宿主网络已经 exact、只是 QGA/guest 未确认时,归类为“宿主已配置, + 来宾未知”,不再自动关机或开机。 +5. 现场漂移或写入结果未知时进入维护队列,仍以原 operation ID 核对;不释放 IP、 + 不清理 claim、不新建 operation。 + +止血开关必须独立于普通维护页,部署更新不能顺带解除。恢复 v1 写入口不是 v2 迁移的 +前置步骤。 + +## v1 未决 operation 处理 + +迁移工具对每个旧 operation 只允许以下分类: + +| v1 证据 | 处理 | +| --- | --- | +| 已有 `succeeded`、`failed` 或 `superseded` 终态 | 原样保留,作为审计历史 | +| `queued` 且 Engine、宿主 spool、systemd unit 都证明从未派发 | 以明确 `not_dispatched` 原因终结,不执行宿主写入 | +| `running`、`waiting_observed`、`paused` 或 `uncertain`,可能已经派发 | 只按原 ID 读取 Engine/宿主结果;禁止创建 v2 替代写操作 | +| 宿主配置 exact,仅缺 QGA 或 guest 启动证据 | 旧操作不伪装为 v1 成功;由 migration operation 接管当前配置,旧操作记录迁移关联并终结为 superseded | +| 宿主不存在目标配置,且确证原操作未写入 | 终结旧操作后才允许进入 v2 migration | +| 回执、现场或资源归属无法证明 | 将 VPC 标记为 `migration_blocked`,人工处理;不猜测成功或失败 | + +旧 power workflow 不在迁移中自动恢复开机。迁移前记录当前真实电源状态;迁移只在实例 +已经关机时修改网络,完成后由用户或独立电源任务决定是否启动。`original_running`、 +`resume_cancelled` 和旧 child operation 只保留审计,不转换成 v2 自动动作。 + +七个无 operation、无资源的历史 uncertain claim 也不能因时间旧或资源列表为空而批量 +删除。它们不直接转成 v2 operation;只有现有协调层能证明其未派发或已终结时才关闭。 + +## 数据库只增不删迁移 + +首轮 schema 只增加字段和表,不删除、重命名或复用 v1 字段: + +### 新增宿主字段 + +- `cloud_hosts.executor_backend` +- `cloud_hosts.executor_epoch` +- Agent identity、证书指纹和最后一次健康回读时间 + +### 新增 VPC/成员字段 + +- `cloud_vpcs.backend_version` +- `cloud_vpcs.migration_state` +- `cloud_vpcs.migrated_at` +- `cloud_vpc_members.desired_state` +- `cloud_vpc_members.host_state` +- `cloud_vpc_members.guest_state` + +### 新增 operation 证据 + +- `cloud_vpc_operations.schema_version` +- `cloud_vpc_operations.superseded_by_operation_id` +- 新表 `cloud_vpc_operation_hosts`,保存 operation、host、executor epoch、manifest + generation/digest、状态和有界 receipt + +以下 v1 表在迁移期间继续保留,但对 `backend_version=2` 的 VPC 只读: + +- `cloud_vpc_subnets` +- `cloud_vpc_routes` +- `cloud_vpc_acl_rules` +- `cloud_vpc_host_deployments` +- `cloud_vpc_operations.power_workflow_json` +- `cloud_vpc_operations.power_instance_id` + +`cloud_private_networks`、`cloud_private_cidr_claims`、`cloud_vpcs`、 +`cloud_vpc_private_ips`、`cloud_vpc_members` 和 `cloud_vpc_operations` 继续承担地址与 +审计保证,不在迁移中移除。 + +迁移完成后的表清理属于单独设计和单独发布。只有所有 VPC 均为 v2、所有 v1 operation +终态、所有 tombstone 收敛、备份和回滚保留期结束后,才能提出 drop migration。本文 +不授权执行任何 drop。 + +## 每个 VPC 的迁移资格 + +自动迁移前必须同时满足: + +1. 根 CIDR 为受支持的 RFC1918 `/24`,CIDR claim 唯一且完整。 +2. 恰好一个活动子网,且它与根 CIDR 相同。 +3. ACL 只有平台默认的同 VPC ingress/egress 允许规则。 +4. 没有用户自定义 route。 +5. 每个成员恰好关联一个私网 IP lease,VM、host、MAC、IP 均唯一。 +6. 没有 `deleting` 子资源、未完成 tombstone 或无法解释的 host deployment。 +7. 没有 queued/running/waiting/paused/uncertain 的 v1 operation。 +8. PHP desired、Engine desired 和所有宿主实际状态能够生成相同的 v2 manifest。 + +任一条件失败时保持 v1 只读并输出具体阻断原因,不自动删除数据来满足资格。 + +## 分阶段实施与门槛 + +### 阶段 0:冻结和现场分类 + +- 部署 v1 mutation kill switch。 +- 固定并核对当前未决 operation。 +- 导出数据库与各宿主受管网络/operation 清单。 + +门槛:没有新的 v1 mutation;所有现有 operation 都有唯一分类和负责人。 + +### 阶段 1:只增 schema 和 Agent observe + +- 应用新增 schema,旧代码仍能运行。 +- 部署 Agent,但 `executor_backend=python_ssh` 时只能 observe。 +- Agent 生成 host manifest 和 drift 报告,不执行写入。 + +门槛:AlmaLinux 与 Debian 的 observe 结果均与当前 XML、route、WG 和 nft 现场一致; +Agent 重启不改变任何宿主状态。 + +### 阶段 2:完整宿主 executor canary + +- 选择隔离测试宿主,清空在途任务并提升 `executor_epoch`。 +- 把该宿主全部写操作切换为 `agent_v1`。 +- 执行 VM 创建、开关机、重装、救援、快照、删除和 VPC 全生命周期。 + +门槛:同一宿主不存在第二个 writer;响应丢失、Agent 重启和面板重启均通过原 operation +收敛;公网功能无回归。 + +### 阶段 3:新建 v2 VPC canary + +- 仅向 canary 账户开放 v2 创建和 stopped-VM 加入。 +- 使用至少一台 AlmaLinux 和一台 Debian 宿主完成跨宿主测试。 +- 使用一台 QGA 正常 VM 和一台 QGA disabled/unavailable VM。 + +门槛:两台 VM 的宿主配置 operation 都终结;QGA 不可用的 VM 显示 +`configured + guest unknown`,不能停在“待回读”。 + +### 阶段 4:迁移现有 VPC + +- 对通过资格扫描的 VPC 生成 migration operation 和完整 per-host manifest。 +- 所有成员停机后写入目标 seed/XML,Agent 应用并精确回读。 +- 在同一数据库事务中把 VPC `backend_version` 切换为 2,并记录旧 operation 关联。 + +门槛:切换前可无写入回退;切换后只有 Agent writer。任一宿主失败时不翻转版本,保留 +地址与旧数据。 + +### 阶段 5:关闭 v1 写路径 + +- 全部 VPC 迁移后永久关闭 v1 worker、自动电源工作流、旧 Fabric/VPC mutation API。 +- Python v1 VPC reconciler 仅保留有界审计读取,随后独立删除代码。 + +门槛:数据库中没有 v1 活动 VPC、非终态 operation、未收敛 tombstone 或 v1 executor +宿主。代码删除和数据库 drop 不与该阶段合并。 + +## 回滚边界 + +- `backend_version` 翻转前,Agent 只 observe 或执行可证明的 canary;可以撤回 Agent + 代码而不改写业务账本。 +- host executor 或 VPC 翻转后,不能直接部署旧代码并恢复 Python/SSH 写入。旧 writer + 不认识新的 epoch、manifest 和 operation receipt,自动回退可能覆盖已应用状态。 +- 翻转后的故障采用 forward-fix:冻结该宿主/VPC,读取同一 operation,修复 Agent 或 + manifest,再以相同 generation/digest 收敛。 +- 代码回滚包必须认识 v2 schema 和 kill switch,即使它暂时不开放新操作,也不能把 v2 + 行当成 v1 行处理。 + +## AlmaLinux 与 Debian 真实验收 + +以下项目必须在真实宿主执行;模拟测试、Shell 语法和 HTTP 成功不能替代: + +### 宿主前置和 Fabric + +- AlmaLinux 与 Debian 使用相同 Agent 协议和 manifest 语义;发行版差异只留在 Agent + 的本地适配层,不改变成功条件。 +- 预检 kernel WireGuard、nftables、libvirt、SELinux/AppArmor、时间同步、MTU、UDP + underlay 和证书权限。 +- Agent enrollment、证书轮换、升级、重启和宿主 reboot 后,`wg-fabric0`、peer、 + endpoint、overlay route 和 owner 证据完全恢复。 +- 私网操作前后,公网 bridge、默认路由、管理 SSH 和已有 VM 公网连通保持不变。 + +### 成员配置和流量 + +- 停机实例加入后,persistent XML、private0 MAC/bridge、seed、宿主 `/32` route、 + WG AllowedIPs 和 nft 集合精确一致。 +- 启动与 VPC 配置是两个 operation;启动失败不能回滚已确认的宿主网络。 +- QGA enabled、disabled、unavailable 三种镜像都能终结配置 operation,只有 guest + health 不同。 +- 同机和跨机分别验证双向 ICMP、TCP 和 UDP;验证跨 VPC 拒绝、伪造 MAC/IP 拒绝、 + IPv6/广播/多播边界和访问宿主服务边界。 +- 至少创建三个 VPC,并依次向每个 VPC 添加新实例,不能出现共享 state 污染或全部 + 进入同一个“待回读”状态。 + +### 故障与恢复 + +- 丢失 apply HTTP 回包后只查询原 operation;Agent 不能重复执行同一 generation。 +- 在 manifest 落盘前、宿主写入中、写入后回执前分别中断 Agent,确认结果只会收敛为 + succeeded、failed 或 uncertain,不出现第二个 writer。 +- 面板、worker、Agent 和宿主分别重启后,原 operation 与本地 receipt 能重新关联。 +- 一台宿主离线时,新成员不宣称 configured;已有成员流量和其他 VPC 不被无关重写。 +- detach 只在全部宿主 absence proof 后释放 IP;中途失败时原 IP 仍不可分配。 +- Agent 遇到未知 bridge、route、WG peer 或 nft owner 时停止写入并给出有界错误, + 不执行自动清理。 + +### 完整生命周期 + +executor canary 还必须验证创建、删除、重装、救援、快照、开关机、配额断网和到期清理。 +这些路径可能修改 XML、seed、磁盘或网络;缺少任一项就不能证明 host executor 已经安全 +从 Python/SSH 切换到 Agent。 + +## 发布完成标准 + +只有同时满足以下条件,才能宣布 v2 可替代 v1: + +- 当前三个待回读 VPC 已按原 operation 分类并安全终结或明确阻断。 +- AlmaLinux 与 Debian 的 canary host 已完成 executor 全生命周期验收。 +- 三个独立 VPC 连续添加实例成功,QGA 不可用不会阻塞宿主配置终态。 +- 跨宿主允许流量、跨 VPC 拒绝、反欺骗、公网无回归和宿主 reboot 均有实机证据。 +- 响应丢失、服务重启和部分宿主失败均只使用原 operation 收敛。 +- 所有生产 VPC 已标明 v1 或 v2,且每个宿主只有一个 executor writer。 +- v1 写入口已关闭,但 v1 数据尚未删除,可继续审计和恢复。 + +在这些门槛完成前,本文只能作为实施边界,不能作为“Go Agent 已上线”或“VPC 已完成 +重构”的证明。 diff --git a/web/app/Services/Cloud/CloudVpcPowerWorkflow.php b/web/app/Services/Cloud/CloudVpcPowerWorkflow.php index 83c1e334..602e1f5b 100644 --- a/web/app/Services/Cloud/CloudVpcPowerWorkflow.php +++ b/web/app/Services/Cloud/CloudVpcPowerWorkflow.php @@ -379,10 +379,12 @@ final class CloudVpcPowerWorkflow $state['phase'] = 'paused'; $state['error_code'] = $code; self::release($operation, $state); - $root->state = 'degraded'; - $root->sync_state = 'waiting'; - $root->last_error_code = $code; - $root->save(); + if (($state['config_confirmed'] ?? false) !== true) { + $root->state = 'degraded'; + $root->sync_state = 'waiting'; + $root->last_error_code = $code; + $root->save(); + } } /** Return true only when a stopped guest may enter the existing apply lane. */ diff --git a/web/app/Services/Cloud/CloudVpcService.php b/web/app/Services/Cloud/CloudVpcService.php index 15e97004..60d3b04a 100644 --- a/web/app/Services/Cloud/CloudVpcService.php +++ b/web/app/Services/Cloud/CloudVpcService.php @@ -948,16 +948,12 @@ final class CloudVpcService if ($locked === null) { throw new CloudError('VPC 不存在', 404); } - $runtimeRetryableSync = in_array( + $configurationRetryableSync = in_array( (string) $locked->sync_state, ['waiting', 'uncertain'], true - ) || ((string) $locked->sync_state === 'applied' - && in_array((string) ($locked->last_error_code ?? ''), [ - 'vpc_private_guest_shutdown_pending', - 'vpc_private_guest_stopped', - ], true)); - $runtimeObservationPending = $allowDeferredRetry + ); + $configurationObservationPending = $allowDeferredRetry && (string) $locked->state === 'degraded' - && $runtimeRetryableSync + && $configurationRetryableSync && (int) $locked->desired_revision === (int) $locked->observed_revision && self::digestMatches( (string) $locked->desired_digest, @@ -965,7 +961,8 @@ final class CloudVpcService ); $operation = CloudVpcOperation::where('vpc_id', $locked->id) ->where(function ($query) use ( - $allowDeferredRetry, $allowFailedRetry, $runtimeObservationPending, $locked + $allowDeferredRetry, $allowFailedRetry, + $configurationObservationPending, $locked ): void { $query->whereIn('status', $allowDeferredRetry ? ['queued', 'running', 'uncertain', 'waiting_observed'] @@ -994,13 +991,13 @@ final class CloudVpcService ->where('desired_revision', (int) $locked->desired_revision); }); - if ($runtimeObservationPending) { - // Member removal may already be durably committed - // while a surviving VM still lacks exact guest - // evidence. Re-run only this root's current, - // idempotent target until runtime proof catches up. - $query->orWhere(function ($runtime) use ($locked): void { - $runtime->where('status', 'succeeded') + if ($configurationObservationPending) { + // A succeeded operation may need another exact host + // configuration readback after a later observation + // became uncertain. Guest runtime health alone never + // reopens the immutable apply operation. + $query->orWhere(function ($configuration) use ($locked): void { + $configuration->where('status', 'succeeded') ->where('kind', '!=', 'vpc_delete') ->where('evidence_version', '>=', self::OBSERVATION_EVIDENCE_VERSION) @@ -1042,10 +1039,10 @@ final class CloudVpcService return null; } $now = time(); - // Runtime-only refreshes intentionally keep a completed operation - // terminal while borrowing its lease. The lease, rather than the - // status string, is therefore the concurrency boundary for both - // ordinary applies and background observation refreshes. + // Configuration readback refreshes intentionally keep a completed + // operation terminal while borrowing its lease. The lease, rather + // than the status string, is the concurrency boundary for both + // ordinary applies and exact observation refreshes. if ((int) $operation->lease_until > $now) { return null; } @@ -1079,10 +1076,10 @@ final class CloudVpcService $locked->save(); return null; } - $runtimeProofRefresh = (string) $operation->status === 'succeeded' + $configurationProofRefresh = (string) $operation->status === 'succeeded' && (int) ($operation->evidence_version ?? 0) >= self::OBSERVATION_EVIDENCE_VERSION; - if (!$runtimeProofRefresh) { + if (!$configurationProofRefresh) { $operation->status = 'running'; $operation->finished_at = null; } @@ -1091,12 +1088,12 @@ final class CloudVpcService $operation->attempts = (int) $operation->attempts + 1; $operation->updated_at = $now; $operation->save(); - return [$operation, $payload, $runtimeProofRefresh, $previousOutcomePending]; + return [$operation, $payload, $configurationProofRefresh, $previousOutcomePending]; }, 3); if ($claim === null) { return self::show($vpcKey, $actor); } - [$operation, $payload, $runtimeProofRefresh, $previousOutcomePending] = $claim; + [$operation, $payload, $configurationProofRefresh, $previousOutcomePending] = $claim; $leaseToken = (string) $operation->lease_token; // Only the explicit user reconcile route may transfer an exact, // childless retained Engine root for this immutable target. Keep the @@ -1171,7 +1168,7 @@ final class CloudVpcService $connection = (new CloudVpc())->getConnection(); $connection->transaction(function () use ( $operation, $leaseToken, $vpc, $status, $error, $now, - $runtimeProofRefresh + $configurationProofRefresh ): void { // Keep the lock order identical to every mutator: VPC root // first, then its operation row. This also prevents an old @@ -1181,14 +1178,14 @@ final class CloudVpcService return; } $row = CloudVpcOperation::where('operation_id', (string) $operation->operation_id) - ->where('status', $runtimeProofRefresh ? 'succeeded' : 'running') + ->where('status', $configurationProofRefresh ? 'succeeded' : 'running') ->where('lease_token', $leaseToken)->lockForUpdate()->first(); if ($row === null) { return; } - if ($runtimeProofRefresh) { - // A runtime-only poll must not erase the last successful - // configuration proof when transport is temporarily + if ($configurationProofRefresh) { + // A configuration readback refresh must not erase the last + // successful proof when transport is temporarily // unavailable. Release the lease and retry later. $row->lease_token = null; $row->lease_until = 0; @@ -1681,6 +1678,37 @@ final class CloudVpcService $expectedVpcCidr = null; $desiredRoutes = []; $desiredContractValid = true; + $desiredHostClosure = null; + $normalizeHostClosure = static function ($rows): ?array { + if (!is_array($rows) || !array_is_list($rows)) { + return null; + } + $closure = []; + foreach ($rows as $host) { + if (!is_array($host) + || !is_string($host['host_id'] ?? null) + || preg_match('/^[1-9][0-9]*$/D', $host['host_id']) !== 1 + || isset($closure[$host['host_id']]) + || !is_array($host['members'] ?? null) + || !array_is_list($host['members'])) { + return null; + } + $members = []; + foreach ($host['members'] as $memberId) { + if (!is_string($memberId) + || preg_match(self::KEY_PATTERN, $memberId) !== 1 + || isset($members[$memberId])) { + return null; + } + $members[$memberId] = true; + } + $memberIds = array_keys($members); + sort($memberIds, SORT_STRING); + $closure[$host['host_id']] = $memberIds; + } + ksort($closure, SORT_STRING); + return $closure; + }; try { $desired = self::desiredDocument($vpc); $expectedVpcCidr = self::cidr( @@ -1709,6 +1737,7 @@ final class CloudVpcService $expectedDestinations[] = (string) $member['private_ip_cidr']; } } + $desiredHostClosure = $normalizeHostClosure($desired['hosts'] ?? null); } catch (\Throwable) { // A malformed desired ledger is itself a closed gate. $desiredContractValid = false; @@ -1717,6 +1746,7 @@ final class CloudVpcService $expectedDestinations = []; $expectedVpcCidr = null; $desiredRoutes = []; + $desiredHostClosure = null; } $expectedDestinations = array_values(array_unique(array_filter( $expectedDestinations, @@ -1997,6 +2027,40 @@ final class CloudVpcService } $liveRequired = $required->filter(static fn ($row): bool => (string) $row->state !== 'deleting'); + $expectedLiveHostIds = array_map( + 'strval', array_keys($expectedMembersByHost) + ); + $liveRequiredHostIds = $liveRequired->keys()->map( + static fn ($hostId): string => (string) $hostId + )->values()->all(); + $requiredHostIds = $required->keys()->map( + static fn ($hostId): string => (string) $hostId + )->values()->all(); + sort($expectedLiveHostIds, SORT_STRING); + sort($liveRequiredHostIds, SORT_STRING); + sort($requiredHostIds, SORT_STRING); + $desiredHostIds = is_array($desiredHostClosure) + ? array_map('strval', array_keys($desiredHostClosure)) : []; + sort($desiredHostIds, SORT_STRING); + $expectedMemberClosure = []; + foreach ($expectedMembersByHost as $hostId => $members) { + $memberIds = array_keys($members); + sort($memberIds, SORT_STRING); + $expectedMemberClosure[(string) $hostId] = $memberIds; + } + ksort($expectedMemberClosure, SORT_STRING); + $hostClosureExact = $desiredContractValid + && is_array($desiredHostClosure) + && $desiredHostIds === $requiredHostIds + && $expectedLiveHostIds === $liveRequiredHostIds; + if ($hostClosureExact) { + foreach ($expectedMemberClosure as $hostId => $memberIds) { + if (($desiredHostClosure[$hostId] ?? null) !== $memberIds) { + $hostClosureExact = false; + break; + } + } + } // A Fabric or host control-plane digest cannot prove that a // deleting private interface/address is gone. The engine reaches // an exact host observation only after consuming every durable @@ -2026,6 +2090,10 @@ final class CloudVpcService // inexact merely because both appear in the same operation. $allRequiredHostsExact = $required->count() > 0; $allRequiredHostsConfigExact = $required->count() > 0; + if (!$hostClosureExact) { + $allRequiredHostsExact = false; + $allRequiredHostsConfigExact = false; + } $allRemovalProof = true; $hasRemovalTarget = false; $currentConfigExactHostIds = []; @@ -2175,8 +2243,8 @@ final class CloudVpcService } elseif (!$deleting) { $hostError = is_string($evidence['last_error_code'] ?? null) ? (string) $evidence['last_error_code'] : null; - $deployment->state = $active ? 'active' : 'degraded'; - $deployment->last_error_code = $active ? null + $deployment->state = $configActive ? 'active' : 'degraded'; + $deployment->last_error_code = $configActive ? null : ($hostError ?? 'vpc_host_observation_mismatch'); } else { $deployment->last_error_code = $removalActive @@ -2184,7 +2252,7 @@ final class CloudVpcService : ($evidence['last_error_code'] ?? 'vpc_host_removal_unverified'); } $deployment->updated_at = time(); - if ($active || $removalActive) { + if ($configActive || $removalActive) { $deployment->last_success_at = time(); } else { $deployment->last_failure_at = time(); @@ -2373,6 +2441,7 @@ final class CloudVpcService && !$pendingChildTombstone; $configurationComplete = $allRequiredHostsConfigExact && $allRemovalProof && $liveRequired->count() > 0 + && $allExpectedMembers !== [] && !$pendingChildTombstone; $removalOnlyComplete = $hasRemovalTarget && $allRemovalProof && $allRequiredHostsExact && $liveRequired->count() === 0 @@ -2389,7 +2458,7 @@ final class CloudVpcService && $allRequiredHostsConfigExact && $allRemovalProof && !$pendingChildTombstone; // Once the detach mutation has advanced the root to this exact - // revision, later runtime-only retries must not reopen or repeat + // revision, later readback retries must not reopen or repeat // the already released member/IP tombstone. They keep the same // operation terminal while retrying guest evidence for siblings. $memberDetachPreviouslyCommitted = @@ -2414,36 +2483,6 @@ final class CloudVpcService // Derive it solely from the per-host closed set; mixed reasons // intentionally collapse to the generic control-plane code. $deferredError = self::singleDeferredEvidenceError($hostEvidence); - $hasUnresolvedMemberEvidence = false; - $hasSuspendedMemberEvidence = false; - $hasStoppingMemberEvidence = false; - $hasStoppedMemberEvidence = false; - foreach ($allExpectedMembers as $memberId => $_expectedMember) { - $runtimeEvidence = $memberGuestEvidence[(string) $memberId] ?? null; - $runtimeState = is_array($runtimeEvidence) - ? (string) ($runtimeEvidence['state'] ?? '') : ''; - if (!in_array( - $runtimeState, ['active', 'suspended', 'stopping', 'stopped'], true - )) { - $hasUnresolvedMemberEvidence = true; - } elseif ($runtimeState === 'suspended') { - $hasSuspendedMemberEvidence = true; - } elseif ($runtimeState === 'stopping') { - $hasStoppingMemberEvidence = true; - } elseif ($runtimeState === 'stopped') { - $hasStoppedMemberEvidence = true; - } - } - $runtimeObservationPending = $operationSucceeded - && $configurationComplete - && $liveRequired->count() > 0 && !$allActive - && ($hasUnresolvedMemberEvidence || $hasStoppingMemberEvidence - || $hasStoppedMemberEvidence); - $intentionalRuntimeSuspended = $operationSucceeded - && $configurationComplete && !$allActive - && !$hasUnresolvedMemberEvidence && !$hasStoppingMemberEvidence - && !$hasStoppedMemberEvidence - && $hasSuspendedMemberEvidence; $configurationObservationUncertain = $operationPreviouslySucceeded && !$configurationComplete && $liveRequired->count() > 0; // A no-members Fabric gate is terminal only after the database has @@ -2551,16 +2590,14 @@ final class CloudVpcService // a tenant data plane active. It may advance the exact desired // revision and finish the operation, but stays degraded/unusable // until a live member host passes the Fabric gate. - $vpc->state = $operationSucceeded && $allActive ? 'active' : 'degraded'; + $vpc->state = $operationSucceeded && $configurationComplete + ? 'active' : 'degraded'; $vpc->sync_state = $operationSucceeded - ? ($configurationObservationUncertain ? 'uncertain' - : ($runtimeObservationPending ? 'waiting' : 'applied')) + ? ($configurationObservationUncertain ? 'uncertain' : 'applied') : ($dataPlaneDeferred ? 'waiting' : ($terminalFailure ? 'failed' : 'uncertain')); $vpc->last_error_code = $operationSucceeded - ? (($runtimeObservationPending || $configurationObservationUncertain) - ? ($deferredError ?? 'vpc_data_plane_deferred') - : ($intentionalRuntimeSuspended - ? 'vpc_private_network_suspended' : null)) + ? ($configurationObservationUncertain + ? ($deferredError ?? 'vpc_data_plane_deferred') : null) : ($dataPlaneDeferred ? ($deferredError ?? 'vpc_data_plane_deferred') : ($terminalFailure ? $gateError : ($deferredError ?? 'vpc_observation_incomplete'))); @@ -3504,7 +3541,7 @@ final class CloudVpcService 'error_code' => $ok ? null : $state['reason_code']]; } - /** Persist the latest VM-side observation without advancing a VPC root. */ + /** Persist VM health; only current persistent-config drift invalidates the root proof. */ public static function recordPrivateObservation( int $instanceId, array $validation, string $operationId ): bool { @@ -3518,8 +3555,9 @@ final class CloudVpcService || !$schema->hasTable('cloud_vpcs')) { return false; } + $hasHostDeployments = $schema->hasTable('cloud_vpc_host_deployments'); return (bool) $connection->transaction(function () use ( - $instanceId, $validation, $operationId + $instanceId, $validation, $operationId, $hasHostDeployments ): bool { // Match the VPC -> member lock order used by control-plane // mutations. A lifecycle readback from an older desired revision @@ -3534,6 +3572,14 @@ final class CloudVpcService if ($vpc === null) { return false; } + // Keep the same root -> host -> member -> lease lock order used by + // recordObserved. A lifecycle receipt may invalidate one exact + // host projection, but must not deadlock with a VPC readback. + $deployment = $hasHostDeployments + ? CloudVpcHostDeployment::where('vpc_id', (int) $vpc->id) + ->where('host_id', (int) $probe->host_id) + ->lockForUpdate()->first() + : null; $member = CloudVpcMember::where('id', (int) $probe->id) ->whereNotIn('state', ['deleted'])->lockForUpdate()->first(); if ($member === null) { @@ -3563,7 +3609,12 @@ final class CloudVpcService $expectedDigest = self::safeDigest($state['desired_digest'] ?? null); $memberDigest = self::safeDigest($member->desired_digest); if ((int) $member->desired_revision !== $expectedRevision - || $memberDigest !== $expectedDigest) { + || $memberDigest !== $expectedDigest + || (int) $vpc->desired_revision !== $expectedRevision + || !self::digestMatches( + (string) $vpc->desired_digest, + (string) ($expectedDigest ?? '') + )) { return false; } if ((string) $vpc->state === 'deleting') { @@ -3611,6 +3662,38 @@ final class CloudVpcService && (string) ($state['state'] ?? '') === 'stopped'; $runtimeStopping = $ok && $desired !== 'removed' && (string) ($state['state'] ?? '') === 'stopping'; + // A structured, identity-bound lifecycle readback can disprove + // the durable host configuration independently of guest/QGA + // health. Missing observations do not revoke a prior receipt; + // current XML/config/seed or revision/digest drift does. + $structuredPersistentEvidence = $desired !== 'removed' + && ($state['required'] ?? false) === true + && is_string($state['vm_uuid'] ?? null) + && preg_match( + '/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/Di', + (string) $state['vm_uuid'] + ) === 1; + $expectedMac = self::privateMacForMember( + (string) $vpc->vpc_key, + (string) $member->member_key + ); + $persistentConfigExact = $structuredPersistentEvidence + && ($state['interface'] ?? null) === self::PRIVATE_INTERFACE + && is_string($expectedMac) + && is_string($state['private_mac'] ?? null) + && hash_equals($expectedMac, strtolower((string) $state['private_mac'])) + && (string) ($state['private_ip_cidr'] ?? '') + === (string) $member->private_ip . '/32' + && ($state['xml_verified'] ?? false) === true + && ($state['config_verified'] ?? false) === true + && ($state['seed_verified'] ?? false) === true + && (int) ($state['observed_revision'] ?? 0) === $expectedRevision + && self::digestMatches( + (string) ($expectedDigest ?? ''), + (string) ($state['observed_digest'] ?? '') + ); + $persistentConfigMismatch = !$ok + && $structuredPersistentEvidence && !$persistentConfigExact; // Mirror the member outcome into its lease row. A private-IP // state left at `deleting` or `active` after readback would make // the next expectation disagree with the member ledger. @@ -3650,103 +3733,42 @@ final class CloudVpcService $private->last_error_code = $member->last_error_code; $private->updated_at = time(); $private->save(); - self::refreshVpcRuntimeAggregate($vpc, (int) $member->host_id); - return true; - }, 3); - } - - /** Refresh host/root runtime state without changing exact config proof. */ - private static function refreshVpcRuntimeAggregate(CloudVpc $vpc, int $hostId): void - { - $now = time(); - $host = CloudVpcHostDeployment::where('vpc_id', $vpc->id) - ->where('host_id', $hostId)->lockForUpdate()->first(); - if ($host !== null && (string) $host->state !== 'deleting' - && (string) $host->state !== 'deleted') { - $hostMembers = CloudVpcMember::where('vpc_id', $vpc->id) - ->where('host_id', $hostId) - ->whereNotIn('state', ['deleting', 'deleted'])->get(); - $hostReady = !$hostMembers->isEmpty() - && $hostMembers->every(static fn ($row): bool => - (string) $row->state === 'active'); - $hostError = null; - foreach ($hostMembers as $hostMember) { - if ((string) $hostMember->state === 'active') { - continue; - } - $hostError = self::safeErrorCode( - (string) ($hostMember->last_error_code ?? '') - ) ?? 'vpc_private_observation_missing'; - break; - } - $host->state = $hostReady ? 'active' : 'degraded'; - $host->last_error_code = $hostReady ? null : $hostError; - $host->updated_at = $now; - if ($hostReady) { - $host->last_success_at = $now; - } else { - $host->last_failure_at = $now; - } - $host->save(); - } - - $members = CloudVpcMember::where('vpc_id', $vpc->id) - ->whereNotIn('state', ['deleting', 'deleted'])->get(); - $memberIds = $members->pluck('id')->map( - static fn ($id): int => (int) $id - )->values()->all(); - $leases = CloudVpcPrivateIp::where('vpc_id', $vpc->id) - ->whereIn('member_id', $memberIds)->get()->keyBy('member_id'); - $runtimeReady = !$members->isEmpty(); - $rootError = null; - foreach ($members as $member) { - $lease = $leases->get((int) $member->id); - if ((string) $member->state === 'active' - && $lease !== null && (string) $lease->state === 'active') { - continue; - } - $runtimeReady = false; - $runtimeError = self::safeErrorCode( - (string) ($member->last_error_code ?? '') - ); - if ($runtimeError === null && $lease !== null) { - $runtimeError = self::safeErrorCode( - (string) ($lease->last_error_code ?? '') - ); - } - $rootError ??= self::safeErrorCode( - (string) ($runtimeError ?? '') - ) ?? 'vpc_private_observation_missing'; - } - $hostsReady = !CloudVpcHostDeployment::where('vpc_id', $vpc->id) - ->whereNotIn('state', ['active', 'deleted'])->exists(); - $runtimeReady = $runtimeReady && $hostsReady; - $configExact = (int) $vpc->desired_revision === (int) $vpc->observed_revision - && self::digestMatches( - (string) $vpc->desired_digest, - (string) $vpc->observed_digest - ); - if ($configExact && (string) $vpc->state !== 'deleting' - && (string) $vpc->state !== 'deleted') { - $vpc->state = $runtimeReady ? 'active' : 'degraded'; - if ($runtimeReady) { - $vpc->sync_state = 'applied'; - $vpc->last_error_code = null; - $vpc->last_success_at = $now; - } else { - // An intentional lifecycle link-down does not invalidate the - // shared host configuration receipt. Preserve an applied - // config state; other runtime gaps retain their waiting lane. - if ((string) $vpc->sync_state === 'applied') { - $vpc->sync_state = 'applied'; - } - $vpc->last_error_code = $rootError - ?? 'vpc_private_observation_missing'; + if ($persistentConfigMismatch && $deployment !== null + && (string) $deployment->state === 'active' + && (int) $deployment->desired_revision === $expectedRevision + && (int) $deployment->observed_revision === $expectedRevision + && self::digestMatches( + (string) ($expectedDigest ?? ''), + (string) $deployment->desired_digest + ) + && self::digestMatches( + (string) ($expectedDigest ?? ''), + (string) $deployment->observed_digest + ) + && (string) $deployment->last_operation_id + === (string) $vpc->last_operation_id + && (string) $vpc->state === 'active' + && (string) $vpc->sync_state === 'applied' + && (int) $vpc->observed_revision === $expectedRevision + && self::digestMatches( + (string) ($expectedDigest ?? ''), + (string) $vpc->observed_digest + )) { + $now = time(); + $deployment->state = 'degraded'; + $deployment->last_error_code = 'vpc_private_observation_mismatch'; + $deployment->last_failure_at = $now; + $deployment->updated_at = $now; + $deployment->save(); + $vpc->state = 'degraded'; + $vpc->sync_state = 'uncertain'; + $vpc->last_error_code = 'vpc_private_observation_mismatch'; $vpc->last_failure_at = $now; + $vpc->updated_at = $now; + $vpc->save(); } - $vpc->updated_at = $now; - $vpc->save(); - } + return true; + }, 3); } private static function safeDigest($value): ?string @@ -5037,7 +5059,8 @@ final class CloudVpcService $observedDigest = (string) ($vpc->observed_digest ?? ''); $hostRows = CloudVpcHostDeployment::where('vpc_id', $vpc->id) ->whereNotIn('state', ['deleted'])->get(); - $hostsReady = $hostRows->count() > 0; + $configurationHostsReady = $hostRows->count() > 0; + $runtimeReady = $configurationHostsReady; $pendingTombstone = CloudVpcHostDeployment::where('vpc_id', $vpc->id) ->where('state', 'deleting')->exists(); foreach ([ @@ -5053,7 +5076,8 @@ final class CloudVpcService } } if ($pendingTombstone) { - $hostsReady = false; + $configurationHostsReady = false; + $runtimeReady = false; } // A VPC projection is not usable while any live member points at an // instance that has left the active lifecycle state. This closes the @@ -5061,8 +5085,19 @@ final class CloudVpcService // matching root digest looking healthy to the tenant UI. $runtimeMembers = CloudVpcMember::where('vpc_id', $vpc->id) ->whereNotIn('state', ['deleted'])->get([ - 'id', 'instance_id', 'private_ip_id', 'state', + 'id', 'instance_id', 'host_id', 'private_ip_id', 'state', ]); + $memberHostIds = $runtimeMembers->pluck('host_id')->map( + static fn ($hostId): string => (string) $hostId + )->unique()->values()->all(); + $deploymentHostIds = $hostRows->pluck('host_id')->map( + static fn ($hostId): string => (string) $hostId + )->unique()->values()->all(); + sort($memberHostIds, SORT_STRING); + sort($deploymentHostIds, SORT_STRING); + if ($runtimeMembers->isEmpty() || $memberHostIds !== $deploymentHostIds) { + $configurationHostsReady = false; + } $memberInstances = $runtimeMembers->pluck('instance_id') ->map(static fn ($id): int => (int) $id) ->unique()->values()->all(); @@ -5091,7 +5126,7 @@ final class CloudVpcService || (string) ($instanceStates->get( (int) $runtimeMember->instance_id )?->network_status ?? '') !== 'active') { - $hostsReady = false; + $runtimeReady = false; break; } // Only a fresh, identity-bound running observation can support @@ -5101,7 +5136,7 @@ final class CloudVpcService if (!is_array($runtime) || ($runtime['state_fresh'] ?? false) !== true || (string) ($runtime['power_state'] ?? '') !== 'running') { - $hostsReady = false; + $runtimeReady = false; break; } } @@ -5112,13 +5147,15 @@ final class CloudVpcService || (int) $host->observed_revision !== (int) $vpc->desired_revision || !self::digestMatches((string) $host->desired_digest, $desiredDigest) || !self::digestMatches((string) $host->observed_digest, $desiredDigest)) { - $hostsReady = false; + $configurationHostsReady = false; break; } } + $runtimeReady = $runtimeReady && $configurationHostsReady; $rootReady = self::digestMatches($desiredDigest, $observedDigest); $currentOperation = null; $currentOperationReady = false; + $currentOperationConfigurationReady = false; $lastOperationId = (string) ($vpc->last_operation_id ?? ''); if (preg_match(self::KEY_PATTERN, $lastOperationId) === 1) { $currentOperation = CloudVpcOperation::where('vpc_id', $vpc->id) @@ -5129,11 +5166,20 @@ final class CloudVpcService && (string) $currentOperation->status === 'succeeded' && (int) $currentOperation->evidence_version >= self::OBSERVATION_EVIDENCE_VERSION; + $workflow = $currentOperation === null + ? null : CloudVpcPowerWorkflow::state($currentOperation); + $currentOperationConfigurationReady = $currentOperation !== null + && (int) $currentOperation->evidence_version + >= self::OBSERVATION_EVIDENCE_VERSION + && ($currentOperationReady + || ($workflow['config_confirmed'] ?? false) === true); } - $usable = (string) $vpc->state === 'active' + $configurationReady = (string) $vpc->state === 'active' && (string) $vpc->sync_state === 'applied' && (int) $vpc->desired_revision === (int) $vpc->observed_revision - && $rootReady && $hostsReady && $currentOperationReady; + && $rootReady && $configurationHostsReady + && $currentOperationConfigurationReady; + $usable = $configurationReady && $runtimeReady; $rawErrorCode = trim((string) ($vpc->last_error_code ?? '')); // setup_state is a read-only tenant projection. It also repairs the // presentation of legacy empty roots that were persisted as failed @@ -5221,6 +5267,10 @@ final class CloudVpcService 'sync_state' => (string) $vpc->sync_state, 'desired_revision' => (int) $vpc->desired_revision, 'observed_revision' => (int) $vpc->observed_revision, + // Configuration and aggregate guest runtime are separate public + // facts. A stopped or unverified guest may make `usable` false + // without reopening this exact host-configuration receipt. + 'configured' => $configurationReady, 'usable' => $usable, 'member_count' => $runtimeMembers->count(), 'setup_state' => $awaitingMembers ? 'awaiting_members' : null, diff --git a/web/app/Services/Cloud/CloudVpcWorkerService.php b/web/app/Services/Cloud/CloudVpcWorkerService.php index e6a5544f..b1176b1c 100644 --- a/web/app/Services/Cloud/CloudVpcWorkerService.php +++ b/web/app/Services/Cloud/CloudVpcWorkerService.php @@ -60,13 +60,13 @@ final class CloudVpcWorkerService 'cloud_vpc_operations.desired_revision') ->where('current_vpc.state', '!=', 'deleted'); }); - })->orWhere(function ($runtime) use ($now): void { - // Configuration may already be committed while one - // or more live guests are not yet observable. Keep - // the mutation terminal, but idempotently re-apply - // only the current root target until runtime proof - // is exact. - $runtime->where('status', 'succeeded') + })->orWhere(function ($configuration) use ($now): void { + // Refresh only a current root whose host + // configuration readback became uncertain after a + // successful apply. Stopped, suspended or + // unobservable guests remain member health and do + // not reopen this operation. + $configuration->where('status', 'succeeded') ->where('kind', '!=', 'vpc_delete') ->where('evidence_version', '>=', CloudVpcService::OBSERVATION_EVIDENCE_VERSION) @@ -86,21 +86,9 @@ final class CloudVpcWorkerService ->whereColumn('current_vpc.observed_digest', 'current_vpc.desired_digest') ->where('current_vpc.state', 'degraded') - ->where(static function ($runtimeState): void { - $runtimeState->whereIn( - 'current_vpc.sync_state', - ['waiting', 'uncertain'] - )->orWhere(static function ($stopped): void { - $stopped->where( - 'current_vpc.sync_state', 'applied' - )->whereIn( - 'current_vpc.last_error_code', [ - 'vpc_private_guest_shutdown_pending', - 'vpc_private_guest_stopped', - ] - ); - }); - }); + ->whereIn('current_vpc.sync_state', [ + 'waiting', 'uncertain', + ]); }); }); }) diff --git a/web/public/cloud/vpc.js b/web/public/cloud/vpc.js index 73ef64e2..8626bcc8 100644 --- a/web/public/cloud/vpc.js +++ b/web/public/cloud/vpc.js @@ -130,9 +130,16 @@ function projectionFieldKnown(root, field) { return Object.prototype.hasOwnProperty.call(root || {}, field); } +function configurationReady(root) { + if (projectionFieldKnown(root, 'configured')) return root?.configured === true; + // Compatibility for a rolling PHP/UI deployment. Older responses exposed + // only the stricter aggregate runtime signal. + return root?.usable === true; +} + function awaitingMembers(root) { const raw = String(root?.state || '').toLowerCase(); - if (raw === 'deleting' || root?.usable === true) return false; + if (raw === 'deleting' || configurationReady(root)) return false; const count = memberCount(root); if (String(root?.setup_state || '').toLowerCase() === 'awaiting_members' && (count === null || count === 0)) return true; @@ -156,7 +163,7 @@ function rootStatus(root) { // is failed or uncertain. Never reopen mutation controls while teardown // still owns the VPC. if (raw === 'deleting') return 'deleting'; - if (root?.usable === true) return 'active'; + if (configurationReady(root)) return 'active'; if (awaitingMembers(root)) return 'awaiting_members'; if (sync === 'waiting' || sync === 'waiting_observed') return 'waiting'; if (sync === 'uncertain' || raw === 'uncertain') return 'uncertain'; @@ -292,6 +299,7 @@ function normalizeRoot(value) { if (!value || typeof value !== 'object') return null; const setupStateKnown = Object.prototype.hasOwnProperty.call(value, 'setup_state'); const memberCountKnown = Object.prototype.hasOwnProperty.call(value, 'member_count'); + const configuredKnown = Object.prototype.hasOwnProperty.call(value, 'configured'); const count = value.member_count === null || value.member_count === undefined || value.member_count === '' ? null : Number(value.member_count); return { @@ -303,6 +311,8 @@ function normalizeRoot(value) { desired_revision: Number(value.desired_revision || 0), observed_revision: Number(value.observed_revision || 0), member_count: count !== null && Number.isInteger(count) && count >= 0 ? count : null, + configured: value.configured === true, + configured_known: configuredKnown, setup_state: value.setup_state ? String(value.setup_state) : '', setup_state_known: setupStateKnown, member_count_known: memberCountKnown, @@ -329,10 +339,14 @@ function normalizeDocument(value) { function needsPolling() { const fastStatuses = new Set(['applying', 'waiting', 'uncertain', 'degraded', 'deleting']); const workflow = powerWorkflow(); - return Boolean(state.vpcs.some(vpc => fastStatuses.has(rootStatus( - state.selected?.vpc?.vpc_key === vpc.vpc_key ? state.selected.vpc : vpc - ))) - || (state.selected && fastStatuses.has(rootStatus(state.selected.vpc))) + const selectedKey = state.selected?.vpc?.vpc_key; + const selectedPaused = workflow?.phase === 'paused'; + return Boolean(state.vpcs.some(vpc => { + const selected = selectedKey === vpc.vpc_key; + return (!selected || !selectedPaused) + && fastStatuses.has(rootStatus(selected ? state.selected.vpc : vpc)); + }) + || (state.selected && !selectedPaused && fastStatuses.has(rootStatus(state.selected.vpc))) || (workflow && !['paused', 'completed'].includes(workflow.phase))); } @@ -495,7 +509,10 @@ function renderList() { meta.append(element('small', '', count === null ? '成员数量待读取' : `${count} 个成员`), element('small', '', paused ? '自动流程已暂停,请核对 / 重试' : (status === 'awaiting_members' ? '下一步:添加实例' - : (displayRoot.usable === true ? '宿主机回读已确认' : '正在核对私网配置')))); + : (configurationReady(displayRoot) + ? (displayRoot.usable === true + ? '配置与成员运行状态均已确认' : '配置已确认,成员健康待处理') + : '正在核对私网配置')))); row.append(main, meta); return row; }); @@ -602,8 +619,10 @@ function renderDetail() { : errorLabel(root.last_error_code); overviewHeading.append(statusPill(paused ? 'paused' : status), element('span', 'vpc-readback-note', paused ? (power.error || power.description) - : (root.usable === true - ? 'WireGuard、私网路由和实例网卡均已回读确认。' + : (configurationReady(root) + ? (root.usable === true + ? 'WireGuard、私网路由、实例网卡和成员运行状态均已确认。' + : 'WireGuard、私网路由和实例网卡配置已确认;请在成员列表查看停机、暂停或来宾核验状态。') : (status === 'deleting' ? '正在清理所有宿主机私网对象;精确回读完成前不会释放 VPC CIDR。' : (status === 'awaiting_members' @@ -659,6 +678,7 @@ function renderDetail() { const diagnosticFacts = element('dl', 'vpc-facts vpc-diagnostic-facts'); diagnosticFacts.append(field('目标 revision', root.desired_revision || 0), field('已观测 revision', root.observed_revision || 0), + field('配置状态', configurationReady(root) ? '已应用' : '待回读'), field('同步状态', safeText(root.sync_state)), field('最近错误代码', root.last_error_code || '无')); diagnostics.body.append(diagnosticFacts, renderOperations(doc)); diff --git a/web/tests/CloudVpcControlPlaneContractTest.php b/web/tests/CloudVpcControlPlaneContractTest.php index 76e904ed..16a2daca 100644 --- a/web/tests/CloudVpcControlPlaneContractTest.php +++ b/web/tests/CloudVpcControlPlaneContractTest.php @@ -268,6 +268,8 @@ $assert($missingRemovalBlock !== '' $assert(str_contains($service, 'canViewInfrastructure') && str_contains($service, 'publicRoot($vpc, $includeHostDetails)') && str_contains($service, 'digestMatches($desiredDigest, $observedDigest)') + && str_contains($service, "'configured' => \$configurationReady") + && !str_contains($service, "'configuration_ready' =>") && str_contains($service, "'member_count' => \$runtimeMembers->count()") && str_contains($service, "'setup_state' => \$awaitingMembers ? 'awaiting_members' : null") && str_contains($service, "['deleting', 'deleted']") @@ -430,10 +432,11 @@ $assert(str_contains($vpcWorkerService, "'waiting_observed'") && str_contains($vpcWorkerService, 'current_vpc.last_operation_id') && str_contains($vpcWorkerService, "where('kind', '!=', 'vpc_delete')") && str_contains($vpcWorkerService, 'current_vpc.sync_state') - && str_contains($vpcWorkerService, 'vpc_private_guest_shutdown_pending') + && !str_contains($vpcWorkerService, 'vpc_private_guest_shutdown_pending') + && !str_contains($vpcWorkerService, 'vpc_private_guest_stopped') && str_contains($vpcWorkerService, 'OBSERVATION_EVIDENCE_VERSION') && str_contains($vpcWorkerService, 'CloudVpcService::reconcile($vpcKey, $actor, $allowDeferredRetry)'), - 'VPC worker must retry waiting or legacy current evidence through its independent apply lane.'); + 'VPC worker must retry configuration uncertainty without polling guest-only health.'); $assert(str_contains($routes, "'/vpcs'") && str_contains($routes, "'/vpcs/{vpc_key:[0-9a-f]{32}}/reconcile'") diff --git a/web/tests/CloudVpcPowerWorkflowTest.php b/web/tests/CloudVpcPowerWorkflowTest.php index 50251e13..b45ff772 100644 --- a/web/tests/CloudVpcPowerWorkflowTest.php +++ b/web/tests/CloudVpcPowerWorkflowTest.php @@ -519,9 +519,22 @@ $advance($op); $state = Workflow::state($op->fresh()); $state['start_deadline'] = time() - 1; $op->power_workflow_json = json_encode($state); $op->save(); +$rootBeforePause = CloudVpc::find($op->vpc_id); +$rootBeforePause->state = 'degraded'; +$rootBeforePause->sync_state = 'uncertain'; +$rootBeforePause->last_error_code = 'vpc_host_configuration_mismatch'; +$rootBeforePause->save(); +$rootProjectionBeforePause = [ + (string) $rootBeforePause->state, + (string) $rootBeforePause->sync_state, + (string) $rootBeforePause->last_error_code, +]; $advance($op); +$rootAfterPause = CloudVpc::find($op->vpc_id); $assert($phase($op) === 'paused' - && Workflow::state($op->fresh())['error_code'] === 'vpc_power_start_timeout', + && Workflow::state($op->fresh())['error_code'] === 'vpc_power_start_timeout' + && [(string) $rootAfterPause->state, (string) $rootAfterPause->sync_state, + (string) $rootAfterPause->last_error_code] === $rootProjectionBeforePause, 'Accepted start without running readback did not stop at its fixed deadline.'); CloudEngineClient::$startChangesPower = true; @@ -749,27 +762,39 @@ $assert($phase($op) === 'completed' && $op->fresh()->status === 'succeeded' 'Service/worker did not apply and restore a running member.'); $root = CloudVpc::find($op->vpc_id); $member = CloudVpcMember::where('instance_id', 121000)->first(); -$assert($root->last_error_code === 'vpc_private_guest_stopped' - && $member->state === 'stopped', - 'Command acceptance incorrectly promoted the old stopped guest proof.'); +$assert($root->state === 'active' && $root->sync_state === 'applied' + && $root->last_error_code === null + && $member->state === 'stopped' + && $member->last_error_code === 'vpc_private_guest_stopped', + 'Guest-only stopped evidence leaked into the applied root configuration.'); $commands = count(CloudEngineClient::$commands); $applies = CloudEngineClient::$applies; $attempts = (int) $op->fresh()->attempts; -// A completed power workflow must still receive the next exact engine -// observation. Exercise the real top-level host list plus observed envelope. -$tick($op); +// A completed, config-exact workflow is terminal for the apply worker. A +// later independent guest-health receipt may update only member/IP runtime. +Capsule::table('cloud_vpc_operations')->where('id', '<>', $op->id) + ->update(['status' => 'superseded', 'lease_until' => 0]); +Capsule::table('cloud_vpc_operations')->where('id', $op->id) + ->update(['updated_at' => time() - 31, 'lease_until' => 0]); +$assert((new CloudVpcWorkerService())->tick() === false + && (int) $op->fresh()->attempts === $attempts + && CloudEngineClient::$applies === $applies + && count(CloudEngineClient::$commands) === $commands, + 'The worker replayed a succeeded operation solely for guest health.'); $root->refresh(); $member->refresh(); $private = \App\Models\CloudVpcPrivateIp::find($member->private_ip_id); $assert($phase($op) === 'completed' && $op->fresh()->status === 'succeeded' - && (int) $op->fresh()->attempts === $attempts + 1 + && (int) $op->fresh()->attempts === $attempts && $root->state === 'active' && $root->sync_state === 'applied' && $root->last_error_code === null && (int) $root->observed_revision === (int) $root->desired_revision - && $member->state === 'active' && $member->last_error_code === null - && $private->state === 'active' && $private->last_error_code === null - && CloudEngineClient::$applies === $applies + 1 + && $member->state === 'stopped' + && $member->last_error_code === 'vpc_private_guest_stopped' + && $private->state === 'stopped' + && $private->last_error_code === 'vpc_private_guest_stopped' + && CloudEngineClient::$applies === $applies && count(CloudEngineClient::$commands) === $commands, - 'Completed automatic start did not refresh the member/IP/root from fresh guest proof.'); + 'A guest-only stopped state was not retained without replaying apply.'); CloudVpcService::detachMember($root->vpc_key, $member->member_key, $actor, [ 'request_key' => 'auto-detach-1210', 'auto_power' => true, ]); diff --git a/web/tests/CloudVpcTombstoneConvergenceTest.php b/web/tests/CloudVpcTombstoneConvergenceTest.php index d390f6d5..472a853d 100644 --- a/web/tests/CloudVpcTombstoneConvergenceTest.php +++ b/web/tests/CloudVpcTombstoneConvergenceTest.php @@ -1304,10 +1304,9 @@ $assert(Capsule::table('cloud_vpc_members')->where('id', 117)->count() === 0 ->value('status') === 'succeeded', 'Refreshing the stale historical removal proof did not unblock convergence.'); -// A running host/libvirt configuration is not usable until the guest itself -// proves the exact address and routes. Preserve one actionable restart reason -// through the host, member and root projections while configuration operation -// completion remains terminal. +// A running host/libvirt configuration is applied independently from guest +// health. Preserve one actionable restart reason on the member/lease while the +// host, root and operation remain terminal for the exact configuration. $vpcKey14 = str_repeat('e', 32); $digest14 = str_repeat('7', 64); $operation14 = str_repeat('e', 31) . '0'; @@ -1340,8 +1339,9 @@ CloudVpcService::recordObserved( ); $rootProjection14 = $publicRootMethod->invoke(null, CloudVpc::find(14)); $assert(Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 14) - ->where('host_id', 140)->value('last_error_code') - === 'vpc_private_guest_restart_required' + ->where('host_id', 140)->value('state') === 'active' + && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 14) + ->where('host_id', 140)->value('last_error_code') === null && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation14) ->value('status') === 'succeeded' && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation14) @@ -1351,7 +1351,12 @@ $assert(Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 14) && Capsule::table('cloud_vpc_members')->where('id', 119) ->value('last_error_code') === 'vpc_private_guest_restart_required' && Capsule::table('cloud_vpcs')->where('id', 14) - ->value('last_error_code') === 'vpc_private_guest_restart_required' + ->value('state') === 'active' + && Capsule::table('cloud_vpcs')->where('id', 14) + ->value('sync_state') === 'applied' + && Capsule::table('cloud_vpcs')->where('id', 14) + ->value('last_error_code') === null + && ($rootProjection14['configured'] ?? false) === true && ($rootProjection14['usable'] ?? true) === false, 'A config-complete guest restart was not retained as non-usable runtime state.'); @@ -1365,17 +1370,16 @@ $deferred14['hosts']['140'] = $host14; CloudVpcService::recordObserved($vpcKey14, 28, $digest14, $deferred14, $operation14); $deniedProjection14 = $publicRootMethod->invoke(null, CloudVpc::find(14)); $assert(Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 14) - ->where('host_id', 140)->value('last_error_code') === 'vpc_private_guest_probe_permission_denied' + ->where('host_id', 140)->value('last_error_code') === null && Capsule::table('cloud_vpc_members')->where('id', 119) ->value('last_error_code') === 'vpc_private_guest_probe_permission_denied' && Capsule::table('cloud_vpcs')->where('id', 14) - ->value('last_error_code') === 'vpc_private_guest_probe_permission_denied' + ->value('last_error_code') === null && ($deniedProjection14['usable'] ?? true) === false, 'A guest permission denial was lost or marked usable.'); -// Each deployment must retain its own host item. A stale loop variable used -// to copy the final host's error onto every prior host. Mixed typed reasons -// remain per-host and collapse to the generic operation/root code. +// Mixed guest reasons remain isolated on their member rows. They do not leak +// into either exact host projection or the applied root configuration. $vpcKey15 = str_repeat('f', 32); $digest15 = str_repeat('8', 64); $operation15 = str_repeat('f', 31) . '0'; @@ -1429,6 +1433,11 @@ $host15a['private_dataplane_verified'] = false; $host15b['private_dataplane_verified'] = false; $host15a['member_nics'][0]['guest_network_verified'] = false; $host15b['member_nics'][0]['guest_network_verified'] = false; +$host15a['member_nics'][0]['restart_required'] = true; +$host15a['member_nics'][0]['guest_reason_code'] = + 'vpc_private_guest_restart_required'; +$host15b['member_nics'][0]['guest_reason_code'] = + 'vpc_private_guest_agent_unavailable'; $host15a['last_error_code'] = 'vpc_private_guest_restart_required'; $host15b['last_error_code'] = 'vpc_private_guest_agent_unavailable'; $deferred15 = $observed(30, $digest15, [ @@ -1437,22 +1446,49 @@ $deferred15 = $observed(30, $digest15, [ $deferred15['state'] = 'applying'; $deferred15['next_stage_allowed'] = false; $deferred15['private_dataplane_verified'] = false; +Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 15) + ->where('host_id', 151)->delete(); +$missingDeployment15 = $deferred15; +$missingDeployment15['hosts'] = ['150' => $host15a]; +CloudVpcService::recordObserved( + $vpcKey15, 30, $digest15, $missingDeployment15, $operation15 +); +$assert(Capsule::table('cloud_vpc_operations')->where('operation_id', $operation15) + ->value('status') !== 'succeeded' + && Capsule::table('cloud_vpcs')->where('id', 15)->value('state') !== 'active', + 'A partial deployment/observed host subset completed the configuration.'); +$seedHost(15, 151, 'applying', 30, $digest15, $operation15); CloudVpcService::recordObserved( $vpcKey15, 30, $digest15, $deferred15, $operation15 ); $assert(Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 15) - ->where('host_id', 150)->value('last_error_code') - === 'vpc_private_guest_restart_required' + ->where('host_id', 150)->value('state') === 'active' && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 15) - ->where('host_id', 151)->value('last_error_code') - === 'vpc_private_guest_agent_unavailable' + ->where('host_id', 151)->value('state') === 'active' + && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 15) + ->whereIn('host_id', [150, 151])->whereNotNull('last_error_code')->count() === 0 + && Capsule::table('cloud_vpc_members')->where('id', 120) + ->value('last_error_code') === 'vpc_private_guest_restart_required' + && Capsule::table('cloud_vpc_members')->where('id', 121) + ->value('last_error_code') === 'vpc_private_guest_agent_unavailable' && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation15) ->value('status') === 'succeeded' && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation15) ->value('error_code') === null && Capsule::table('cloud_vpcs')->where('id', 15) - ->value('last_error_code') === 'vpc_data_plane_deferred', - 'Multi-host guest errors were cross-contaminated or unsafely collapsed.'); + ->value('state') === 'active' + && Capsule::table('cloud_vpcs')->where('id', 15) + ->value('sync_state') === 'applied' + && Capsule::table('cloud_vpcs')->where('id', 15) + ->value('last_error_code') === null, + 'Multi-host guest errors leaked out of member-scoped health.'); +$configuredProjection15 = $publicRootMethod->invoke(null, CloudVpc::find(15)); +Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 15) + ->where('host_id', 151)->delete(); +$missingProjection15 = $publicRootMethod->invoke(null, CloudVpc::find(15)); +$assert(($configuredProjection15['configured'] ?? false) === true + && ($missingProjection15['configured'] ?? true) === false, + 'The public configured projection ignored a live member host missing from deployment rows.'); // A pre-upgrade succeeded receipt has no guest-evidence contract version. It // must fail closed immediately; the worker contract separately reclaims only @@ -1486,8 +1522,8 @@ $assert(($rootProjection16['usable'] ?? true) === false, // Retiring member A on a host with live sibling B must converge from exact // current configuration even when B's guest probe is unsupported. The proof -// releases only A/IP; B, the host and the root remain fail-closed for runtime -// usability until B supplies exact guest evidence. +// releases only A/IP; B remains fail-closed for runtime usability while the +// host and root retain their exact applied configuration projection. $vpcKey17 = str_repeat('1', 31) . '7'; $digest17 = str_repeat('a', 63) . '7'; $operation17 = str_repeat('2', 31) . '7'; @@ -1539,23 +1575,26 @@ $assert(Capsule::table('cloud_vpc_members')->where('id', 123)->count() === 0 && Capsule::table('cloud_vpc_members')->where('id', 124)->count() === 1 && Capsule::table('cloud_vpc_private_ips')->where('id', 224)->count() === 1 && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 17) - ->where('host_id', 170)->value('state') === 'degraded' + ->where('host_id', 170)->value('state') === 'active' && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation17) ->value('status') === 'succeeded' && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation17) ->value('error_code') === null && Capsule::table('cloud_vpcs')->where('id', 17) - ->value('state') === 'degraded' + ->value('state') === 'active' && Capsule::table('cloud_vpcs')->where('id', 17) - ->value('sync_state') === 'waiting' + ->value('sync_state') === 'applied' && Capsule::table('cloud_vpcs')->where('id', 17) + ->value('last_error_code') === null + && Capsule::table('cloud_vpc_members')->where('id', 124) ->value('last_error_code') === 'vpc_private_guest_probe_unsupported' + && ($rootProjection17['configured'] ?? false) === true && ($rootProjection17['usable'] ?? true) === false, 'Config-exact detach did not release only A while B guest readiness stayed closed.'); -// No new mutation is required once B becomes observable. The worker reuses -// the current, idempotent detach operation and the exact guest receipt opens -// only the runtime gate; the already released A/IP rows stay absent. +// No new mutation is required once B becomes observable. A later guest-health +// receipt may use the same immutable operation identity without reopening the +// applied configuration; the already released A/IP rows stay absent. $readyHost17 = $activeHost( $vpcKey17, '10.37.0.0/24', 170, 34, $digest17, $liveKey17, $liveUuid17, '10.37.0.11' @@ -1586,8 +1625,7 @@ $assert(Capsule::table('cloud_vpc_members')->where('id', 123)->count() === 0 // Runtime evidence is member-scoped. A running/exact A remains usable when B // is stopped after the same host configuration has completed. The operation -// is terminal for configuration, while the same ID remains the worker's -// idempotent runtime-reconcile target for B. +// is terminal for configuration and is not left as a worker retry target. $vpcKey19 = str_repeat('9', 31) . 'a'; $digest19 = str_repeat('c', 63) . '9'; $operation19 = str_repeat('a', 31) . '9'; @@ -1652,13 +1690,33 @@ $assert(Capsule::table('cloud_vpc_operations')->where('operation_id', $operation ->value('state') === 'degraded' && Capsule::table('cloud_vpc_members')->where('id', 127) ->value('last_error_code') === 'vpc_private_guest_restart_required' + && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 19) + ->where('host_id', 190)->value('state') === 'active' + && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 19) + ->where('host_id', 190)->value('last_error_code') === null + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('state') === 'active' + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('sync_state') === 'applied' + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('last_error_code') === null && ($projection19a['state'] ?? null) === 'active' && ($projection19a['readback'] ?? null) === 'confirmed' && ($projection19b['reason_code'] ?? null) === 'vpc_private_guest_restart_required' + && ($rootProjection19['configured'] ?? false) === true && ($rootProjection19['usable'] ?? true) === false, 'A stopped sibling blocked an independently proven running member.'); +// Age every operation as if the daemon polled again. Guest-only health must +// not make a succeeded, config-exact operation eligible for another apply. +Capsule::table('cloud_vpc_operations')->where('operation_id', '<>', $operation19) + ->update(['status' => 'superseded', 'lease_until' => 0]); +Capsule::table('cloud_vpc_operations')->where('operation_id', $operation19) + ->update(['updated_at' => time() - 31, 'lease_until' => 0]); +$assert((new \App\Services\Cloud\CloudVpcWorkerService())->tick() === false, + 'A config-exact root with guest-only health remained an automatic retry target.'); + $ready19 = $host19; $ready19['state'] = 'active'; $ready19['private_dataplane_verified'] = true; @@ -1745,6 +1803,72 @@ $stoppedObservation19b = [ 'guest_network_readback' => 'stopped', 'guest_link_state' => null, 'reason_code' => null, 'observed_at' => time(), ]; + +// A current VM lifecycle receipt separates persistent host configuration from +// guest/QGA health. Guest-only failure stays on member/IP, while a positive +// XML/config/seed mismatch invalidates the host/root configuration projection. +$guestOnlyObservation19b = $stoppedObservation19b; +$guestOnlyObservation19b['state'] = 'active'; +$guestOnlyObservation19b['domain_running'] = true; +$guestOnlyObservation19b['guest_network_verified'] = false; +$guestOnlyObservation19b['guest_network_readback'] = 'unavailable'; +$guestOnlyObservation19b['guest_link_state'] = null; +$guestOnlyValidation19b = CloudVpcService::validatePrivateObservation( + $expectation19b, $guestOnlyObservation19b, + 'action_start_policy_active', $uuid19b +); +$assert(($guestOnlyValidation19b['ok'] ?? true) === false + && CloudVpcService::recordPrivateObservation( + 19002, $guestOnlyValidation19b, str_repeat('e', 31) . '9' + ) === true, + 'Guest-only lifecycle failure could not be persisted.'); +$guestOnlyRoot19 = $publicRootMethod->invoke(null, CloudVpc::find(19)); +$assert(Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 19) + ->where('host_id', 190)->value('state') === 'active' + && Capsule::table('cloud_vpcs')->where('id', 19)->value('state') === 'active' + && Capsule::table('cloud_vpcs')->where('id', 19)->value('sync_state') === 'applied' + && Capsule::table('cloud_vpc_members')->where('id', 127) + ->value('state') === 'uncertain' + && ($guestOnlyRoot19['configured'] ?? false) === true + && ($guestOnlyRoot19['usable'] ?? true) === false, + 'Guest-only lifecycle health revoked the exact configuration receipt.'); +CloudVpcService::recordObserved( + $vpcKey19, 38, $digest19, + $observed(38, $digest19, ['190' => $ready19]), + $operation19 +); + +$configDriftObservation19b = $guestOnlyObservation19b; +$configDriftObservation19b['xml_verified'] = false; +$configDriftValidation19b = CloudVpcService::validatePrivateObservation( + $expectation19b, $configDriftObservation19b, + 'action_start_policy_active', $uuid19b +); +$assert(($configDriftValidation19b['ok'] ?? true) === false + && CloudVpcService::recordPrivateObservation( + 19002, $configDriftValidation19b, str_repeat('f', 31) . '9' + ) === true, + 'Persistent lifecycle configuration drift could not be persisted.'); +$configDriftRoot19 = $publicRootMethod->invoke(null, CloudVpc::find(19)); +$assert(Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 19) + ->where('host_id', 190)->value('state') === 'degraded' + && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 19) + ->where('host_id', 190)->value('last_error_code') + === 'vpc_private_observation_mismatch' + && Capsule::table('cloud_vpcs')->where('id', 19)->value('state') === 'degraded' + && Capsule::table('cloud_vpcs')->where('id', 19)->value('sync_state') === 'uncertain' + && Capsule::table('cloud_vpcs')->where('id', 19)->value('last_error_code') + === 'vpc_private_observation_mismatch' + && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation19) + ->value('status') === 'succeeded' + && ($configDriftRoot19['configured'] ?? true) === false, + 'Persistent lifecycle configuration drift left host/root configured.'); +CloudVpcService::recordObserved( + $vpcKey19, 38, $digest19, + $observed(38, $digest19, ['190' => $ready19]), + $operation19 +); + $shutdownRunningObservation19b = $stoppedObservation19b; $shutdownRunningObservation19b['state'] = 'active'; $shutdownRunningObservation19b['domain_running'] = true; @@ -1785,8 +1909,12 @@ CloudVpcService::recordObserved( $assert(Capsule::table('cloud_vpc_members')->where('id', 127) ->value('state') === 'stopping' && Capsule::table('cloud_vpcs')->where('id', 19) - ->value('sync_state') === 'waiting' + ->value('state') === 'active' && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('sync_state') === 'applied' + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('last_error_code') === null + && Capsule::table('cloud_vpc_private_ips')->where('id', 227) ->value('last_error_code') === 'vpc_private_guest_shutdown_pending', 'A periodic running/QGA receipt reopened a graceful-shutdown transition.'); $shutdownValidation19b = CloudVpcService::validatePrivateObservation( @@ -1847,6 +1975,12 @@ $assert(Capsule::table('cloud_vpc_members')->where('id', 127) && Capsule::table('cloud_vpc_private_ips')->where('id', 227) ->value('state') === 'stopped' && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('state') === 'active' + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('sync_state') === 'applied' + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('last_error_code') === null + && Capsule::table('cloud_vpc_private_ips')->where('id', 227) ->value('last_error_code') === 'vpc_private_guest_stopped', 'Periodic reconciliation overwrote exact stopped evidence with degraded.'); @@ -2003,9 +2137,13 @@ $assert(Capsule::table('cloud_vpc_members')->where('id', 127) && Capsule::table('cloud_vpc_private_ips')->where('id', 227) ->value('state') === 'suspended' && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 19) - ->where('host_id', 190)->value('state') === 'degraded' + ->where('host_id', 190)->value('state') === 'active' && Capsule::table('cloud_vpcs')->where('id', 19) - ->value('state') === 'degraded' + ->value('state') === 'active' + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('sync_state') === 'applied' + && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('last_error_code') === null && ($suspendedProjection19b['state'] ?? null) === 'suspended' && ($suspendedProjection19b['link_state'] ?? null) === 'down' && ($suspendedRoot19['usable'] ?? true) === false, @@ -2037,11 +2175,12 @@ $assert(Capsule::table('cloud_vpc_members')->where('id', 127) && Capsule::table('cloud_vpc_operations')->where('operation_id', $operation19) ->value('status') === 'succeeded' && Capsule::table('cloud_vpc_host_deployments')->where('vpc_id', 19) - ->where('host_id', 190)->value('last_error_code') - === 'vpc_private_network_suspended' + ->where('host_id', 190)->value('last_error_code') === null && Capsule::table('cloud_vpcs')->where('id', 19) ->value('sync_state') === 'applied' && Capsule::table('cloud_vpcs')->where('id', 19) + ->value('last_error_code') === null + && Capsule::table('cloud_vpc_private_ips')->where('id', 227) ->value('last_error_code') === 'vpc_private_network_suspended' && ($periodicRoot19['usable'] ?? true) === false, 'Periodic VPC observation overwrote intentional suspended runtime state.'); diff --git a/web/tests/CloudVpcUserPageBehaviorTest.mjs b/web/tests/CloudVpcUserPageBehaviorTest.mjs index 903ae63b..dfc9be20 100644 --- a/web/tests/CloudVpcUserPageBehaviorTest.mjs +++ b/web/tests/CloudVpcUserPageBehaviorTest.mjs @@ -17,6 +17,7 @@ const source = moduleSource + `\n;globalThis.__vpcBehavior = { state, normalizeRoot, + configurationReady, awaitingMembers, rootStatus, childStatus, @@ -107,6 +108,7 @@ vm.runInNewContext(source, context, { filename: 'vpc.js' }); const { state, normalizeRoot, + configurationReady, awaitingMembers, rootStatus, childStatus, @@ -185,6 +187,14 @@ assert.equal(powerWorkflow(detaching).title, '正在移除私网配置'); const paused = workflowDocument('paused', { error_code: 'vpc_power_shutdown_timeout', resume_cancelled: true, }); +Object.assign(paused.vpc, { + configured: false, usable: false, state: 'degraded', sync_state: 'waiting', +}); +state.selected = paused; +state.vpcs = [paused.vpc]; +assert.equal(rootStatus(paused.vpc), 'waiting'); +assert.equal(needsPolling(), false, + 'A paused pre-configuration workflow must wait for an explicit retry instead of polling forever.'); const pauseText = nodeText(renderPowerWorkflow(paused)); assert.match(pauseText, /关机等待超时.*未强制断电.*实例详情.*核对 \/ 重试/u); assert.match(pauseText, /手动电源操作.*不再自动恢复开机/u); @@ -214,16 +224,19 @@ assert.match(nodeText(renderPowerWorkflow(workflowDocument('completed', { original_running: false, }))), /原本已关机.*保持关机/u); const completedWithoutGuestProof = workflowDocument('completed'); -Object.assign(completedWithoutGuestProof.vpc, { usable: false, state: 'degraded', sync_state: 'waiting', - last_error_code: 'vpc_private_guest_stopped' }); -assert.equal(rootStatus(completedWithoutGuestProof.vpc), 'waiting', - 'Finishing the power workflow must not manufacture guest-network readiness.'); +Object.assign(completedWithoutGuestProof.vpc, { + configured: true, usable: false, state: 'active', sync_state: 'applied', + last_error_code: '', +}); +assert.equal(configurationReady(completedWithoutGuestProof.vpc), true); +assert.equal(rootStatus(completedWithoutGuestProof.vpc), 'active', + 'Guest health must not reopen an exact host-configuration receipt.'); assert.match(nodeText(renderPowerWorkflow(completedWithoutGuestProof)), /来宾网络可用性将单独核验/u); -assert.match(errorLabel(completedWithoutGuestProof.vpc.last_error_code), /上次回读时.*仍待核验/u); +assert.match(errorLabel('vpc_private_guest_stopped'), /上次回读时.*仍待核验/u); state.selected = completedWithoutGuestProof; state.vpcs = [completedWithoutGuestProof.vpc]; -assert.equal(needsPolling(), true, - 'Completed power handling must keep following the pending guest-network observation.'); +assert.equal(needsPolling(), false, + 'A completed config-exact operation must not poll forever for guest-only health.'); assert.equal(completedWithoutGuestProof.vpc.usable, false); for (const mutate of [ doc => { doc.vpc.last_operation_id = 'newer-operation'; }, @@ -245,8 +258,8 @@ assert.equal(untrustedFields.resumeCancelled, false); state.selected = null; state.vpcs = []; -// Known guest evidence must explain the current blocker while leaving the -// server-owned readiness gate closed. A friendly label is never guest proof. +// Known guest evidence remains actionable member guidance. It must not make a +// config-exact root look pending or keep the root polling loop alive. const guestProbeGuidance = [ ['vpc_private_guest_agent_unavailable', /来宾代理.*实例已启动.*代理服务/u], ['vpc_private_guest_probe_unsupported', /来宾代理.*核验所需能力.*管理员.*尚未确认可用/u], @@ -261,18 +274,19 @@ for (const [code, guidance] of guestProbeGuidance) { assert.match(errorLabel(code), guidance, `${code} must show reviewed, actionable guidance instead of generic waiting.`); const pendingGuest = normalizeRoot({ - vpc_key: 'guest-pending', state: 'degraded', sync_state: 'waiting', - usable: false, member_count: 2, last_error_code: code, + vpc_key: 'guest-pending', state: 'active', sync_state: 'applied', + configured: true, usable: false, member_count: 2, last_error_code: '', }); - assert.equal(pendingGuest.last_error_code, code); + assert.equal(pendingGuest.last_error_code, ''); assert.equal(pendingGuest.usable, false, 'Rendering a specific guest diagnosis must not invent a readiness receipt.'); + assert.equal(configurationReady(pendingGuest), true); assert.equal(awaitingMembers(pendingGuest), false); - assert.equal(rootStatus(pendingGuest), 'waiting'); + assert.equal(rootStatus(pendingGuest), 'active'); state.vpcs = [pendingGuest]; state.selected = null; - assert.equal(needsPolling(), true, - 'Guest readiness must continue following current engine observations.'); + assert.equal(needsPolling(), false, + 'Guest-only health must not reopen automatic root reconciliation.'); } state.vpcs = []; assert.equal(errorLabel('vpc_private_guest_probe_unknown_unsafe_payload'), '', diff --git a/web/tests/CloudVpcUserPageContractTest.php b/web/tests/CloudVpcUserPageContractTest.php index 97270bc2..75ef913b 100644 --- a/web/tests/CloudVpcUserPageContractTest.php +++ b/web/tests/CloudVpcUserPageContractTest.php @@ -222,7 +222,11 @@ foreach (['awaiting_members', 'applying', 'degraded', 'uncertain', 'waiting', 'a $assert(str_contains($script, $status), 'VPC UI lost state projection for ' . $status . '.'); } -$assert(str_contains($script, 'usable === true') +$assert(str_contains($script, 'function configurationReady(root)') + && str_contains($script, "projectionFieldKnown(root, 'configured')") + && str_contains($script, 'root?.configured === true') + && str_contains($script, 'root?.usable === true') + && !str_contains($script, 'configuration_ready') && str_contains($script, 'desired_revision') && str_contains($script, 'observed_revision') && str_contains($script, 'setTimeout') @@ -231,7 +235,7 @@ $assert(str_contains($script, 'usable === true') && str_contains($script, 'loadDetail(state.selectedKey, true)') && str_contains($script, 'state.detailDirty') && str_contains($script, 'allowDirty = false'), - 'VPC UI must poll desired/observed state, pause hidden tabs and only show active after usable readback.'); + 'VPC UI must prefer root configuration receipts, retain old usable fallback and bound polling.'); $detailInputStart = strpos($script, 'function handleDetailInput('); $detailInputEnd = strpos($script, 'function readBootstrap(', $detailInputStart ?: 0); $detailInput = $detailInputStart !== false && $detailInputEnd !== false