Merge fix/v2.0.10-battle-recovery for Web 2.0.10
This commit is contained in:
@@ -83,6 +83,20 @@ jobs:
|
|||||||
ranch_web.tests.test_commission_procurement_views -v
|
ranch_web.tests.test_commission_procurement_views -v
|
||||||
- name: Offline updater and task log regression
|
- name: Offline updater and task log regression
|
||||||
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package ranch_web.tests.test_activity ranch_web.tests.test_task_logs -v
|
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package ranch_web.tests.test_activity ranch_web.tests.test_task_logs -v
|
||||||
|
- name: Offline battle transport, recovery, and capability regression
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: |
|
||||||
|
python -B -m unittest \
|
||||||
|
ranch_assistant.tests.test_battle_worker_transport \
|
||||||
|
ranch_assistant.tests.test_battle_recovery \
|
||||||
|
ranch_assistant.tests.test_battle_capability_presentation \
|
||||||
|
ranch_web.tests.test_lifecycle_recovery -v
|
||||||
|
- name: Offline Web battle recovery contract and status API regression
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: |
|
||||||
|
python -B -m unittest \
|
||||||
|
ranch_web.tests.test_battle_recovery_contract \
|
||||||
|
ranch_web.tests.test_status_recovery_api -v
|
||||||
- name: Offline account recovery regression
|
- name: Offline account recovery regression
|
||||||
run: python -B -m unittest ranch_web.tests.test_run_intent ranch_web.tests.test_scheduler_recovery ranch_web.tests.test_auto_relogin ranch_web.tests.test_connection_state -v
|
run: python -B -m unittest ranch_web.tests.test_run_intent ranch_web.tests.test_scheduler_recovery ranch_web.tests.test_auto_relogin ranch_web.tests.test_connection_state -v
|
||||||
- name: Build image
|
- name: Build image
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
FROM python:3.12-slim-bookworm
|
FROM python:3.12-slim-bookworm
|
||||||
|
|
||||||
ARG WEB_VERSION=2.0.9
|
ARG WEB_VERSION=2.0.10
|
||||||
ARG VCS_REF=unknown
|
ARG VCS_REF=unknown
|
||||||
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
|
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
|
||||||
org.opencontainers.image.title="myrzx_bot Web" \
|
org.opencontainers.image.title="myrzx_bot Web" \
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
# 牧羊人之心Bot
|
# 牧羊人之心Bot
|
||||||
|
|
||||||
Web **2.0.9**,源码发布入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
|
Web **2.0.10**,源码发布入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
|
||||||
支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。
|
支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。
|
||||||
|
|
||||||
## 运行指引
|
## 运行指引
|
||||||
|
|
||||||
### Web 2.0.9(源码发布入口 main)
|
### Web 2.0.10(源码发布入口 main)
|
||||||
|
|
||||||
Windows 使用 Python 3.12+,在项目根目录执行:
|
Windows 使用 Python 3.12+,在项目根目录执行:
|
||||||
|
|
||||||
@@ -19,9 +19,11 @@ py -3 -m venv .venv-web
|
|||||||
|
|
||||||
Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。
|
Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。
|
||||||
|
|
||||||
**2.0.9** 清理设置页重复运行提示,沿用原单一底部分类日志。委托明确显示中文未接取原因,成熟魔物需求联动购蛋、孵化,先备齐资源再接取;按剩余步骤计算缺口,继续遵守预算及魔物保护设置。
|
**2.0.10** 修复 Linux 战斗子进程输入传输、中断恢复、停止检查及导航能力误报。升级后,符合证据的旧委托备料战斗可按原客户端协议记录失败并退出一次;完整战果可续交尚未发送的结果,未知已发送写请求不重放。来源策略关闭时明确等待启用,保留用户运行意愿,不自动开启策略。
|
||||||
|
|
||||||
正常自动战斗默认使用快速数值模型,保留现有伤害配置,无需另选模式;按双方属性、血量、伤害、时间及关卡目标估算胜负,逐帧实现仅供研发。358/358份主线与委托战斗配置通过输入预检,表示配置可计算,实际仍可能打不过。正常潜能误报也已修复;验证结果见 [发布说明](analysis/RELEASE_2_0_9.md)。
|
本版后端、模型与更新器共 **550 项唯一测试:548 通过、2 项 Windows 预期跳过**;另有 **14 项全新浏览器测试全部通过**。正式镜像与稳定 Release 就绪后,由用户通过“帮助 → 检查版本更新…”在线升级,详情见 [本版发布说明](analysis/RELEASE_2_0_10.md)。
|
||||||
|
|
||||||
|
沿用 2.0.9 的快速数值模型、伤害配置、委托备料与潜能误报修复;模型按双方属性、血量、伤害、时间及关卡目标估算胜负,逐帧实现仅供研发。2.0.9 的配置预检与历史验证见 [历史发布说明](analysis/RELEASE_2_0_9.md)。
|
||||||
|
|
||||||
**2.0.8** 自动委托提供“当前委托 / 每日记录”,跨城市按合格候选的预计氪金 **20→15→10** 排序并说明回退原因;按角色、北京时间自然日持久记录接取、推进和领奖,保留最近90天、每角色最多5000条事件。静态预计奖励与领奖回包确认金额分开,缺失金额保持未确认;旧历史仅从本地任务 journal 可证实的部分回填。详见 [2.0.8 发布说明](analysis/RELEASE_2_0_8.md)。
|
**2.0.8** 自动委托提供“当前委托 / 每日记录”,跨城市按合格候选的预计氪金 **20→15→10** 排序并说明回退原因;按角色、北京时间自然日持久记录接取、推进和领奖,保留最近90天、每角色最多5000条事件。静态预计奖励与领奖回包确认金额分开,缺失金额保持未确认;旧历史仅从本地任务 journal 可证实的部分回填。详见 [2.0.8 发布说明](analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
@@ -42,7 +44,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
|
|||||||
|
|
||||||
| 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 |
|
| 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Web 2.0.9 | 1.9.68 | 源码发布入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
|
| Web 2.0.10 | 1.9.68 | 源码发布入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
|
||||||
| 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` |
|
| 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` |
|
||||||
| 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 |
|
| 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 |
|
||||||
| 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 |
|
| 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 |
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Web 2.0.10 发布说明
|
||||||
|
|
||||||
|
Web **2.0.10** 基于 **2.0.9**;游戏资料 **1.9.68**,桌面正式版 **1.2.0**。
|
||||||
|
|
||||||
|
## 本版范围
|
||||||
|
|
||||||
|
- **Linux 输入传输**:战斗子进程从匿名临时文件一次读取完整 stdin,修复 Python 3.12 管道重试丢失剩余输入导致的技术超时,保留取消与大小限制。
|
||||||
|
- **旧战斗失败退出**:升级后,旧委托备料记录若已确认入场、未发送结算且符合技术失败条件,按原客户端协议发送 `recordBattleResult`、`result=0` 退出一次;兼容来源任务与步骤均为0的记录,不重新入场、不提交胜利。
|
||||||
|
- **按证据恢复**:保存的原始战斗输入最多用于一次本地恢复;完整战果校验通过后按战斗时钟续交尚未发送的结果。未知已发送写请求不重放。
|
||||||
|
- **停止与等待**:停止检查覆盖恢复提交;内部暂停保留用户运行意愿,来源策略关闭时明确等待启用,不自动开启策略。
|
||||||
|
- **状态与能力展示**:接口透出5个安全策略状态字段,区分运行意愿、实际执行与等待原因;包含 2.0.9 后的导航能力误报修正,真实输入不支持、资源不足及失败原因继续保留。
|
||||||
|
|
||||||
|
沿用现有快速 HP/DPS 模型、伤害配置与工作台布局。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
后端、模型与更新器共 **550 项唯一测试:548 通过、2 项 Windows 预期跳过**;另有 **14 项全新浏览器测试全部通过**,8组独立探针复核通过。
|
||||||
|
|
||||||
|
本轮验证未写入真实游戏 API、未手动部署、未修改生产 journal。升级后依据持久化证据及策略授权恢复。
|
||||||
|
|
||||||
|
## 发布与升级
|
||||||
|
|
||||||
|
正式镜像与稳定 Release 就绪后,由用户在“帮助 → 检查版本更新…”发起在线升级,见 [部署说明](../deploy/web/README.md)。
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
name: ranch-web
|
name: ranch-web
|
||||||
services:
|
services:
|
||||||
web:
|
web:
|
||||||
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.9}
|
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.10}
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
args:
|
args:
|
||||||
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.9}
|
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.10}
|
||||||
user: "10001:10001"
|
user: "10001:10001"
|
||||||
init: true
|
init: true
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
+10
-8
@@ -1,8 +1,8 @@
|
|||||||
# Web 2 Linux Docker 部署与更新
|
# Web 2 Linux Docker 部署与更新
|
||||||
|
|
||||||
当前应用及更新示例为 `v2.0.9`。下文首次初始化章节保留 2.0.1 流程及历史版本示例。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
|
当前应用及更新示例为 `v2.0.10`。下文首次初始化章节保留 2.0.1 流程及历史版本示例。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
|
||||||
|
|
||||||
2.0.9 仅整理设置页重复运行提示,21项相关测试通过;以下历史结果不计入本补丁,见 [本版发布说明](../../analysis/RELEASE_2_0_9.md)。
|
2.0.10 修复 Linux 战斗输入传输、中断恢复、停止检查及能力状态误报。升级后按持久化证据恢复:符合条件的旧委托备料技术失败记录退出一次;来源策略关闭时明确等待启用,保留运行意愿,不自动开启策略;未知已发送写请求不重放。已有宿主机由用户在 Web 内发起在线更新,见 [本版发布说明](../../analysis/RELEASE_2_0_10.md)。
|
||||||
|
|
||||||
已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。
|
已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env
|
|||||||
sudoedit .env .image.env
|
sudoedit .env .image.env
|
||||||
```
|
```
|
||||||
|
|
||||||
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 的目标示例为 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.9`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
|
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 的目标示例为 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.10`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
|
||||||
|
|
||||||
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、委托历史、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
|
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、委托历史、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳
|
|||||||
|
|
||||||
### 已完成 2.0.1 初始化的宿主机
|
### 已完成 2.0.1 初始化的宿主机
|
||||||
|
|
||||||
稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.9 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。
|
稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.10 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。
|
||||||
|
|
||||||
### 全新宿主机安装
|
### 全新宿主机安装
|
||||||
|
|
||||||
@@ -110,7 +110,7 @@ python3 -B /opt/ranch-web/updater.pyz --version
|
|||||||
|
|
||||||
Docker 保存的宿主机登录配置供更新器拉镜像使用;不要复制开发机的 Git/registry 凭据,也不要把 Docker 凭据放进 GitHub Token 文件或 Web 容器。[GHCR 官方认证说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
Docker 保存的宿主机登录配置供更新器拉镜像使用;不要复制开发机的 Git/registry 凭据,也不要把 Docker 凭据放进 GitHub Token 文件或 Web 容器。[GHCR 官方认证说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
||||||
|
|
||||||
4. 使用新包先检查再由用户明确发起在线更新。以下 `--apply v2.0.1` 仅保留首次初始化的历史示例,不是本轮 2.0.9 升级命令:
|
4. 使用新包先检查再由用户明确发起在线更新。以下 `--apply v2.0.1` 仅保留首次初始化的历史示例,不是本轮 2.0.10 升级命令:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check
|
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check
|
||||||
@@ -165,12 +165,14 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会
|
|||||||
|
|
||||||
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。
|
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。
|
||||||
|
|
||||||
|
2.0.10 后端、模型与更新器共 **550 项唯一测试:548 通过、2 项 Windows 预期跳过**;另有 **14 项全新浏览器测试全部通过**,8组独立探针复核通过。本轮验证未写入真实游戏 API、未手动部署、未修改生产 journal;升级后的恢复以保存证据与策略授权为准。
|
||||||
|
|
||||||
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过,详见 [发布说明](../../analysis/RELEASE_2_0_8.md#验证)。2.0.7 结果保留在 [历史发布说明](../../analysis/RELEASE_2_0_7.md#验证)。以下命令可复现本地更新器构建与离线检查;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件:
|
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过,详见 [发布说明](../../analysis/RELEASE_2_0_8.md#验证)。2.0.7 结果保留在 [历史发布说明](../../analysis/RELEASE_2_0_7.md#验证)。以下命令可复现本地更新器构建与离线检查;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python -B tools/build_web_updater.py --output test-artifacts/releases/v2.0.9/updater.pyz
|
python -B tools/build_web_updater.py --output test-artifacts/releases/v2.0.10/updater.pyz
|
||||||
python -B test-artifacts/releases/v2.0.9/updater.pyz --version
|
python -B test-artifacts/releases/v2.0.10/updater.pyz --version
|
||||||
python -B test-artifacts/releases/v2.0.9/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.9 --dry-run
|
python -B test-artifacts/releases/v2.0.10/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.10 --dry-run
|
||||||
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v
|
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
# Pull only after the v2.0.9 image publishing workflow succeeds and the image is available.
|
# Pull only after the v2.0.10 image publishing workflow succeeds and the image is available.
|
||||||
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.9
|
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.10
|
||||||
|
|||||||
@@ -1363,6 +1363,8 @@ class ExperimentalBattleRuntime:
|
|||||||
diagnostics=[{"code": "static_data", "message": str(exc)}])
|
diagnostics=[{"code": "static_data", "message": str(exc)}])
|
||||||
|
|
||||||
def run(self, request, *, cancel_event=None, timeout=30.0):
|
def run(self, request, *, cancel_event=None, timeout=30.0):
|
||||||
|
import tempfile
|
||||||
|
|
||||||
timeout = _number(timeout, "timeout")
|
timeout = _number(timeout, "timeout")
|
||||||
if timeout < 0:
|
if timeout < 0:
|
||||||
raise SimulationInputError("timeout must be nonnegative")
|
raise SimulationInputError("timeout must be nonnegative")
|
||||||
@@ -1380,13 +1382,18 @@ class ExperimentalBattleRuntime:
|
|||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
process = None
|
process = None
|
||||||
try:
|
try:
|
||||||
|
# POSIX communicate(None) retries do not resume a partial stdin write.
|
||||||
|
# A bounded, rewound file gives the child all input and EOF once;
|
||||||
|
# its inherited handle remains valid after the parent closes its copy.
|
||||||
|
with tempfile.TemporaryFile(mode="w+b") as input_stream:
|
||||||
|
input_stream.write(wire)
|
||||||
|
input_stream.seek(0)
|
||||||
process = subprocess.Popen(
|
process = subprocess.Popen(
|
||||||
[sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"],
|
[sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"],
|
||||||
cwd=str(Path(__file__).resolve().parent.parent),
|
cwd=str(Path(__file__).resolve().parent.parent),
|
||||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
stdin=input_stream, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
)
|
)
|
||||||
pending_input = wire
|
|
||||||
while True:
|
while True:
|
||||||
if cancel_event is not None and cancel_event.is_set():
|
if cancel_event is not None and cancel_event.is_set():
|
||||||
return _execution_failure("cancelled", "worker_cancelled")
|
return _execution_failure("cancelled", "worker_cancelled")
|
||||||
@@ -1394,10 +1401,10 @@ class ExperimentalBattleRuntime:
|
|||||||
if left <= 0:
|
if left <= 0:
|
||||||
return _execution_failure("timeout", "worker_wall_clock_limit")
|
return _execution_failure("timeout", "worker_wall_clock_limit")
|
||||||
try:
|
try:
|
||||||
stdout, stderr = process.communicate(input=pending_input, timeout=min(.05, left))
|
stdout, stderr = process.communicate(timeout=min(.05, left))
|
||||||
break
|
break
|
||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
pending_input = None
|
pass
|
||||||
if len(stdout) > MAX_WIRE_BYTES or len(stderr) > 65536:
|
if len(stdout) > MAX_WIRE_BYTES or len(stderr) > 65536:
|
||||||
return _execution_failure("error", "worker_output_exceeds_limit")
|
return _execution_failure("error", "worker_output_exceeds_limit")
|
||||||
result = json.loads(stdout)
|
result = json.loads(stdout)
|
||||||
|
|||||||
+265
-46
@@ -172,6 +172,9 @@ class BattleJournal:
|
|||||||
value(intent, "stage_id", ""), value(intent, "difficulty", "1"))})
|
value(intent, "stage_id", ""), value(intent, "difficulty", "1"))})
|
||||||
if value(intent, "token") and value(intent, "account_key"):
|
if value(intent, "token") and value(intent, "account_key"):
|
||||||
record.update(intent_id=value(intent, "token"), account_key=value(intent, "account_key"))
|
record.update(intent_id=value(intent, "token"), account_key=value(intent, "account_key"))
|
||||||
|
if record.get("source_task_type_id") and not record.get("source_task_id"):
|
||||||
|
from .progression import ProgressionPlanner
|
||||||
|
record["source_offer_day"] = ProgressionPlanner._loop_day(snapshot, snapshot.now - 10)
|
||||||
state = self.role(snapshot)
|
state = self.role(snapshot)
|
||||||
state["records"].append(record)
|
state["records"].append(record)
|
||||||
state["pending"] = record["attempt_id"]
|
state["pending"] = record["attempt_id"]
|
||||||
@@ -428,7 +431,8 @@ class BattleOrchestrator:
|
|||||||
"experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics",
|
"experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics",
|
||||||
"ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events",
|
"ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events",
|
||||||
"model", "simulation_method", "team_budgets", "generated_units", "spawn_bound_reached",
|
"model", "simulation_method", "team_budgets", "generated_units", "spawn_bound_reached",
|
||||||
"damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope")}}
|
"damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope",
|
||||||
|
"supported", "timeout_kind")}}
|
||||||
trace = value(result, "trace")
|
trace = value(result, "trace")
|
||||||
if trace is None:
|
if trace is None:
|
||||||
trace = value(result, "events")
|
trace = value(result, "events")
|
||||||
@@ -441,8 +445,88 @@ class BattleOrchestrator:
|
|||||||
evidence["trace"] = public_data(trace)
|
evidence["trace"] = public_data(trace)
|
||||||
return evidence
|
return evidence
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def combat_resource_digest():
|
||||||
|
# Bind retries to the same combat tables and quick-model mathematics.
|
||||||
|
# Worker transport changes do not alter this contract.
|
||||||
|
root = Path(__file__).parent
|
||||||
|
return digest([hashlib.sha256(path.read_bytes()).hexdigest() for path in
|
||||||
|
(root / "data" / "combat_manifest.json", root / "battle_quick.py")])
|
||||||
|
|
||||||
|
def save_combat_request(self, record, request):
|
||||||
|
if request.get("battle_mode") != "experimental":
|
||||||
|
return {}
|
||||||
|
from .battle_simulator import _transport_request
|
||||||
|
combat = public_data(_transport_request(request))
|
||||||
|
raw = combat.get("roster")
|
||||||
|
if isinstance(raw, dict):
|
||||||
|
teams = [{key: row[key] for key in ("teamName", "teamType", "monsters") if key in row}
|
||||||
|
for row in raw.get("teams", []) if row.get("teamName") == combat["team"]]
|
||||||
|
for row in teams:
|
||||||
|
members = row.get("monsters") or []
|
||||||
|
if isinstance(members, str):
|
||||||
|
members = members.split(",")
|
||||||
|
# Preserve lineup order and empty slots; exploration helpers
|
||||||
|
# discard those slots and therefore cannot normalize combat.
|
||||||
|
row["monsters"] = [int(mid) if str(mid).strip() else 0 for mid in members]
|
||||||
|
ids = {str(mid) for row in teams for mid in row["monsters"]}
|
||||||
|
if not teams:
|
||||||
|
ids = set(combat["team"].split(","))
|
||||||
|
fields = {"id", "typeId", "level", "mode", "tpLevel", "feel", "upStar", "potentialLevel", "skin", "controller",
|
||||||
|
"skill_1", "skill_2", "skill_1_lv", "skill_2_lv", *["equip" + str(i) for i in range(1, 6)],
|
||||||
|
*[prefix + stat for prefix in ("g", "p") for stat in ("Atk", "Def", "Hp", "Dex")]}
|
||||||
|
raw["teams"] = teams
|
||||||
|
raw["monsters"] = [{key: val for key, val in row.items() if key in fields}
|
||||||
|
for row in raw.get("monsters", []) if str(row.get("id")) in ids]
|
||||||
|
raw["monsterAttributes"] = [row for row in raw.get("monsterAttributes", []) or [] if str(row.get("monsterId")) in ids]
|
||||||
|
combat["battle_mode"] = "experimental"
|
||||||
|
return {"combat_request": combat, "combat_request_digest": digest(combat),
|
||||||
|
"combat_resource_digest": self.combat_resource_digest()}
|
||||||
|
|
||||||
|
def accept_runtime_result(self, record, request, result, started, cancel):
|
||||||
|
mode = request.get("battle_mode", "original")
|
||||||
|
evidence = self.runtime_evidence(result, mode)
|
||||||
|
for key in ("damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope"):
|
||||||
|
if evidence.get(key) is None:
|
||||||
|
evidence.pop(key, None)
|
||||||
|
self.journal.update(record, "runtime_returned", runtime_outcome=value(result, "outcome"), **evidence)
|
||||||
|
outcome, data = value(result, "outcome"), value(result, "battle_data")
|
||||||
|
eligible = outcome in ("win", "loss")
|
||||||
|
if mode == "experimental":
|
||||||
|
eligible = (eligible and value(result, "experimental_settlement_eligible") is True
|
||||||
|
and value(result, "execution_mode") == "experimental" and value(result, "execution_status") == "completed"
|
||||||
|
and value(result, "supported") is True and value(result, "terminal") is True
|
||||||
|
and value(result, "approximate") is True and value(result, "faithful") is False
|
||||||
|
and not value(result, "anomalies") and not any(row.get("blocking") is True
|
||||||
|
for row in value(result, "diagnostics", []) or [] if isinstance(row, dict)))
|
||||||
|
else:
|
||||||
|
eligible = (eligible and value(result, "settlement_eligible") is True
|
||||||
|
and value(result, "faithful") is True and value(result, "approximate") is not True)
|
||||||
|
if not eligible or not isinstance(data, dict) or type(data.get("win")) is not bool:
|
||||||
|
message = ("本地战斗运行超时,已入场但尚无战果,等待恢复核对" if value(result, "execution_status") == "timed_out"
|
||||||
|
else "战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self._unknown(record, message)
|
||||||
|
return False
|
||||||
|
if data["win"] != (outcome == "win"):
|
||||||
|
self._unknown(record, "运行结果与战果胜负不一致,未提交结算")
|
||||||
|
return False
|
||||||
|
position = data.get("battlePosition")
|
||||||
|
if (not isinstance(position, dict) or {k: v for k, v in position.items() if v is not None}
|
||||||
|
!= {k: v for k, v in request["battle_position"].items() if v is not None}):
|
||||||
|
self._unknown(record, "运行时战果定位不匹配,未提交结算")
|
||||||
|
return False
|
||||||
|
# A generation cancellation does not invalidate an already computed result.
|
||||||
|
self.journal.update(record, "runtime_complete", battle_data=data)
|
||||||
|
ready = self.wait_for_battle_clock(record, request, result, data, started, cancel)
|
||||||
|
if cancel.is_set():
|
||||||
|
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
|
||||||
|
return False
|
||||||
|
return ready
|
||||||
|
|
||||||
def wait_for_battle_clock(self, record, request, result, data, started, cancel):
|
def wait_for_battle_clock(self, record, request, result, data, started, cancel):
|
||||||
if value(result, "requires_realtime_wait") is not True:
|
if value(result, "requires_realtime_wait") is not True:
|
||||||
|
self.journal.update(record, "waiting_for_battle_clock", battle_clock_seconds=0,
|
||||||
|
battle_ready_at=time.time(), resume_clock_ready=True)
|
||||||
return True
|
return True
|
||||||
duration = None
|
duration = None
|
||||||
for field, scale in (("model_elapsed_ms", .001), ("battle_elapsed_ms", .001), ("elapsed_ms", .001),
|
for field, scale in (("model_elapsed_ms", .001), ("battle_elapsed_ms", .001), ("elapsed_ms", .001),
|
||||||
@@ -471,39 +555,154 @@ class BattleOrchestrator:
|
|||||||
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
|
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def confirmed_start(record):
|
||||||
|
response = record.get("start_response")
|
||||||
|
task = bool(record.get("task_id"))
|
||||||
|
path = "battleService/battleStart" if task else "stageService/stageStart"
|
||||||
|
return (record.get("start_path") == path and isinstance(response, dict)
|
||||||
|
and response.get("resCode", 0) in (0, "0") and (task or response.get("triggerEvent") is False
|
||||||
|
or type(response.get("triggerEvent")) is int and response["triggerEvent"] == 0))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def source_matches(record, snapshot):
|
||||||
|
if not record.get("source_task_type_id"):
|
||||||
|
return True
|
||||||
|
if not record.get("source_task_id") and not record.get("source_step_number"):
|
||||||
|
from .progression import ProgressionPlanner
|
||||||
|
history = snapshot.raw.get("history", {})
|
||||||
|
offers = history.get("loopTask") or {}
|
||||||
|
today = ProgressionPlanner._loop_day(snapshot, snapshot.now - 10)
|
||||||
|
return (record.get("source_offer_day") == today and history.get("loopTaskTime") is not None
|
||||||
|
and ProgressionPlanner._loop_day(snapshot, history["loopTaskTime"]) == today
|
||||||
|
and isinstance(offers, dict) and any(str(key) == str(record["source_task_type_id"])
|
||||||
|
for rows in offers.values() if isinstance(rows, (list, tuple)) for key in rows)
|
||||||
|
and not any(str(task.get("typeId")) == str(record["source_task_type_id"])
|
||||||
|
for task in snapshot.raw.get("currentTasks", [])))
|
||||||
|
return any(str(task.get("id")) == str(record.get("source_task_id"))
|
||||||
|
and str(task.get("typeId")) == str(record["source_task_type_id"])
|
||||||
|
and str(task.get("curStep")) == str(record.get("source_step_number"))
|
||||||
|
for task in snapshot.raw.get("currentTasks", []))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def legacy_stage_failure(record):
|
||||||
|
return (record.get("kind") == "stage_battle" and not record.get("task_id")
|
||||||
|
and not record.get("task_type_id") and record.get("battle_kind") == "ordinary_stage"
|
||||||
|
and record.get("stage_category") in (None, "", "ordinary") and record.get("source_task_type_id")
|
||||||
|
and record.get("execution_mode") == "experimental" and record.get("terminal") is False
|
||||||
|
and record.get("terminal_reason") in ("worker_wall_clock_limit", "worker_cancelled", "worker_interrupted")
|
||||||
|
and record.get("execution_status") in ("cancelled", "timed_out") and not record.get("battle_data"))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resumable_task_clock(record):
|
def resumable_task_clock(record):
|
||||||
common = bool(record and ((record.get("kind") == "progression_battle" and record.get("task_id"))
|
common = bool(record and record.get("kind") in ("progression_battle", "map_battle", "stage_battle", "battle", "task_battle")
|
||||||
or (record.get("kind") == "map_battle" and not record.get("task_id")))
|
and ((record.get("execution_mode") == "experimental" and record.get("execution_status") == "completed"
|
||||||
and record.get("execution_mode") == "experimental" and record.get("execution_status") == "completed"
|
|
||||||
and record.get("experimental_settlement_eligible") is True and record.get("terminal") is True
|
and record.get("experimental_settlement_eligible") is True and record.get("terminal") is True
|
||||||
and record.get("approximate") is True and record.get("faithful") is False
|
and record.get("approximate") is True and record.get("faithful") is False)
|
||||||
|
or (record.get("battle_mode") == "original" and record.get("settlement_eligible") is True
|
||||||
|
and record.get("faithful") is True and record.get("approximate") is not True))
|
||||||
and not record.get("anomalies") and not any(row.get("blocking") is True
|
and not record.get("anomalies") and not any(row.get("blocking") is True
|
||||||
for row in record.get("diagnostics") or [] if isinstance(row, dict))
|
for row in record.get("diagnostics") or [] if isinstance(row, dict))
|
||||||
and isinstance(record.get("battle_data"), dict) and type(record["battle_data"].get("win")) is bool)
|
and isinstance(record.get("battle_data"), dict) and type(record["battle_data"].get("win")) is bool)
|
||||||
if not common:
|
if not common:
|
||||||
return False
|
return False
|
||||||
if (record.get("kind") == "map_battle" and record.get("phase") == "settlement_acknowledged"
|
if record.get("phase") in ("record_pending", "record_unknown"):
|
||||||
and record.get("settlement_confirmed") is True):
|
return False
|
||||||
|
if not record.get("task_id") and record.get("settlement_confirmed") is True:
|
||||||
return (record["battle_data"]["win"] is True and isinstance(record.get("response"), dict)
|
return (record["battle_data"]["win"] is True and isinstance(record.get("response"), dict)
|
||||||
and record["response"].get("resCode", 0) in (0, "0"))
|
and record["response"].get("resCode", 0) in (0, "0")
|
||||||
return (record.get("phase") in ("unknown", "waiting_for_battle_clock")
|
and (not record.get("record_dispatched") or record.get("record_confirmed") is True))
|
||||||
|
return (record.get("phase") in ("unknown", "runtime_complete", "waiting_for_battle_clock", "record_acknowledged")
|
||||||
and record.get("path") in ("", "battleService/battleStart", "stageService/stageStart")
|
and record.get("path") in ("", "battleService/battleStart", "stageService/stageStart")
|
||||||
and not record.get("settlement_confirmed") and not record.get("settlement_dispatched")
|
and not record.get("settlement_confirmed") and not record.get("settlement_dispatched")
|
||||||
|
and (not record.get("record_dispatched") or record.get("record_confirmed") is True)
|
||||||
and (record.get("resume_clock_ready") is True or
|
and (record.get("resume_clock_ready") is True or
|
||||||
|
record.get("phase") == "runtime_complete" or
|
||||||
record.get("message") == "等待战斗时钟期间已取消,开战记录保留待核对"))
|
record.get("message") == "等待战斗时钟期间已取消,开战记录保留待核对"))
|
||||||
|
|
||||||
|
def recovery_status(self, record, *, snapshot=None):
|
||||||
|
"""Read-only classification. Resumable never grants permission to write."""
|
||||||
|
def status(state, message=""):
|
||||||
|
return {"state": state, "resumable": state not in ("none", "blocked"), "message": message}
|
||||||
|
if not record:
|
||||||
|
return status("none")
|
||||||
|
if isinstance(snapshot, dict):
|
||||||
|
snapshot = SimpleNamespace(raw=snapshot, now=time.time())
|
||||||
|
if record.get("kind") not in ("progression_battle", "map_battle", "stage_battle", "battle", "task_battle"):
|
||||||
|
return status("blocked", record.get("message") or "任务请求待核对,不能按战斗恢复")
|
||||||
|
if snapshot and str(record.get("role_id")) != role_id(snapshot):
|
||||||
|
return status("blocked", "角色与原入场记录不匹配,保留待核对记录")
|
||||||
|
preaccept = not record.get("source_task_id") and not record.get("source_step_number")
|
||||||
|
source_matches = snapshot is None or self.source_matches(record, snapshot)
|
||||||
|
if (not source_matches
|
||||||
|
and not (preaccept and self.legacy_stage_failure(record))):
|
||||||
|
return status("blocked", "角色或来源委托步骤已变化,保留原战斗记录等待核对")
|
||||||
|
if record.get("abandon_requested") and record.get("record_confirmed") is True and record.get("record_result") is False:
|
||||||
|
return status("finish_abandonment", "失败退出已确认,等待完成本地记录")
|
||||||
|
if self.resumable_task_clock(record):
|
||||||
|
return status("resume_result", "完整战果已保存,可续交尚未发送的结果")
|
||||||
|
if record.get("phase") in ("record_pending", "record_unknown") or record.get("record_dispatched"):
|
||||||
|
return status("blocked", "战果记录请求已发送但结果未确认,禁止重复发送")
|
||||||
|
if record.get("settlement_dispatched") or record.get("settlement_confirmed") or record.get("path") not in (
|
||||||
|
"", None, "stageService/stageStart", "battleService/battleStart"):
|
||||||
|
return status("blocked", "结算请求可能已发送,等待服务器证据,禁止重复结算")
|
||||||
|
if record.get("phase") == "prepared" and record.get("start_dispatched") is False and not record.get("start_response"):
|
||||||
|
return status("unsent", "开战请求尚未发送,可取消本地准备记录")
|
||||||
|
if not self.confirmed_start(record):
|
||||||
|
return status("blocked", "开战请求结果未确认,禁止重新入场或自动退出")
|
||||||
|
interrupted = (record.get("runtime_not_started") is True or record.get("phase") in ("started", "running", "hidden_started") or
|
||||||
|
record.get("execution_status") in ("cancelled", "timed_out", "error"))
|
||||||
|
if not interrupted or record.get("battle_data"):
|
||||||
|
return status("blocked", "没有可验证的完整战果或安全恢复证据,保留待核对记录")
|
||||||
|
combat = record.get("combat_request")
|
||||||
|
if not isinstance(combat, dict):
|
||||||
|
# Original AIR: BattlePausePanel.yesEscapeHandler -> checkGameOver
|
||||||
|
# (run=True, winnerTeam=2) -> BattlePanel.showLose -> battleResult(false).
|
||||||
|
if self.legacy_stage_failure(record):
|
||||||
|
return status("abandon_stage", "旧记录缺少原始战斗输入,本地计算已超时或取消;开启后按原客户端退出协议记录失败,不推进任务")
|
||||||
|
return status("blocked", "旧记录缺少原始战斗输入,不能用当前属性重算;需要权威记录或原客户端退出核对")
|
||||||
|
if self.legacy_stage_failure(record) and (not source_matches or record.get("runtime_recovery_attempts", 0) >= 1):
|
||||||
|
return status("abandon_stage", "本地战斗未完成且来源委托已变化或恢复已用尽;开启后按原客户端退出协议记录失败")
|
||||||
|
if record.get("runtime_recovery_attempts", 0) >= 1:
|
||||||
|
return status("blocked", "本地战斗恢复已尝试一次仍未完成,保留入场记录等待核对")
|
||||||
|
if (record.get("battle_mode") != "experimental" or digest(combat) != record.get("combat_request_digest")
|
||||||
|
or self.combat_resource_digest() != record.get("combat_resource_digest")):
|
||||||
|
return status("blocked", "保存的原始战斗输入或资源校验不匹配,禁止改用当前属性重算")
|
||||||
|
return status("retry_local_runtime", "入场已确认且结算未发送,可用保存的原始输入恢复一次本地战斗")
|
||||||
|
|
||||||
def resume_task_clock(self, client, snapshot, intent, policy, *, cancel):
|
def resume_task_clock(self, client, snapshot, intent, policy, *, cancel):
|
||||||
"""Resume an unsent result, or finish recording a confirmed map settlement."""
|
"""Recover this entry only; never replay start or an uncertain server write."""
|
||||||
with self.journal.lock:
|
with self.journal.lock:
|
||||||
|
self.journal.reload()
|
||||||
record = self.journal.pending(snapshot)
|
record = self.journal.pending(snapshot)
|
||||||
if not policy.enabled or cancel.is_set() or not self.resumable_task_clock(record):
|
recovery = self.recovery_status(record, snapshot=snapshot)
|
||||||
|
if not policy.enabled or cancel.is_set() or not recovery["resumable"]:
|
||||||
return ""
|
return ""
|
||||||
if str(record.get("role_id")) != str(role_id(snapshot)):
|
if str(record.get("role_id")) != str(role_id(snapshot)):
|
||||||
return ""
|
return ""
|
||||||
if any(str(record.get(key)) != str(value(intent, key)) for key in
|
if any(str(record.get(key)) != str(value(intent, key)) for key in
|
||||||
("kind", "task_id", "task_type_id", "step_number")):
|
("kind", "task_id", "task_type_id", "step_number")):
|
||||||
return ""
|
return ""
|
||||||
|
if not record.get("task_id") and any(str(record.get(key)) != str(value(intent, key)) for key in
|
||||||
|
("stage_id", "difficulty", "battle_kind", "source_task_id", "source_task_type_id", "source_step_number")):
|
||||||
|
return ""
|
||||||
|
if recovery["state"] == "unsent":
|
||||||
|
if self.observer and (record.get("task_id") or record.get("map_roster_signature")):
|
||||||
|
self.observer("cancelled_before_start", intent, None)
|
||||||
|
self.journal.finish(snapshot, record, "cancelled", "已取消尚未发送的开战准备记录;未重新入场")
|
||||||
|
return record["message"]
|
||||||
|
if recovery["state"] in ("abandon_stage", "finish_abandonment"):
|
||||||
|
try:
|
||||||
|
if recovery["state"] == "abandon_stage":
|
||||||
|
self.journal.update(record, "abandon_pending", abandon_requested=True)
|
||||||
|
self._record(client, record, record["stage_id"], False, cancel=cancel)
|
||||||
|
self.journal.finish(snapshot, record, "abandoned", "已按原客户端退出协议确认失败;未提交胜利战果或推进来源委托")
|
||||||
|
return record["message"]
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
return "策略已停止,失败退出请求尚未发送,保留原入场记录"
|
||||||
|
except Exception as error:
|
||||||
|
self._unknown(record, "失败退出请求结果未确认,禁止重复发送", error_type=type(error).__name__)
|
||||||
|
raise
|
||||||
task_battle = bool(record.get("task_id"))
|
task_battle = bool(record.get("task_id"))
|
||||||
if task_battle:
|
if task_battle:
|
||||||
task = next((row for row in snapshot.raw.get("currentTasks", [])
|
task = next((row for row in snapshot.raw.get("currentTasks", [])
|
||||||
@@ -516,6 +715,25 @@ class BattleOrchestrator:
|
|||||||
"stageLevel": None if task_battle else str(record.get("difficulty")),
|
"stageLevel": None if task_battle else str(record.get("difficulty")),
|
||||||
"taskTypeId": str(record["task_type_id"]) if task_battle else None,
|
"taskTypeId": str(record["task_type_id"]) if task_battle else None,
|
||||||
"taskStep": int(record["step_number"]) - 1 if task_battle else 0}
|
"taskStep": int(record["step_number"]) - 1 if task_battle else 0}
|
||||||
|
if recovery["state"] == "retry_local_runtime":
|
||||||
|
request = deepcopy(record["combat_request"])
|
||||||
|
position = request.get("battle_position")
|
||||||
|
if (not isinstance(position, dict) or {k: v for k, v in position.items() if v is not None}
|
||||||
|
!= {k: v for k, v in expected.items() if v is not None}
|
||||||
|
or request.get("team") != record.get("team")):
|
||||||
|
return "保存的原始战斗输入与入场定位不匹配,保留待核对记录"
|
||||||
|
supported, reason = self.inspect(request)
|
||||||
|
if not supported:
|
||||||
|
return "保存的原始战斗输入当前无法执行:" + reason
|
||||||
|
self.journal.update(record, "running", runtime_recovery_attempts=1, runtime_not_started=False)
|
||||||
|
try:
|
||||||
|
started = self.clock()
|
||||||
|
result = self.runtime.run(request, cancel_event=cancel)
|
||||||
|
if not self.accept_runtime_result(record, request, result, started, cancel):
|
||||||
|
return record["message"]
|
||||||
|
except Exception as error:
|
||||||
|
self._unknown(record, "本地战斗恢复未完成,保留原入场记录", error_type=type(error).__name__)
|
||||||
|
raise
|
||||||
data = record["battle_data"]
|
data = record["battle_data"]
|
||||||
position = data.get("battlePosition")
|
position = data.get("battlePosition")
|
||||||
if not isinstance(position, dict) or {key: val for key, val in position.items() if val is not None} != {
|
if not isinstance(position, dict) or {key: val for key, val in position.items() if val is not None} != {
|
||||||
@@ -524,6 +742,10 @@ class BattleOrchestrator:
|
|||||||
ready = 0 if record.get("settlement_confirmed") else record.get("battle_ready_at")
|
ready = 0 if record.get("settlement_confirmed") else record.get("battle_ready_at")
|
||||||
if ready is None:
|
if ready is None:
|
||||||
duration = record.get("battle_clock_seconds")
|
duration = record.get("battle_clock_seconds")
|
||||||
|
if duration is None and record.get("requires_realtime_wait") is not True:
|
||||||
|
duration = 0
|
||||||
|
if duration is None and type(record.get("elapsed_ms")) in (int, float):
|
||||||
|
duration = record["elapsed_ms"] / 1000
|
||||||
stamp = record.get("updated_at")
|
stamp = record.get("updated_at")
|
||||||
if any(type(number) not in (int, float) or not math.isfinite(number) or number < 0
|
if any(type(number) not in (int, float) or not math.isfinite(number) or number < 0
|
||||||
for number in (duration, stamp)):
|
for number in (duration, stamp)):
|
||||||
@@ -536,7 +758,7 @@ class BattleOrchestrator:
|
|||||||
return "已核对保存的战果;尚未到结算时间,2分钟内自动复查"
|
return "已核对保存的战果;尚未到结算时间,2分钟内自动复查"
|
||||||
try:
|
try:
|
||||||
if not data["win"]:
|
if not data["win"]:
|
||||||
if not task_battle or record.get("battle_kind") == "passStage":
|
if (not task_battle or record.get("battle_kind") == "passStage") and not record.get("record_confirmed"):
|
||||||
self._record(client, record, record["stage_id"], False, cancel=cancel)
|
self._record(client, record, record["stage_id"], False, cancel=cancel)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("loss", intent, None)
|
self.observer("loss", intent, None)
|
||||||
@@ -552,15 +774,16 @@ class BattleOrchestrator:
|
|||||||
response = self._call(client, path, payload, cancel=cancel)
|
response = self._call(client, path, payload, cancel=cancel)
|
||||||
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response),
|
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response),
|
||||||
settlement_confirmed=True, reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
settlement_confirmed=True, reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
||||||
if not task_battle:
|
if not task_battle and not record.get("record_confirmed"):
|
||||||
self._record(client, record, record["stage_id"], True)
|
self._record(client, record, record["stage_id"], True, cancel=cancel)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("settled", intent, response)
|
self.observer("settled", intent, response)
|
||||||
elif task_battle:
|
elif task_battle:
|
||||||
self.journal.checkpoint(snapshot, intent, response)
|
self.journal.checkpoint(snapshot, intent, response)
|
||||||
self.journal.finish(snapshot, record, "win", "已自动续交保存的战果;未重新开战或重新模拟")
|
self.journal.finish(snapshot, record, "win", "已恢复此入场的战果并确认结算;未重新开战")
|
||||||
return record["message"]
|
return record["message"]
|
||||||
except CancelledBeforeDispatch:
|
except CancelledBeforeDispatch:
|
||||||
|
if not record.get("settlement_confirmed"):
|
||||||
self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart" if task_battle else "stageService/stageStart",
|
self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart" if task_battle else "stageService/stageStart",
|
||||||
settlement_dispatched=False, resume_clock_ready=True)
|
settlement_dispatched=False, resume_clock_ready=True)
|
||||||
return "策略已停止,保存的战果将在重新开启后续交"
|
return "策略已停止,保存的战果将在重新开启后续交"
|
||||||
@@ -601,24 +824,31 @@ class BattleOrchestrator:
|
|||||||
return "任务 / 战斗已取消,未开始"
|
return "任务 / 战斗已取消,未开始"
|
||||||
record = self.journal.begin(snapshot, intent)
|
record = self.journal.begin(snapshot, intent)
|
||||||
try:
|
try:
|
||||||
|
self.journal.update(record, "prepared", start_dispatched=False)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("started", intent, None)
|
self.observer("started", intent, None)
|
||||||
if value(intent, "task_id"):
|
if value(intent, "task_id"):
|
||||||
path, payload = "battleService/battleStart", {"battleType": "task", "taskTypeId": str(value(intent, "task_type_id"))}
|
path, payload = "battleService/battleStart", {"battleType": "task", "taskTypeId": str(value(intent, "task_type_id"))}
|
||||||
else:
|
else:
|
||||||
path, payload = "stageService/stageStart", {"stageTypeId": str(value(intent, "stage_id")), "stageLevel": str(value(intent, "difficulty", "1"))}
|
path, payload = "stageService/stageStart", {"stageTypeId": str(value(intent, "stage_id")), "stageLevel": str(value(intent, "difficulty", "1"))}
|
||||||
self.journal.update(record, "start_pending", start_path=path, input_digest=digest(public_data(request)),
|
self.journal.update(record, "start_pending",
|
||||||
|
**{key: val for key, val in self._inspection_evidence.items() if key not in ("battle_mode", "resource_identity")},
|
||||||
|
**self.save_combat_request(record, request),
|
||||||
|
path=path, start_path=path, start_dispatched=True, settlement_dispatched=False, record_dispatched=False,
|
||||||
|
input_digest=digest(public_data(request)),
|
||||||
team=policy.team, battle_mode=mode,
|
team=policy.team, battle_mode=mode,
|
||||||
resource_identity=(request.get("original_data") or {}).get("manifest", {}).get("source"))
|
resource_identity=(request.get("original_data") or {}).get("manifest", {}).get("source"))
|
||||||
try:
|
try:
|
||||||
started = self._call(client, path, payload, cancel=cancel)
|
started = self._call(client, path, payload, cancel=cancel)
|
||||||
except CancelledBeforeDispatch:
|
except CancelledBeforeDispatch:
|
||||||
|
self.journal.update(record, "start_pending", start_dispatched=False)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("cancelled_before_start", intent, None)
|
self.observer("cancelled_before_start", intent, None)
|
||||||
self.journal.finish(snapshot, record, "cancelled", "开战请求尚未发送,已取消;未消耗入场资源")
|
self.journal.finish(snapshot, record, "cancelled", "开战请求尚未发送,已取消;未消耗入场资源")
|
||||||
return record["message"]
|
return record["message"]
|
||||||
battle_started = self.clock()
|
battle_started = self.clock()
|
||||||
self.journal.update(record, "started", start_response=gameplay_response(started))
|
self.journal.update(record, "started", start_confirmed=True, start_confirmed_at=time.time(),
|
||||||
|
runtime_not_started=True, start_response=gameplay_response(started))
|
||||||
if not value(intent, "task_id"):
|
if not value(intent, "task_id"):
|
||||||
reward = event_reward(started)
|
reward = event_reward(started)
|
||||||
if reward is not None:
|
if reward is not None:
|
||||||
@@ -638,38 +868,17 @@ class BattleOrchestrator:
|
|||||||
supported, reason = self.inspect(request)
|
supported, reason = self.inspect(request)
|
||||||
if not supported:
|
if not supported:
|
||||||
return self._unknown(record, "隐藏关卡待处理:" + reason)
|
return self._unknown(record, "隐藏关卡待处理:" + reason)
|
||||||
self.journal.update(record, "hidden_started", stage_id=hidden, difficulty="1")
|
self.journal.update(record, "hidden_started", stage_id=hidden, difficulty="1",
|
||||||
|
**self.save_combat_request(record, request))
|
||||||
else:
|
else:
|
||||||
return self._unknown(record, "探索事件或开战状态未知,等待核对")
|
return self._unknown(record, "探索事件或开战状态未知,等待核对")
|
||||||
if cancel.is_set():
|
if cancel.is_set():
|
||||||
return self._unknown(record, "开战后已取消,等待服务器状态核对")
|
return self._unknown(record, "开战后已取消,等待服务器状态核对")
|
||||||
self.journal.update(record, "running")
|
self.journal.update(record, "running", runtime_not_started=False)
|
||||||
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
|
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
|
||||||
evidence = self.runtime_evidence(result, mode)
|
if not self.accept_runtime_result(record, request, result, battle_started, cancel):
|
||||||
self.journal.update(record, "runtime_returned", **evidence)
|
|
||||||
if cancel.is_set() or value(result, "outcome") in ("cancelled", "cancel", "timeout", "unknown", "unsupported"):
|
|
||||||
return self._unknown(record, "战斗已取消、超时或结果不确定,等待核对")
|
|
||||||
data = value(result, "battle_data")
|
|
||||||
eligible = value(result, "outcome") in ("win", "loss")
|
|
||||||
if mode == "experimental":
|
|
||||||
eligible = (eligible and value(result, "experimental_settlement_eligible") is True
|
|
||||||
and value(result, "execution_mode") == "experimental" and value(result, "execution_status") == "completed"
|
|
||||||
and value(result, "supported") is True and value(result, "terminal") is True
|
|
||||||
and value(result, "approximate") is True and value(result, "faithful") is False and not value(result, "anomalies"))
|
|
||||||
else:
|
|
||||||
eligible = eligible and value(result, "settlement_eligible") is True and value(result, "faithful") is True and value(result, "approximate") is not True
|
|
||||||
if not eligible or not isinstance(data, dict) or type(data.get("win")) is not bool:
|
|
||||||
return self._unknown(record, "所选运行时未提供可结算的实际执行结果,未提交结算")
|
|
||||||
if data["win"] != (value(result, "outcome") == "win"):
|
|
||||||
return self._unknown(record, "运行结果与战果胜负不一致,未提交结算")
|
|
||||||
position = data.get("battlePosition")
|
|
||||||
if (not isinstance(position, dict) or {k: v for k, v in position.items() if v is not None}
|
|
||||||
!= {k: v for k, v in request["battle_position"].items() if v is not None}):
|
|
||||||
return self._unknown(record, "运行时战果定位不匹配,未提交结算")
|
|
||||||
# Keep all statistics and integrity records exactly as supplied.
|
|
||||||
self.journal.update(record, "runtime_complete", battle_data=data)
|
|
||||||
if not self.wait_for_battle_clock(record, request, result, data, battle_started, cancel):
|
|
||||||
return record["message"]
|
return record["message"]
|
||||||
|
data = record["battle_data"]
|
||||||
if not data["win"]:
|
if not data["win"]:
|
||||||
if not value(intent, "task_id") or value(intent, "battle_kind") == "passStage":
|
if not value(intent, "task_id") or value(intent, "battle_kind") == "passStage":
|
||||||
self._record(client, record, request["stage_id"], False, cancel=cancel)
|
self._record(client, record, request["stage_id"], False, cancel=cancel)
|
||||||
@@ -683,7 +892,7 @@ class BattleOrchestrator:
|
|||||||
"taskTypeId": str(value(intent, "task_type_id")), "removeIds": None, "battleData": data}
|
"taskTypeId": str(value(intent, "task_type_id")), "removeIds": None, "battleData": data}
|
||||||
else:
|
else:
|
||||||
path, payload = "battleService/battleEnd", {"battleData": data}
|
path, payload = "battleService/battleEnd", {"battleData": data}
|
||||||
self.journal.update(record, "settlement_pending", path=path)
|
self.journal.update(record, "settlement_pending", path=path, settlement_dispatched=True)
|
||||||
response = self._call(client, path, payload, cancel=cancel)
|
response = self._call(client, path, payload, cancel=cancel)
|
||||||
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response), settlement_confirmed=True,
|
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response), settlement_confirmed=True,
|
||||||
reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
||||||
@@ -700,6 +909,11 @@ class BattleOrchestrator:
|
|||||||
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
|
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
|
||||||
self.journal.finish(snapshot, record, "win", label + ",结算接口已确认;后续进度以服务器快照核对")
|
self.journal.finish(snapshot, record, "win", label + ",结算接口已确认;后续进度以服务器快照核对")
|
||||||
return label + ",已确认对应结算"
|
return label + ",已确认对应结算"
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
if not record.get("settlement_confirmed"):
|
||||||
|
self.journal.update(record, "waiting_for_battle_clock", path=record["start_path"],
|
||||||
|
settlement_dispatched=False, resume_clock_ready=True)
|
||||||
|
return "策略已停止,保存的战果将在重新开启后续交"
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
self._unknown(record, "任务 / 战斗请求或运行未确认;禁止自动重试", error_type=type(error).__name__)
|
self._unknown(record, "任务 / 战斗请求或运行未确认;禁止自动重试", error_type=type(error).__name__)
|
||||||
raise
|
raise
|
||||||
@@ -739,12 +953,17 @@ class BattleOrchestrator:
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
def _record(self, client, record, stage, win, *, cancel=None):
|
def _record(self, client, record, stage, win, *, cancel=None):
|
||||||
self.journal.update(record, "record_pending")
|
phase = record["phase"]
|
||||||
|
self.journal.update(record, "record_pending", record_dispatched=True, record_result=win)
|
||||||
try:
|
try:
|
||||||
self._call(client, "battleService/recordBattleResult", {"stageId": str(stage), "cityId": str(stage)[1:2], "result": int(win)}, cancel=cancel)
|
response = self._call(client, "battleService/recordBattleResult", {"stageId": str(stage), "cityId": str(stage)[1:2], "result": int(win)}, cancel=cancel)
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
self.journal.update(record, phase, record_dispatched=False)
|
||||||
|
raise
|
||||||
except Exception:
|
except Exception:
|
||||||
self.journal.update(record, "record_unknown", message="战果记录未确认,不能重放战斗")
|
self.journal.update(record, "record_unknown", message="战果记录未确认,不能重放战斗")
|
||||||
raise
|
raise
|
||||||
|
self.journal.update(record, "record_acknowledged", record_confirmed=True, record_response=gameplay_response(response))
|
||||||
|
|
||||||
def _unknown(self, record, message, **fields):
|
def _unknown(self, record, message, **fields):
|
||||||
phase = "record_unknown" if record["phase"] == "record_unknown" else "unknown"
|
phase = "record_unknown" if record["phase"] == "record_unknown" else "unknown"
|
||||||
|
|||||||
+55
-14
@@ -588,14 +588,43 @@ class Engine:
|
|||||||
or self._breakthrough_pending and now - self._breakthrough_pending_last_check >= 120))
|
or self._breakthrough_pending and now - self._breakthrough_pending_last_check >= 120))
|
||||||
return not self.demo and bool(automation or self._progression_pending() and now - self.last_pending_check >= 120)
|
return not self.demo and bool(automation or self._progression_pending() and now - self.last_pending_check >= 120)
|
||||||
|
|
||||||
def _resume_pending_task_clock(self):
|
def pending_battle_recovery(self):
|
||||||
|
"""Read-only recovery contract for desktop/Web pending guards."""
|
||||||
|
record = self.battle_journal.pending(self.snapshot) if self.snapshot is not None else None
|
||||||
|
status = self.battles.recovery_status(record, snapshot=self.snapshot)
|
||||||
|
if status["resumable"]:
|
||||||
|
if self.game_data is None and (record.get("source_task_type_id") or record.get("task_type_id")):
|
||||||
|
from .game_data import load_progression_data
|
||||||
|
self.game_data = load_progression_data()
|
||||||
|
if not self._intent_policy(record).enabled:
|
||||||
|
origin = ("自动扫荡" if record.get("kind") == "map_battle" else
|
||||||
|
"自动委托" if self._is_commission(record) else "自动主线")
|
||||||
|
return {"state": "blocked_policy", "resumable": False,
|
||||||
|
"message": "等待启用" + origin + "来源策略;已保留待核对战斗"}
|
||||||
|
return status
|
||||||
|
|
||||||
|
def _resume_pending_task_clock(self, *, running=None, generation=None):
|
||||||
record = self.battle_journal.pending(self.snapshot)
|
record = self.battle_journal.pending(self.snapshot)
|
||||||
if not self.auto or self._progression_cancel.is_set() or not self.battles.resumable_task_clock(record):
|
if not self.pending_battle_recovery()["resumable"]:
|
||||||
return ""
|
return ""
|
||||||
if record.get("kind") == "map_battle":
|
with self._progression_cancel_lock:
|
||||||
|
if (not (self.auto if running is None else running is True)
|
||||||
|
or generation is not None and generation != self._progression_cancel_generation):
|
||||||
|
return ""
|
||||||
|
# Web deliberately keeps auto=False. Only its current running intent
|
||||||
|
# may rearm an older cancellation; a newer Stop always wins.
|
||||||
|
if running is True and self._progression_cancel.is_set():
|
||||||
|
self._progression_cancel = threading.Event()
|
||||||
|
cancel = self._progression_cancel
|
||||||
|
if cancel.is_set():
|
||||||
|
return ""
|
||||||
|
if not record.get("task_id"):
|
||||||
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number", "stage_category",
|
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number", "stage_category",
|
||||||
"stage_id", "difficulty", "battle_kind", "team", "path")}
|
"stage_id", "difficulty", "battle_kind", "team", "path", "source_task_id", "source_task_type_id", "source_step_number")}
|
||||||
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._map_policy(), cancel=self._progression_cancel)
|
policy = self._intent_policy(intent)
|
||||||
|
if self.pending_battle_recovery()["state"] == "retry_local_runtime":
|
||||||
|
self._select_battle_runtime(record["battle_mode"])
|
||||||
|
return self.battles.resume_task_clock(self.client, self.snapshot, intent, policy, cancel=cancel)
|
||||||
pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None
|
pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None
|
||||||
if not pending or not isinstance(pending.get("intent"), dict):
|
if not pending or not isinstance(pending.get("intent"), dict):
|
||||||
return ""
|
return ""
|
||||||
@@ -607,8 +636,10 @@ class Engine:
|
|||||||
if intent.token in issued and issued[intent.token] != intent.to_dict():
|
if intent.token in issued and issued[intent.token] != intent.to_dict():
|
||||||
return ""
|
return ""
|
||||||
issued[intent.token] = intent.to_dict()
|
issued[intent.token] = intent.to_dict()
|
||||||
|
if self.pending_battle_recovery()["state"] == "retry_local_runtime":
|
||||||
|
self._select_battle_runtime(record["battle_mode"])
|
||||||
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._intent_policy(intent),
|
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._intent_policy(intent),
|
||||||
cancel=self._progression_cancel)
|
cancel=cancel)
|
||||||
|
|
||||||
def _battle_capability(self, intent):
|
def _battle_capability(self, intent):
|
||||||
try:
|
try:
|
||||||
@@ -648,7 +679,11 @@ class Engine:
|
|||||||
supported, reason = self._commission_offer_checks[key]
|
supported, reason = self._commission_offer_checks[key]
|
||||||
if not supported:
|
if not supported:
|
||||||
intent = replace(intent, block_reason=reason)
|
intent = replace(intent, block_reason=reason)
|
||||||
if (value(intent, "kind") in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle")
|
# Local battle preludes share the planner's cached input preflight.
|
||||||
|
prelude = value(intent, "task_id") and value(intent, "battle_kind") in battle_kinds and (
|
||||||
|
value(intent, "kind") == "progression_navigate" or
|
||||||
|
value(intent, "kind") == "progression_dialogue" and value(intent, "phase") == "before")
|
||||||
|
if (prelude or value(intent, "kind") in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle")
|
||||||
or self._is_farm(intent) and not self._is_sweep_intent(intent)) and not value(intent, "block_reason"):
|
or self._is_farm(intent) and not self._is_sweep_intent(intent)) and not value(intent, "block_reason"):
|
||||||
supported, reason = self._battle_capability(intent)
|
supported, reason = self._battle_capability(intent)
|
||||||
reasons[str(value(intent, "source_task_type_id") or value(intent, "task_type_id"))] = (supported, reason)
|
reasons[str(value(intent, "source_task_type_id") or value(intent, "task_type_id"))] = (supported, reason)
|
||||||
@@ -673,14 +708,15 @@ class Engine:
|
|||||||
stage_id=value(farm, "stage_id"), difficulty=value(farm, "difficulty"))
|
stage_id=value(farm, "stage_id"), difficulty=value(farm, "difficulty"))
|
||||||
reason = row.get("block_reason") or row.get("blocked_reason") or ""
|
reason = row.get("block_reason") or row.get("blocked_reason") or ""
|
||||||
if row.get("battle_kind") in battle_kinds:
|
if row.get("battle_kind") in battle_kinds:
|
||||||
supported, runtime_reason = reasons.get(str(row.get("task_type_id")),
|
supported, runtime_reason = reasons.get(str(row.get("task_type_id")), (None, ""))
|
||||||
(False, "战斗运行时能力尚未核对;配置存在不代表已支持实战"))
|
|
||||||
row["supported"] = bool(source_supported and supported and not reason)
|
|
||||||
reason = reason or runtime_reason
|
reason = reason or runtime_reason
|
||||||
|
row["supported"] = False if not source_supported or reason else supported
|
||||||
else:
|
else:
|
||||||
row["supported"] = bool(source_supported and not reason)
|
row["supported"] = bool(source_supported and not reason)
|
||||||
row["block_reason"] = row["blocked_reason"] = reason
|
row["block_reason"] = row["blocked_reason"] = reason
|
||||||
row["reason_kind"] = commission_reason_kind(reason)
|
row["reason_kind"] = "unchecked" if row["supported"] is None else commission_reason_kind(reason)
|
||||||
|
if row["supported"] is None and row.get("category") == "mainline" and not self.progression_policy.enabled:
|
||||||
|
row.setdefault("status", "自动主线策略未启用")
|
||||||
return rows, adjusted
|
return rows, adjusted
|
||||||
|
|
||||||
def _battle_request(self, snapshot, intent, policy, request):
|
def _battle_request(self, snapshot, intent, policy, request):
|
||||||
@@ -1331,7 +1367,10 @@ class Engine:
|
|||||||
|
|
||||||
@single_flight
|
@single_flight
|
||||||
@account_serial
|
@account_serial
|
||||||
def poll(self, *, hatch_only=False, defer_hatch=False):
|
def poll(self, *, hatch_only=False, defer_hatch=False, resume_pending=None):
|
||||||
|
if resume_pending is not None and type(resume_pending) is not bool:
|
||||||
|
raise ValueError("resume_pending must be a boolean or None")
|
||||||
|
recovery_generation = self._progression_cancel_generation
|
||||||
self.last_executed = False
|
self.last_executed = False
|
||||||
settled = False
|
settled = False
|
||||||
if self.demo:
|
if self.demo:
|
||||||
@@ -1355,7 +1394,7 @@ class Engine:
|
|||||||
if self._progression_pending():
|
if self._progression_pending():
|
||||||
self.pending_hatches = []
|
self.pending_hatches = []
|
||||||
pending_map = (self.battle_journal.pending(self.snapshot) or {}).get("kind") == "map_battle"
|
pending_map = (self.battle_journal.pending(self.snapshot) or {}).get("kind") == "map_battle"
|
||||||
recovered = self._resume_pending_task_clock() if not self.demo else ""
|
recovered = self._resume_pending_task_clock(running=resume_pending, generation=recovery_generation) if not self.demo else ""
|
||||||
if recovered:
|
if recovered:
|
||||||
self.last_executed = True
|
self.last_executed = True
|
||||||
if not self.battle_journal.pending(self.snapshot):
|
if not self.battle_journal.pending(self.snapshot):
|
||||||
@@ -1364,7 +1403,9 @@ class Engine:
|
|||||||
self.stage_cache.get(self.snapshot, refresh=True)
|
self.stage_cache.get(self.snapshot, refresh=True)
|
||||||
return self.snapshot, self.plans(), recovered
|
return self.snapshot, self.plans(), recovered
|
||||||
pending = self.battle_journal.pending(self.snapshot) or {}
|
pending = self.battle_journal.pending(self.snapshot) or {}
|
||||||
return self.snapshot, [], message + ";" + (pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作") + ";后台每2分钟自动核对"
|
recovery = self.pending_battle_recovery()
|
||||||
|
detail = recovery["message"] or pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作"
|
||||||
|
return self.snapshot, [], message + ";" + detail
|
||||||
explore_pending = self.explore_planner.pending(self.snapshot)
|
explore_pending = self.explore_planner.pending(self.snapshot)
|
||||||
if explore_pending or self._breakthrough_pending:
|
if explore_pending or self._breakthrough_pending:
|
||||||
self.pending_hatches = []
|
self.pending_hatches = []
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""Offline presentation regressions: input support never predicts a victory."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionPolicy
|
||||||
|
from ranch_web.policies import default_config
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
|
||||||
|
|
||||||
|
class BattleCapabilityPresentationTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.runtime = Mock()
|
||||||
|
self.runtime.inspect.return_value = {"supported": True, "settlement_eligible": True,
|
||||||
|
"faithful": True, "approximate": False}
|
||||||
|
self.runtime.run.side_effect = AssertionError("presentation must not simulate")
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.call.side_effect = AssertionError("offline: no game calls")
|
||||||
|
self.client.snapshot.side_effect = AssertionError("offline: no snapshot requests")
|
||||||
|
self.step = {"statusType": "passStage", "statusValue": {"stage": "0216", "level": "1"},
|
||||||
|
"position": "city1_wild_stage0216_level1", "story": "before", "afterStory": "after"}
|
||||||
|
self.data = ProgressionData({"task_info": {"1002013": {"type": 1, "name": "offline mainline",
|
||||||
|
"steps": [self.step]}}, "scripts": {"before": {"supported": True}, "after": {"supported": True}},
|
||||||
|
"game_setting": {"cityInfo": {"1": {"name": "offline city"}}},
|
||||||
|
"stage_info": {"0216": {"city": 1, "cost": {"ti": 6},
|
||||||
|
"level": {"1": {"cost": 0, "battle": {"fixture": True}}}}}})
|
||||||
|
self.engine = Engine(Catalog(), self.client, game_data=self.data, battle_runtime=self.runtime)
|
||||||
|
self.engine.progression_policy = ProgressionPolicy(enabled=True)
|
||||||
|
self.engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
|
||||||
|
self.engine.snapshot = Snapshot({"master": {"id": 1, "level": 20, "ti": 100, "money": 1000},
|
||||||
|
"currentTasks": [{"id": 11, "typeId": "1002013", "curStep": 1, "stepValue": 0}],
|
||||||
|
"monsters": [{"id": 101, "typeId": 1001010, "mode": 2, "process": 3, "level": 20}],
|
||||||
|
"teams": [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [101]}],
|
||||||
|
"items": [], "stacks": [], "rooms": [],
|
||||||
|
"history": {"unlockCity": {"1": True}, "unlockStage": {"0216": [1]}}})
|
||||||
|
self.addCleanup(self.assert_read_only)
|
||||||
|
|
||||||
|
def assert_read_only(self):
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.client.snapshot.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
def refresh(self):
|
||||||
|
self.engine._refresh_progression_cache(force=True)
|
||||||
|
self.assertEqual(self.engine._progression_error, "")
|
||||||
|
return next(row for row in self.engine.progression_rows() if row["task_type_id"] == "1002013")
|
||||||
|
|
||||||
|
def mainline_view(self):
|
||||||
|
# Rendering consumes prepared DTOs; it must never inspect or plan.
|
||||||
|
with patch.object(self.engine, "_battle_capability", side_effect=AssertionError("view inspection")), \
|
||||||
|
patch.object(self.engine, "_refresh_progression_cache", side_effect=AssertionError("view planning")):
|
||||||
|
return build_view(self.engine, "mainline", default_config())
|
||||||
|
|
||||||
|
def test_navigation_and_before_story_reuse_positive_preflight_without_a_false_block(self):
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertEqual(self.engine._progression_intents[0].kind, "progression_navigate")
|
||||||
|
self.assertTrue(row["supported"])
|
||||||
|
self.assertEqual((row["block_reason"], row["blocked_reason"], row["reason_kind"]), ("", "", "ready"))
|
||||||
|
self.assertIn("前往任务位置", row["next_action"])
|
||||||
|
self.refresh()
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
self.assertEqual(self.mainline_view()["rows"][0]["support"], "已支持")
|
||||||
|
_, account = self.engine.progression_planner._account(self.engine.snapshot)
|
||||||
|
account["position"] = self.step["position"]
|
||||||
|
row = self.refresh()
|
||||||
|
action = self.engine._progression_intents[0]
|
||||||
|
self.assertEqual((action.kind, action.phase), ("progression_dialogue", "before"))
|
||||||
|
self.assertIs(row["supported"], True)
|
||||||
|
self.assertEqual(row["blocked_reason"], "")
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
|
||||||
|
def test_disabled_mainline_is_neutral_without_execution_intents(self):
|
||||||
|
self.engine.progression_policy.enabled = False
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertEqual(self.engine._progression_intents, [])
|
||||||
|
self.assertIsNone(row["supported"])
|
||||||
|
self.assertEqual((row["blocked_reason"], row["reason_kind"]), ("", "unchecked"))
|
||||||
|
self.assertEqual(row["status"], "自动主线策略未启用")
|
||||||
|
self.assertIn("前往任务位置", row["next_action"])
|
||||||
|
view = self.mainline_view()
|
||||||
|
self.assertEqual(view["rows"][0]["support"], "支持状态未确认")
|
||||||
|
self.assertNotIn("模型尚未支持", str(view))
|
||||||
|
self.engine.progression_policy.enabled = True
|
||||||
|
self.assertIs(self.refresh()["supported"], True)
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
|
||||||
|
def test_real_unsupported_inputs_keep_their_reason_even_while_paused(self):
|
||||||
|
reason = "Unsupported monster controller: fixture"
|
||||||
|
self.runtime.inspect.return_value.update(supported=False, reasons=[reason])
|
||||||
|
for enabled in (True, False):
|
||||||
|
with self.subTest(enabled=enabled):
|
||||||
|
self.engine.progression_policy.enabled = enabled
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertIs(row["supported"], False)
|
||||||
|
self.assertEqual((row["blocked_reason"], row["reason_kind"]), (reason, "model_unsupported"))
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
|
||||||
|
def test_resource_policy_and_unchecked_rows_keep_truthful_reasons_without_inspections(self):
|
||||||
|
for field, invalid, word in (("teams", [], "队"), ("ti", 0, "体力")):
|
||||||
|
with self.subTest(field=field):
|
||||||
|
target = self.engine.snapshot.raw if field == "teams" else self.engine.snapshot.raw["master"]
|
||||||
|
original = target[field]
|
||||||
|
target[field] = invalid
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertIs(row["supported"], False)
|
||||||
|
self.assertIn(word, row["blocked_reason"])
|
||||||
|
self.assertNotEqual(row["reason_kind"], "model_unsupported")
|
||||||
|
target[field] = original
|
||||||
|
source = [{"task_type_id": str(i), "battle_kind": "passStage", "supported": supported,
|
||||||
|
"block_reason": reason} for i, (supported, reason) in enumerate((
|
||||||
|
(False, ""), (True, "自动对话未启用"), (False, "前置任务尚未完成")))]
|
||||||
|
rows, _ = self.engine._overlay_battle_capabilities(deepcopy(source), [])
|
||||||
|
self.assertTrue(all(row["supported"] is False for row in rows))
|
||||||
|
self.assertEqual([row["blocked_reason"] for row in rows], [row["block_reason"] for row in source])
|
||||||
|
rows = [{"task_type_id": str(i), "state": state, "category": "mainline", "battle_kind": "passStage",
|
||||||
|
"supported": state == "received"} for i, state in enumerate(["finished", "locked", "received"] * 400)]
|
||||||
|
rows, _ = self.engine._overlay_battle_capabilities(rows, [])
|
||||||
|
self.assertTrue(all(row["block_reason"] == "" and row["reason_kind"] != "model_unsupported" for row in rows))
|
||||||
|
self.assertTrue(all(row["supported"] is None and row["reason_kind"] == "unchecked"
|
||||||
|
for row in rows if row["state"] == "received"))
|
||||||
|
self.runtime.inspect.assert_not_called()
|
||||||
|
|
||||||
|
def test_inspect_support_does_not_relabel_a_recorded_loss_as_unsupported_or_win(self):
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertIs(row["supported"], True)
|
||||||
|
self.engine._progression_records = [{"task_type_id": "1002013", "task_id": 11,
|
||||||
|
"battle_kind": "passStage", "battle_mode": "experimental", "outcome": "loss"}]
|
||||||
|
before = deepcopy(self.engine._progression_records)
|
||||||
|
view = build_view(self.engine, "battles", default_config())
|
||||||
|
self.assertEqual(view["rows"][0]["outcome"], "loss")
|
||||||
|
self.assertIn("打不过", view["rows"][0]["outcome_label"])
|
||||||
|
self.assertEqual(self.engine._progression_records, before)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
"""Interrupted combat recovery; all server calls and worker results are offline fakes."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.battles import BattleJournal, BattleOrchestrator
|
||||||
|
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime, fixture, intent, policy
|
||||||
|
from ranch_assistant.tests.test_core import workspace_temp
|
||||||
|
|
||||||
|
|
||||||
|
class BattleRecoveryTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.folder = self.enterContext(workspace_temp())
|
||||||
|
self.path = self.folder / "journal.json"
|
||||||
|
self.catalog, self.snapshot = fixture()
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"id": 51, "typeId": "1002013", "curStep": 1}]
|
||||||
|
self.runtime = ExperimentalRuntime()
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.call.side_effect = lambda path, payload: {"resCode": 0, "triggerEvent": False, "reward": {}}
|
||||||
|
self.runner = BattleOrchestrator(self.catalog, BattleJournal(self.path), self.runtime)
|
||||||
|
self.action = intent(kind="stage_battle", source_task_id=51, source_task_type_id="1002013", source_step_number=1)
|
||||||
|
self.policy = policy(battle_mode="experimental")
|
||||||
|
|
||||||
|
def paths(self):
|
||||||
|
return [call.args[0] for call in self.client.call.call_args_list]
|
||||||
|
|
||||||
|
def restart(self):
|
||||||
|
self.runner = BattleOrchestrator(self.catalog, BattleJournal(self.path), self.runtime)
|
||||||
|
|
||||||
|
def test_generation_cancel_inside_worker_retries_saved_combat_without_second_entry(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
original = self.runtime._run
|
||||||
|
captured = []
|
||||||
|
def interrupted(request, *, cancel_event):
|
||||||
|
captured.append(deepcopy(request))
|
||||||
|
cancel_event.set()
|
||||||
|
return {"outcome": "cancelled", "execution_mode": "experimental", "execution_status": "cancelled",
|
||||||
|
"faithful": False, "approximate": True, "terminal": False, "terminal_reason": "worker_cancelled"}
|
||||||
|
self.runtime.run.side_effect = interrupted
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart"])
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "retry_local_runtime")
|
||||||
|
self.snapshot.raw["monsters"][0]["level"] = 999
|
||||||
|
retried = []
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
retried.append(deepcopy(request))
|
||||||
|
return original(request, cancel_event=cancel_event)
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(retried[0], record["combat_request"])
|
||||||
|
self.assertNotIn("level", retried[0]["roster"]["monsters"][0])
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(len(self.paths()), 3)
|
||||||
|
|
||||||
|
def test_cancel_at_completed_result_preserves_it_without_resimulation(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
result = self.runtime._run(request, cancel_event=cancel_event)
|
||||||
|
cancel_event.set()
|
||||||
|
return result
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertTrue(record["battle_data"]["win"])
|
||||||
|
self.assertTrue(self.runner.resumable_task_clock(record))
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_cancel_during_wait_resumes_saved_stage_battle_without_new_worker(self):
|
||||||
|
self.runner.clock = lambda: 0
|
||||||
|
cancel = threading.Event()
|
||||||
|
cancel.wait = Mock(side_effect=lambda timeout: cancel.set() or True)
|
||||||
|
self.runtime.run.side_effect = lambda request, cancel_event: self.runtime._run(request, cancel_event=cancel_event) | {
|
||||||
|
"requires_realtime_wait": True, "model_elapsed_ms": 10000}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
|
||||||
|
self.runner.journal.update(record, record["phase"], battle_ready_at=1)
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_save_combat_request_normalizes_comma_lineup_without_losing_slots_or_inputs(self):
|
||||||
|
from ranch_assistant.battle_quick import simulate_quick
|
||||||
|
from ranch_assistant.tests.test_battle_simulator import monster, request
|
||||||
|
for members in ([100001, 0, 100002], "100001,0,100002"):
|
||||||
|
with self.subTest(members=members):
|
||||||
|
combat = request(players=[monster(mid=100001), monster(mid=100002)], master_level=62,
|
||||||
|
battle_mode="experimental")
|
||||||
|
combat["roster"]["teams"][0]["monsters"] = members
|
||||||
|
combat["roster"]["master"]["sessionKey"] = "credential-canary"
|
||||||
|
combat["roster"]["monsters"][0]["nicName"] = "nickname-canary"
|
||||||
|
combat["roster"]["monsters"][0]["token"] = "credential-canary"
|
||||||
|
before = deepcopy(combat)
|
||||||
|
saved = self.runner.save_combat_request({}, combat)["combat_request"]
|
||||||
|
self.assertEqual(saved["roster"]["teams"][0]["monsters"], [100001, 0, 100002])
|
||||||
|
self.assertEqual([row["id"] for row in saved["roster"]["monsters"]], [100001, 100002])
|
||||||
|
normalized = deepcopy(before)
|
||||||
|
normalized["roster"]["teams"][0]["monsters"] = [100001, 0, 100002]
|
||||||
|
self.assertEqual(simulate_quick(saved), simulate_quick(normalized))
|
||||||
|
self.assertNotIn("canary", json.dumps(saved))
|
||||||
|
self.assertEqual(combat, before)
|
||||||
|
|
||||||
|
def test_combat_input_is_durable_before_start_and_original_profile_survives_timeout(self):
|
||||||
|
self.runner.request_builder = lambda snapshot, action, chosen, request: request | {"damage_profile": "client_v4_x10"}
|
||||||
|
original = self.client.call.side_effect
|
||||||
|
def call(path, payload):
|
||||||
|
if path.endswith("stageStart"):
|
||||||
|
pending = BattleJournal(self.path).pending(self.snapshot)
|
||||||
|
self.assertEqual(pending["combat_request"]["damage_profile"], "client_v4_x10")
|
||||||
|
self.assertFalse(pending["settlement_dispatched"])
|
||||||
|
return original(path, payload)
|
||||||
|
self.client.call.side_effect = call
|
||||||
|
self.runtime.run.side_effect = lambda *args, **kwargs: {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal": False, "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"faithful": False, "approximate": True, "damage_profile": None}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.pending(self.snapshot)["combat_request"]["damage_profile"], "client_v4_x10")
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "retry_local_runtime")
|
||||||
|
|
||||||
|
def test_settlement_lost_reply_is_never_replayed_even_with_saved_inputs(self):
|
||||||
|
def call(path, payload):
|
||||||
|
if path.endswith("battleEnd"):
|
||||||
|
raise TimeoutError()
|
||||||
|
return {"resCode": 0, "triggerEvent": False}
|
||||||
|
self.client.call.side_effect = call
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "blocked")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
|
||||||
|
|
||||||
|
def test_cancel_before_settlement_dispatch_remains_resumable(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
update = self.runner.journal.update
|
||||||
|
def stop(record, phase, **fields):
|
||||||
|
update(record, phase, **fields)
|
||||||
|
if phase == "settlement_pending":
|
||||||
|
cancel.set()
|
||||||
|
self.runner.journal.update = stop
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertFalse(record["settlement_dispatched"])
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_preaccept_retry_requires_current_offer_day_and_never_reopens_entry(self):
|
||||||
|
self.action.update(source_task_id=0, source_task_type_id="4001004", source_step_number=0)
|
||||||
|
self.snapshot.raw["history"].update(loopTask={"1": ["4001004"]}, loopTaskTime=self.snapshot.now)
|
||||||
|
self.runtime.run.side_effect = lambda *args, **kwargs: {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal": False, "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"faithful": False, "approximate": True}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(self.runner.recovery_status(record, snapshot=self.snapshot)["state"], "retry_local_runtime")
|
||||||
|
self.snapshot.raw["history"]["loopTaskTime"] -= 86400
|
||||||
|
self.assertEqual(self.runner.recovery_status(record, snapshot=self.snapshot)["state"], "abandon_stage")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.client.call.call_args.args[1]["result"], 0)
|
||||||
|
|
||||||
|
def test_local_retry_is_bounded_then_uses_failure_exit_without_another_worker(self):
|
||||||
|
self.runtime.run.side_effect = lambda *args, **kwargs: {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal": False, "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"faithful": False, "approximate": True}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.pending(self.snapshot)["runtime_recovery_attempts"], 1)
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "abandon_stage")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 2)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_stage_battle_with_confirmed_settlement_restart_only_finishes_record(self):
|
||||||
|
with patch.object(self.runner, "_record", side_effect=SystemExit("crash after durable settlement reply")):
|
||||||
|
with self.assertRaises(SystemExit):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "resume_result")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_stop_during_recovery_settlement_keeps_ack_and_resumes_only_optional_record(self):
|
||||||
|
initial_cancel = threading.Event()
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
result = self.runtime._run(request, cancel_event=cancel_event)
|
||||||
|
cancel_event.set()
|
||||||
|
return result
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=initial_cancel)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart"])
|
||||||
|
recovery_cancel = threading.Event()
|
||||||
|
def settlement_ack_after_stop(path, payload):
|
||||||
|
if path == "battleService/battleEnd":
|
||||||
|
recovery_cancel.set()
|
||||||
|
return {"resCode": 0, "reward": {"money": 11}}
|
||||||
|
self.client.call.side_effect = settlement_ack_after_stop
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=recovery_cancel)
|
||||||
|
self.assertTrue(recovery_cancel.is_set())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(record["phase"], "settlement_acknowledged")
|
||||||
|
self.assertTrue(record["settlement_confirmed"])
|
||||||
|
self.assertFalse(record["record_dispatched"])
|
||||||
|
self.assertIsNot(record.get("record_confirmed"), True)
|
||||||
|
self.assertEqual(record["response"], {"resCode": 0, "reward": {"money": 11}})
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=recovery_cancel)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(len(self.paths()), 3)
|
||||||
|
|
||||||
|
def legacy_timeout(self, **changes):
|
||||||
|
record = self.runner.journal.begin(self.snapshot, self.action)
|
||||||
|
self.runner.journal.update(record, "unknown", path="stageService/stageStart", start_path="stageService/stageStart",
|
||||||
|
start_response={"resCode": 0, "stageEvent": None, "triggerEvent": False},
|
||||||
|
battle_mode="experimental", execution_mode="experimental", execution_status="timed_out", terminal=False,
|
||||||
|
terminal_reason="worker_wall_clock_limit", message="战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self.runner.journal.update(record, "unknown", **changes)
|
||||||
|
return record
|
||||||
|
|
||||||
|
def test_legacy_worker_timeout_uses_original_failure_exit_once(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
before = deepcopy(self.snapshot.raw)
|
||||||
|
self.restart()
|
||||||
|
status = self.runner.recovery_status(self.runner.pending(self.snapshot), snapshot=self.snapshot)
|
||||||
|
self.assertEqual(status["state"], "abandon_stage")
|
||||||
|
self.assertIn("原始战斗输入", status["message"])
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.client.call.call_args.args[1], {"stageId": "0101", "cityId": "1", "result": 0})
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
done = self.runner.journal.records(self.snapshot)[0]
|
||||||
|
self.assertEqual(done["outcome"], "abandoned")
|
||||||
|
self.assertTrue(done["record_confirmed"])
|
||||||
|
self.assertNotIn("battle_data", done)
|
||||||
|
self.assertEqual(self.snapshot.raw, before)
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(len(self.paths()), 1)
|
||||||
|
|
||||||
|
def test_lost_failure_response_stays_pending_and_is_never_replayed(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
self.client.call.side_effect = TimeoutError("lost failure acknowledgement")
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(record["phase"], "record_unknown")
|
||||||
|
self.assertTrue(record["record_dispatched"])
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "blocked")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_real_preaccept_source_zero_legacy_timeout_exits_without_task_or_offer(self):
|
||||||
|
self.action.update(stage_id="0102", task_type_id="", source_task_id=0,
|
||||||
|
source_task_type_id="4001004", source_step_number=0, stage_category=None)
|
||||||
|
self.legacy_timeout()
|
||||||
|
before = deepcopy(self.snapshot.raw)
|
||||||
|
self.restart()
|
||||||
|
status = self.runner.recovery_status(self.runner.pending(self.snapshot), snapshot=self.snapshot.raw)
|
||||||
|
self.assertEqual(status["state"], "abandon_stage")
|
||||||
|
self.assertIn("旧记录缺少原始战斗输入", status["message"])
|
||||||
|
self.assertNotIn("来源委托已变化", status["message"])
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.client.call.call_args.args[1], {"stageId": "0102", "cityId": "1", "result": 0})
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.assertEqual(self.snapshot.raw, before)
|
||||||
|
self.assertEqual(self.runner.journal.role(self.snapshot)["losses"], 0)
|
||||||
|
self.assertEqual(self.runner.journal.records(self.snapshot)[0]["outcome"], "abandoned")
|
||||||
|
|
||||||
|
def test_failure_acknowledged_before_crash_finishes_locally_without_second_record(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
finish = self.runner.journal.finish
|
||||||
|
self.runner.journal.finish = Mock(side_effect=SystemExit("crash after durable failure reply"))
|
||||||
|
with self.assertRaises(SystemExit):
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.runner.journal.finish = finish
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "finish_abandonment")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_unconfirmed_start_or_changed_source_or_settlement_attempt_blocks_failure_exit(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
for changes in ({"start_response": None}, {"settlement_dispatched": True},
|
||||||
|
{"path": "battleService/battleEnd"}, {"source_task_id": 999},
|
||||||
|
{"terminal_reason": "unclassified_failure"}):
|
||||||
|
with self.subTest(changes=changes):
|
||||||
|
original = deepcopy(self.runner.pending(self.snapshot))
|
||||||
|
self.runner.journal.update(self.runner.pending(self.snapshot), "unknown", **changes)
|
||||||
|
status = self.runner.recovery_status(self.runner.pending(self.snapshot), snapshot=self.snapshot)
|
||||||
|
self.assertEqual(status["state"], "blocked")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.runner.journal.role(self.snapshot)["records"][-1] = original
|
||||||
|
self.runner.journal.save()
|
||||||
|
self.assertIsNotNone(self.runner.pending(self.snapshot))
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class EngineBattleRecoveryTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
from ranch_assistant.engine import Engine, demo_snapshot
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionPolicy
|
||||||
|
self.folder = self.enterContext(workspace_temp())
|
||||||
|
self.catalog = Catalog()
|
||||||
|
self.raw = deepcopy(demo_snapshot(self.catalog).raw)
|
||||||
|
self.raw["currentTasks"] = [{"id": 71, "typeId": "1002013", "curStep": 1}]
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw))
|
||||||
|
self.client.call.return_value = {"resCode": 0, "triggerEvent": False}
|
||||||
|
self.engine = Engine(self.catalog, self.client, self.folder / "purchase.json",
|
||||||
|
game_data=ProgressionData({"task_info": {}, "stage_info": {}, "game_setting": {}}),
|
||||||
|
experimental_runtime=ExperimentalRuntime())
|
||||||
|
self.engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
|
||||||
|
self.engine.progression_policy = ProgressionPolicy(enabled=True, battle_mode="experimental")
|
||||||
|
self.engine.snapshot = Snapshot(deepcopy(self.raw))
|
||||||
|
self.engine.master_sync.settle = Mock()
|
||||||
|
self.action = intent(kind="stage_battle", stage_id="0102", task_type_id="", source_task_id=0,
|
||||||
|
source_task_type_id="4001004", source_step_number=0)
|
||||||
|
self.record = self.engine.battle_journal.begin(self.engine.snapshot, self.action)
|
||||||
|
self.engine.battle_journal.update(self.record, "unknown", path="stageService/stageStart", start_path="stageService/stageStart",
|
||||||
|
start_response={"resCode": 0, "stageEvent": None, "triggerEvent": False},
|
||||||
|
battle_mode="experimental", execution_mode="experimental", execution_status="timed_out", terminal=False,
|
||||||
|
terminal_reason="worker_wall_clock_limit")
|
||||||
|
self.engine.auto = False
|
||||||
|
|
||||||
|
def test_disabled_cold_commission_origin_blocks_until_quest_policy_is_enabled(self):
|
||||||
|
self.engine.game_data = None
|
||||||
|
self.engine.quest_policy.enabled = False
|
||||||
|
self.engine.daily_policy.enabled = True
|
||||||
|
before = self.engine.battle_journal.path.read_bytes()
|
||||||
|
record = deepcopy(self.record)
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "blocked_policy")
|
||||||
|
self.assertFalse(status["resumable"])
|
||||||
|
self.assertIn("等待启用自动委托来源策略", status["message"])
|
||||||
|
self.assertEqual(self.engine.battle_journal.path.read_bytes(), before)
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.engine.battle_journal.pending(self.engine.snapshot), record)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertFalse(self.engine.quest_policy.enabled)
|
||||||
|
self.assertTrue(self.engine.daily_policy.enabled)
|
||||||
|
self.engine.quest_policy.enabled = True
|
||||||
|
self.assertTrue(self.engine.pending_battle_recovery()["resumable"])
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertEqual(self.client.call.call_args.args[0], "battleService/recordBattleResult")
|
||||||
|
|
||||||
|
def test_enabled_cold_commission_origin_does_not_require_mainline_policy(self):
|
||||||
|
self.engine.game_data = None
|
||||||
|
self.engine.progression_policy.enabled = False
|
||||||
|
self.engine.quest_policy.enabled = True
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "abandon_stage")
|
||||||
|
self.assertTrue(status["resumable"])
|
||||||
|
self.assertIsNotNone(self.engine.game_data)
|
||||||
|
self.assertTrue(self.engine._is_commission(self.record))
|
||||||
|
self.assertFalse(self.engine.progression_policy.enabled)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_disabled_map_and_mainline_origins_name_their_policies(self):
|
||||||
|
self.engine.progression_policy.enabled = False
|
||||||
|
self.engine.sweep_policy.enabled = False
|
||||||
|
for kind, source_id, source_type, source_step, label in (
|
||||||
|
("map_battle", 0, "", 0, "自动扫荡"),
|
||||||
|
("stage_battle", 71, "1002013", 1, "自动主线")):
|
||||||
|
with self.subTest(kind=kind):
|
||||||
|
self.engine.game_data = None
|
||||||
|
self.engine.battle_journal.update(self.record, "waiting_for_battle_clock", kind=kind,
|
||||||
|
source_task_id=source_id, source_task_type_id=source_type, source_step_number=source_step,
|
||||||
|
battle_data={"win": True}, execution_status="completed", terminal=True,
|
||||||
|
experimental_settlement_eligible=True, approximate=True, faithful=False, resume_clock_ready=True)
|
||||||
|
self.assertTrue(self.engine.battles.recovery_status(self.record, snapshot=self.engine.snapshot)["resumable"])
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "blocked_policy")
|
||||||
|
self.assertFalse(status["resumable"])
|
||||||
|
self.assertIn("等待启用" + label + "来源策略", status["message"])
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_web_explicit_running_resumes_preaccept_failure_while_auto_stays_false(self):
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
self.engine.poll(resume_pending=False)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertTrue(self.engine.pending_battle_recovery()["resumable"])
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertFalse(self.engine.auto)
|
||||||
|
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertEqual(self.client.call.call_args.args, ("battleService/recordBattleResult", {"stageId": "0102", "cityId": "1", "result": 0}))
|
||||||
|
self.assertEqual(self.engine.snapshot.raw["currentTasks"], self.raw["currentTasks"])
|
||||||
|
self.assertFalse(self.engine._progression_pending())
|
||||||
|
self.engine._require_no_battle() # Other selected strategies are no longer blocked.
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_new_stop_during_snapshot_read_wins_over_old_running_argument(self):
|
||||||
|
read = self.client.snapshot.side_effect
|
||||||
|
def read_then_stop():
|
||||||
|
result = read()
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
return result
|
||||||
|
self.client.snapshot.side_effect = read_then_stop
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertTrue(self.engine._progression_cancel.is_set())
|
||||||
|
self.assertIsNotNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.client.snapshot.side_effect = read
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_guard_is_read_only_and_unknown_settlement_is_blocked(self):
|
||||||
|
self.engine.battle_journal.update(self.record, "unknown", path="battleService/battleEnd", settlement_dispatched=True)
|
||||||
|
before = self.engine.battle_journal.path.read_bytes()
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "blocked")
|
||||||
|
self.assertFalse(status["resumable"])
|
||||||
|
self.assertEqual(self.engine.battle_journal.path.read_bytes(), before)
|
||||||
|
record = deepcopy(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.engine.battle_journal.pending(self.engine.snapshot), record)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertIsNotNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
|
||||||
|
def test_engine_generation_cancel_in_worker_resumes_single_started_entry(self):
|
||||||
|
from ranch_assistant.model import Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionIntent
|
||||||
|
self.engine.battle_journal.finish(self.engine.snapshot, self.record, "cancelled")
|
||||||
|
self.raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [900]}]
|
||||||
|
self.raw["history"]["unlockStage"] = {"0102": [1]}
|
||||||
|
self.raw["history"].update(loopTask={"1": ["4001004"]}, loopTaskTime=self.engine.snapshot.now)
|
||||||
|
self.engine.snapshot = Snapshot(deepcopy(self.raw))
|
||||||
|
self.engine.battles.catalog = fixture()[0]
|
||||||
|
self.engine.game_data.stages["0102"] = {"level": {"1": {"battle": {"fixture": True}}}}
|
||||||
|
self.engine._battle_catalog_ready = True
|
||||||
|
self.engine._ensure_progression()
|
||||||
|
scope, _ = self.engine.progression_planner._account(self.engine.snapshot)
|
||||||
|
action = ProgressionIntent(kind="stage_battle", description="offline preaccept farming", stage_id="0102",
|
||||||
|
difficulty=1, battle_kind="ordinary_stage", path="stageService/stageStart", team="teamA",
|
||||||
|
battle_mode="experimental", account_key=scope, token="offline-fixture", source_task_type_id="4001004")
|
||||||
|
self.engine.progression_planner._issued[action.token] = action.to_dict()
|
||||||
|
self.engine._select_battle_runtime("experimental")
|
||||||
|
runtime = self.engine.battles.runtime
|
||||||
|
def interrupted(request, *, cancel_event):
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
return {"outcome": "cancelled", "execution_mode": "experimental", "execution_status": "cancelled",
|
||||||
|
"faithful": False, "approximate": True, "terminal": False, "terminal_reason": "worker_cancelled"}
|
||||||
|
runtime.run.side_effect = interrupted
|
||||||
|
self.engine.battles.run(self.client, self.engine.snapshot, action,
|
||||||
|
self.engine.progression_policy, cancel=self.engine._progression_cancel)
|
||||||
|
self.assertEqual(self.engine._progression_cancel_generation, 1)
|
||||||
|
self.assertEqual(self.engine.pending_battle_recovery()["state"], "retry_local_runtime")
|
||||||
|
runtime.run.side_effect = runtime._run
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.assertEqual([call.args[0] for call in self.client.call.call_args_list],
|
||||||
|
["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(runtime.run.call_count, 2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""Bounded, offline regressions for the fixed battle worker's stdin transport."""
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from ranch_assistant import battle_simulator as simulator
|
||||||
|
from ranch_assistant.battle_quick import simulate_quick
|
||||||
|
from ranch_assistant.tests.test_battle_simulator import request
|
||||||
|
|
||||||
|
|
||||||
|
# Delay the real worker's first read past several parent polling quanta.
|
||||||
|
SLOW_WORKER = """
|
||||||
|
import runpy, sys, time
|
||||||
|
time.sleep(.2)
|
||||||
|
sys.argv = ['ranch_assistant.battle_simulator', '--worker']
|
||||||
|
runpy.run_module('ranch_assistant.battle_simulator', run_name='__main__')
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class PartialFirstWrite:
|
||||||
|
"""Reproduce POSIX's partial-write/None-retry behavior on every platform.
|
||||||
|
|
||||||
|
The child and its pipes are real. A tiny first write followed by a timeout
|
||||||
|
leaves stdin open; a retry without input never resumes that write. No
|
||||||
|
background writer is needed, so killed children cannot leave writer threads.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, process):
|
||||||
|
self.process = process
|
||||||
|
self.partial_write = False
|
||||||
|
self.timeouts = 0
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
return getattr(self.process, name)
|
||||||
|
|
||||||
|
def communicate(self, input=None, timeout=None):
|
||||||
|
if self.process.stdin is not None and self.process.poll() is None:
|
||||||
|
if input is not None:
|
||||||
|
self.process.stdin.write(input[:512])
|
||||||
|
self.process.stdin.flush()
|
||||||
|
self.partial_write = True
|
||||||
|
try:
|
||||||
|
self.process.wait(timeout=timeout)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.timeouts += 1
|
||||||
|
raise
|
||||||
|
try:
|
||||||
|
return self.process.communicate(input=input, timeout=timeout)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.timeouts += 1
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
class BattleWorkerTransportTests(unittest.TestCase):
|
||||||
|
def large_request(self):
|
||||||
|
payload = request()
|
||||||
|
# A valid snapshot field retained by the combat-only serializer.
|
||||||
|
payload['roster']['monsters'][0]['nicName'] = 'x' * (128 * 1024)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
def launch_slow_worker(self, *, partial=False, cancel_event=None):
|
||||||
|
real_popen = subprocess.Popen
|
||||||
|
launched = []
|
||||||
|
streams = []
|
||||||
|
|
||||||
|
def launch(command, **kwargs):
|
||||||
|
self.assertEqual(command, [sys.executable, '-m',
|
||||||
|
'ranch_assistant.battle_simulator', '--worker'])
|
||||||
|
self.assertNotIn('shell', kwargs)
|
||||||
|
stream = kwargs['stdin']
|
||||||
|
if stream != subprocess.PIPE:
|
||||||
|
streams.append(stream)
|
||||||
|
wire = stream.read()
|
||||||
|
self.assertGreater(len(wire), 128 * 1024)
|
||||||
|
self.assertLessEqual(len(wire), simulator.MAX_WIRE_BYTES)
|
||||||
|
self.assertNotIn(b'account-secret', wire)
|
||||||
|
self.assertEqual(json.loads(wire)['request']['roster']['monsters'][0]['nicName'],
|
||||||
|
'x' * (128 * 1024))
|
||||||
|
stream.seek(0)
|
||||||
|
process = real_popen([sys.executable, '-c', SLOW_WORKER], **kwargs)
|
||||||
|
observed = PartialFirstWrite(process) if partial else process
|
||||||
|
launched.append(observed)
|
||||||
|
if cancel_event is not None:
|
||||||
|
cancel_event.set()
|
||||||
|
return observed
|
||||||
|
|
||||||
|
return launch, launched, streams
|
||||||
|
|
||||||
|
def assert_cleaned_up(self, processes, streams):
|
||||||
|
self.assertEqual(len(processes), 1)
|
||||||
|
self.assertIsNotNone(processes[0].poll())
|
||||||
|
self.assertTrue(processes[0].stdout.closed)
|
||||||
|
self.assertTrue(processes[0].stderr.closed)
|
||||||
|
for stream in streams:
|
||||||
|
self.assertTrue(stream.closed)
|
||||||
|
|
||||||
|
def test_partial_first_quantum_delivers_one_complete_request(self):
|
||||||
|
payload = self.large_request()
|
||||||
|
expected = simulate_quick(payload)
|
||||||
|
self.assertIn(expected['outcome'], ('win', 'loss'))
|
||||||
|
launch, processes, streams = self.launch_slow_worker(partial=True)
|
||||||
|
with patch.object(simulator.subprocess, 'Popen', side_effect=launch):
|
||||||
|
actual = simulator.ExperimentalBattleRuntime().run(payload, timeout=1.5)
|
||||||
|
self.assert_cleaned_up(processes, streams)
|
||||||
|
self.assertGreaterEqual(processes[0].timeouts, 2)
|
||||||
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
|
def test_native_slow_reader_preserves_result_and_omits_credentials(self):
|
||||||
|
payload = self.large_request()
|
||||||
|
expected = simulate_quick(payload)
|
||||||
|
payload['credentials'] = 'account-secret'
|
||||||
|
payload['roster']['master']['token'] = 'account-secret'
|
||||||
|
launch, processes, streams = self.launch_slow_worker()
|
||||||
|
with patch.object(simulator.subprocess, 'Popen', side_effect=launch):
|
||||||
|
actual = simulator.ExperimentalBattleRuntime().run(payload, timeout=1.5)
|
||||||
|
self.assert_cleaned_up(processes, streams)
|
||||||
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
|
def test_cancel_and_deadline_reap_slow_reader_and_close_input(self):
|
||||||
|
for cancelled in (False, True):
|
||||||
|
with self.subTest(cancelled=cancelled):
|
||||||
|
event = threading.Event()
|
||||||
|
launch, processes, streams = self.launch_slow_worker(
|
||||||
|
cancel_event=event if cancelled else None)
|
||||||
|
with patch.object(simulator.subprocess, 'Popen', side_effect=launch):
|
||||||
|
result = simulator.ExperimentalBattleRuntime().run(
|
||||||
|
self.large_request(), cancel_event=event,
|
||||||
|
timeout=1.5 if cancelled else .1)
|
||||||
|
self.assertEqual(result['outcome'], 'cancelled' if cancelled else 'timeout')
|
||||||
|
self.assertFalse(result['terminal'])
|
||||||
|
self.assertIsNone(result['battle_data'])
|
||||||
|
self.assert_cleaned_up(processes, streams)
|
||||||
|
|
||||||
|
def test_oversize_input_never_launches_worker(self):
|
||||||
|
with patch.object(simulator, 'MAX_WIRE_BYTES', 1024), \
|
||||||
|
patch.object(simulator.subprocess, 'Popen') as launch:
|
||||||
|
result = simulator.ExperimentalBattleRuntime().run(self.large_request())
|
||||||
|
launch.assert_not_called()
|
||||||
|
self.assertEqual(result['terminal_reason'], 'request_exceeds_worker_input_limit')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
+12
-10
@@ -1,10 +1,10 @@
|
|||||||
# 牧羊人之心牧场助手 · Web 2.0.9
|
# 牧羊人之心牧场助手 · Web 2.0.10
|
||||||
|
|
||||||
## 产品约束
|
## 产品约束
|
||||||
|
|
||||||
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web `2.0.9`,源码发布入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md),既有功能与历史验证见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web `2.0.10`,源码发布入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md),既有功能与历史验证见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
2.0.9 包含界面清理、委托补缺、默认快速战斗与潜能误报修复;保留账号简短状态、错误、表格、表单与原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_9.md)。
|
2.0.10 聚焦战斗输入传输、中断恢复、启停意愿与能力状态纠正;保留账号简短状态、错误、表格、表单与原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_10.md)。
|
||||||
|
|
||||||
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
||||||
|
|
||||||
@@ -28,13 +28,15 @@
|
|||||||
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
||||||
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
|
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
|
||||||
|
|
||||||
## 2.0.9 本轮范围
|
## 2.0.10 本轮范围
|
||||||
|
|
||||||
默认使用快速数值模型,委托按剩余步骤统一计算采购和提交需求:
|
- Linux 战斗子进程从匿名临时文件一次读取完整 stdin,保留取消、超时及输入大小检查。
|
||||||
|
- 升级后,旧委托备料记录若已确认入场、未发送结算且符合技术失败条件,按原客户端协议记录失败并退出一次;兼容来源任务与步骤均为0的记录,不重新入场或提交胜利。
|
||||||
|
- 保存的原始战斗输入最多用于一次本地恢复;完整战果校验通过后按战斗时钟续交尚未发送的结果。未知已发送写请求不重放。
|
||||||
|
- 手动停止阻止恢复提交;内部暂停保留用户运行意愿,来源策略关闭时明确等待启用,不自动开启策略。
|
||||||
|
- 状态接口透出5个安全策略状态字段,区分运行意愿、实际执行与等待原因;修复导航及策略关闭时的能力误报,保留真实不支持、资源不足及失败原因。具体行为见 [发布说明](../analysis/RELEASE_2_0_10.md)。
|
||||||
|
|
||||||
- 委托用明确中文说明未接取的实际原因;成熟魔物交付需求联动购蛋、孵化,优先备齐所需资源再接取。锁定、培养、优质备份等魔物继续受保护,采购与孵蛋遵守耗用预算和需求缺口限制。
|
沿用 2.0.9 的快速 HP/DPS 模型、伤害配置、按剩余步骤计算的委托备料及正常潜能误报修复,历史范围见 [2.0.9 发布说明](../analysis/RELEASE_2_0_9.md)。
|
||||||
- 正常执行默认使用现有内置实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。模型结合双方属性、血量、每秒伤害(DPS)、有效血量(EHP)、时间与关卡目标估算胜利、战败或超时,仍有机制简化,不保证全部关卡可通关或与客户端结果一致。
|
|
||||||
- 潜能检查依据合法的 `PotentialPanel` 上限区分正常数值与异常,修复正常潜能的误报。
|
|
||||||
|
|
||||||
## 2.0.8 自动委托与每日历史
|
## 2.0.8 自动委托与每日历史
|
||||||
|
|
||||||
@@ -89,9 +91,9 @@
|
|||||||
|
|
||||||
## 安全与验证
|
## 安全与验证
|
||||||
|
|
||||||
2.0.9 快速模型可读取358/358份主线与委托战斗配置,表示输入可计算。离线样本有胜有败,8个20氪金委托战斗为5胜3败;当前卡点样本的默认路径结果及耗时见 [发布说明](../analysis/RELEASE_2_0_9.md#验证)。
|
2.0.10 后端、模型与更新器共 **550 项唯一测试:548 通过、2 项 Windows 预期跳过**;另有 **14 项全新浏览器测试全部通过**,8组独立探针复核通过。范围见 [本版发布说明](../analysis/RELEASE_2_0_10.md#验证);战斗模型仍为近似实现。
|
||||||
|
|
||||||
617项唯一回归用例中615项通过,2项因Windows环境跳过;另有8项界面浏览器测试通过。多步骤采购修复已通过独立复核;未在线提交游戏结算。
|
2.0.9 的历史验证见 [历史发布说明](../analysis/RELEASE_2_0_9.md#验证),不计入本版。
|
||||||
|
|
||||||
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。证据与发布门禁见 [发布说明](../analysis/RELEASE_2_0_8.md#验证);历史版本结果不计入本版。
|
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。证据与发布门禁见 [发布说明](../analysis/RELEASE_2_0_8.md#验证);历史版本结果不计入本版。
|
||||||
|
|
||||||
|
|||||||
+11
-7
@@ -1,8 +1,8 @@
|
|||||||
# Web 2.0.9 运行说明
|
# Web 2.0.10 运行说明
|
||||||
|
|
||||||
Web **2.0.9**,源码发布入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。自动委托提供当前委托与每日记录,功能和历史验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
Web **2.0.10**,源码发布入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。自动委托提供当前委托与每日记录,功能和历史验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
2.0.9 清理重复运行提示,补齐委托资源准备、默认快速战斗及正常潜能误报修复。委托明确显示中文未接取原因,成熟魔物需求联动购蛋、孵化;按剩余步骤备料,遵守预算、需求缺口及魔物保护设置。详情继续使用原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_9.md)。
|
2.0.10 修复 Linux 战斗子进程大输入传输、停止检查及导航能力误报。升级后按保存的入场、原始输入与战果证据恢复:符合条件的旧委托备料技术失败记录退出一次,完整战果续交尚未发送的结果;未知已发送写请求不重放。中文状态明确指出等待原因,详情继续使用原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_10.md)。
|
||||||
|
|
||||||
正常执行默认使用现有内置实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。模型按双方属性、血量、每秒伤害、时间与目标估算胜利、战败或超时,仍有机制简化,不保证全部关卡可通关或与客户端结果一致。
|
正常执行默认使用现有内置实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。模型按双方属性、血量、每秒伤害、时间与目标估算胜利、战败或超时,仍有机制简化,不保证全部关卡可通关或与客户端结果一致。
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ py -3 -m venv .venv-web
|
|||||||
|
|
||||||
关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控、重登及策略执行都由服务端管理。手动“停止”只暂停策略,连接监控与掉线重登继续;该暂停在重新登录和服务重启后仍保留,点击“开启”恢复。
|
关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控、重登及策略执行都由服务端管理。手动“停止”只暂停策略,连接监控与掉线重登继续;该暂停在重新登录和服务重启后仍保留,点击“开启”恢复。
|
||||||
|
|
||||||
临时网络故障采用退避后的只读状态检查,确认角色连接恢复后自动继续原先启用的策略。会话失效时按登录页等待时长自动重新登录。账号状态区分用户暂停、临时恢复和请求待核对,心跳成功不等于策略已经运行;日志保留失败原因及恢复结果。未确认的消耗请求仍保留核对记录,不自动重复提交。
|
临时网络故障采用退避后的只读状态检查,确认角色连接恢复后自动继续原先启用的策略。会话失效时按登录页等待时长自动重新登录。账号状态区分用户暂停、临时恢复和请求待核对,心跳成功不等于策略已经运行;日志保留失败原因及恢复结果。内部暂停保留用户运行意愿;来源策略关闭时明确等待启用,不自动勾选。已保存的完整战果仅在用户允许运行、来源策略已启用、原入场及来源校验通过且战斗时钟满足时续交尚未发送的结果;手动停止阻止恢复提交,未知已发送写请求保留核对记录,不自动重发。
|
||||||
|
|
||||||
服务重启会保留配置、加密会话及启停选择,并自动恢复有登录记录的账号。只有清除登录记录或移除账号才取消持续自动登录;缺少密码、区服或原角色信息时显示具体原因。运行日志按账号限量持久保存,旧角色数据会标注缓存状态。
|
服务重启会保留配置、加密会话及启停选择,并自动恢复有登录记录的账号。只有清除登录记录或移除账号才取消持续自动登录;缺少密码、区服或原角色信息时显示具体原因。运行日志按账号限量持久保存,旧角色数据会标注缓存状态。
|
||||||
|
|
||||||
@@ -108,13 +108,17 @@ sh start-web.sh --no-browser
|
|||||||
|
|
||||||
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
||||||
|
|
||||||
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,稳定 Release 和正式镜像就绪、宿主机心跳有效后,可直接通过“帮助 → 检查版本更新…”升级 **2.0.9**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
|
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,稳定 Release 和正式镜像就绪、宿主机心跳有效后,可直接通过“帮助 → 检查版本更新…”升级 **2.0.10**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
|
||||||
|
|
||||||
## 离线验证
|
## 离线验证
|
||||||
|
|
||||||
2.0.9 快速模型的输入预检覆盖358/358份主线与委托战斗配置。当前卡点的真实账号离线样本预计战斗5秒,直接计算约1.2毫秒,含隔离进程启动与检查约0.21秒;8个20氪金委托战斗的离线结果为5胜3败,见 [本版发布说明](../analysis/RELEASE_2_0_9.md#验证)。
|
2.0.10 后端、模型与更新器共 **550 项唯一测试:548 通过、2 项 Windows 预期跳过**;另有 **14 项全新浏览器测试全部通过**,8组独立探针复核通过,见 [本版发布说明](../analysis/RELEASE_2_0_10.md#验证)。镜像工作流新增子进程传输、战斗恢复、能力展示、Web 生命周期、恢复契约及状态 API 六个定向模块:
|
||||||
|
|
||||||
617项唯一回归用例中615项通过,2项因Windows环境跳过;另有8项界面浏览器测试通过。多步骤采购循环已经修复并独立复核。本轮未在线提交游戏结算或手动部署X99。
|
```console
|
||||||
|
python -B -m unittest ranch_assistant.tests.test_battle_worker_transport ranch_assistant.tests.test_battle_recovery ranch_assistant.tests.test_battle_capability_presentation ranch_web.tests.test_lifecycle_recovery ranch_web.tests.test_battle_recovery_contract ranch_web.tests.test_status_recovery_api -v
|
||||||
|
```
|
||||||
|
|
||||||
|
2.0.9 的历史验证见 [历史发布说明](../analysis/RELEASE_2_0_9.md#验证),不计入本版。
|
||||||
|
|
||||||
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。分组结果与证据见 [发布说明](../analysis/RELEASE_2_0_8.md#验证)。2.0.7 的结果保留在 [历史发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录也不计入本版验收。
|
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。分组结果与证据见 [发布说明](../analysis/RELEASE_2_0_8.md#验证)。2.0.7 的结果保留在 [历史发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录也不计入本版验收。
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"""Headless Web workspace for the ranch assistant."""
|
"""Headless Web workspace for the ranch assistant."""
|
||||||
|
|
||||||
__version__ = "2.0.9"
|
__version__ = "2.0.10"
|
||||||
GAME_VERSION = "1.9.68"
|
GAME_VERSION = "1.9.68"
|
||||||
|
|
||||||
__all__ = ["__version__", "GAME_VERSION"]
|
__all__ = ["__version__", "GAME_VERSION"]
|
||||||
|
|||||||
+3
-1
@@ -577,9 +577,11 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP
|
|||||||
if not isinstance(value, dict):
|
if not isinstance(value, dict):
|
||||||
raise HTTPException(500, "账号状态返回格式不正确")
|
raise HTTPException(500, "账号状态返回格式不正确")
|
||||||
result = {field: value.get(field) for field in ("id", "label", "connected", "demo", "running", "busy", "revision", "error",
|
result = {field: value.get(field) for field in ("id", "label", "connected", "demo", "running", "busy", "revision", "error",
|
||||||
"connection_state", "connection_message", "last_game_success_at", "next_retry_at")}
|
"connection_state", "connection_message", "last_game_success_at", "next_retry_at",
|
||||||
|
"strategy_requested", "manual_stop", "strategy_state", "strategy_message", "strategy_retry_at")}
|
||||||
result["error"] = public_error(result["error"])
|
result["error"] = public_error(result["error"])
|
||||||
result["connection_message"] = public_error(result["connection_message"])
|
result["connection_message"] = public_error(result["connection_message"])
|
||||||
|
result["strategy_message"] = public_error(result["strategy_message"])
|
||||||
auto = value.get("auto_relogin_status")
|
auto = value.get("auto_relogin_status")
|
||||||
result["auto_relogin_status"] = ({field: auto.get(field) for field in ("state", "message", "next_attempt_at")}
|
result["auto_relogin_status"] = ({field: auto.get(field) for field in ("state", "message", "next_attempt_at")}
|
||||||
if isinstance(auto, dict) else None)
|
if isinstance(auto, dict) else None)
|
||||||
|
|||||||
+69
-13
@@ -335,12 +335,54 @@ class AccountWorker:
|
|||||||
self._legacy_pending.pop(identity)
|
self._legacy_pending.pop(identity)
|
||||||
self._save_run_intents()
|
self._save_run_intents()
|
||||||
|
|
||||||
|
def _pending_battle_recovery(self):
|
||||||
|
classify = getattr(self.engine, "pending_battle_recovery", None)
|
||||||
|
if callable(classify):
|
||||||
|
status = classify()
|
||||||
|
return status if isinstance(status, dict) else {}
|
||||||
|
# Compatibility for older Engine test doubles without the public API.
|
||||||
|
if self.engine.snapshot is not None:
|
||||||
|
record = self.engine.battle_journal.pending(self.engine.snapshot)
|
||||||
|
if record:
|
||||||
|
if self.engine.battles.resumable_task_clock(record) is True:
|
||||||
|
return {"resumable": True, "message": "战果已保存;等待结算时间及对应策略启用后续交"}
|
||||||
|
return {}
|
||||||
|
|
||||||
def _pending_execution_reason(self):
|
def _pending_execution_reason(self):
|
||||||
|
suffix = ";禁止自动重发,请在游戏内核对结果"
|
||||||
if self.active_identity in self._legacy_pending:
|
if self.active_identity in self._legacy_pending:
|
||||||
return "赠礼、装填或喂养请求结果待核对,禁止自动重发;后台继续读取游戏状态,确认后自动恢复已勾选策略"
|
kind = self._legacy_pending[self.active_identity]["kind"]
|
||||||
if self.engine.snapshot is not None and (self.engine._progression_pending()
|
return {"gift": "赠礼", "hatch": "装填", "feed": "喂养"}[kind] + "请求结果待核对" + suffix
|
||||||
or self.engine.explore_planner.pending(self.engine.snapshot) or self.engine._breakthrough_pending):
|
if self.engine.snapshot is None:
|
||||||
return "存在未确认的任务、战斗、探险或突破请求,禁止自动重发;后台继续核对,核对完成后恢复已勾选策略"
|
return ""
|
||||||
|
if self.engine._progression_pending():
|
||||||
|
sweep = self.engine.sweeper.state.get("pending")
|
||||||
|
if sweep:
|
||||||
|
return f"扫荡(关卡 {sweep.get('stage', '')}):{sweep.get('phase') or '请求结果待核对'}" + suffix
|
||||||
|
recovery = self._pending_battle_recovery()
|
||||||
|
if recovery.get("state") == "blocked_policy":
|
||||||
|
return recovery.get("message") or "等待启用本次战斗的来源策略后恢复"
|
||||||
|
if recovery.get("resumable") is not True:
|
||||||
|
record = self.engine.battle_journal.pending(self.engine.snapshot) or {}
|
||||||
|
label = record.get("description") or ("战斗" if record.get("stage_id") else "任务")
|
||||||
|
if record.get("stage_id"):
|
||||||
|
label += f"(关卡 {record['stage_id']},难度 {record.get('difficulty') or 1})"
|
||||||
|
detail = record.get("message") or "请求结果待核对"
|
||||||
|
if record.get("execution_status") == "timed_out" or record.get("terminal_reason") == "worker_wall_clock_limit":
|
||||||
|
detail = "本地战斗计算超时"
|
||||||
|
if (not record.get("battle_data") and not record.get("settlement_dispatched")
|
||||||
|
and not record.get("settlement_confirmed")
|
||||||
|
and record.get("path") in ("", "battleService/battleStart", "stageService/stageStart")):
|
||||||
|
detail += ",尚未提交结算"
|
||||||
|
return label + ":" + detail + suffix
|
||||||
|
explore = self.engine.explore_planner.pending(self.engine.snapshot)
|
||||||
|
if explore:
|
||||||
|
label = "探险出发" if explore.get("kind") == "explore_start" else "探险领奖"
|
||||||
|
return f"{label}(队伍 {explore.get('team_id', '')}):{explore.get('message') or '请求结果待核对'}" + suffix
|
||||||
|
if self.engine._breakthrough_pending:
|
||||||
|
record = self.engine._breakthrough_pending
|
||||||
|
label = "潜能提升" if record.get("kind") == "potential" else "突破"
|
||||||
|
return label + ":" + (record.get("message") or "请求结果待核对") + suffix
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
def _refresh_execution(self):
|
def _refresh_execution(self):
|
||||||
@@ -372,6 +414,9 @@ class AccountWorker:
|
|||||||
state, message = "recovering", self.connection_message
|
state, message = "recovering", self.connection_message
|
||||||
elif not self._running:
|
elif not self._running:
|
||||||
state, message = "offline", self.connection_message
|
state, message = "offline", self.connection_message
|
||||||
|
elif (recovery := self._pending_battle_recovery()).get("resumable") is True:
|
||||||
|
state = "recovering"
|
||||||
|
message = recovery.get("message") or "等待对应策略允许恢复"
|
||||||
else:
|
else:
|
||||||
state, message = "running", "已勾选的策略将自动执行"
|
state, message = "running", "已勾选的策略将自动执行"
|
||||||
return {"strategy_requested": requested, "manual_stop": not requested,
|
return {"strategy_requested": requested, "manual_stop": not requested,
|
||||||
@@ -1117,14 +1162,23 @@ class AccountWorker:
|
|||||||
self.schedule.next_fast[kind] = math.inf
|
self.schedule.next_fast[kind] = math.inf
|
||||||
auto = True
|
auto = True
|
||||||
value = self.engine.poll_automation(kind)
|
value = self.engine.poll_automation(kind)
|
||||||
elif kind == "poll":
|
elif kind in ("poll", "reconcile"):
|
||||||
auto = self._set_auto(self._running)
|
recovering = self._pending_battle_recovery().get("resumable") is True
|
||||||
value = self.engine.poll(defer_hatch=True)
|
with self.lock:
|
||||||
self.schedule.poll_finished(self.config)
|
# Recover only the original entry, with general automation
|
||||||
elif kind == "reconcile":
|
# disabled. Stop/config changes still revoke this job.
|
||||||
self._set_auto(False)
|
auto = self._set_auto(self._running and kind == "poll" and not recovering)
|
||||||
# Engine's durable pending barriers reconcile before planning.
|
resume_pending = bool(recovering and self._running and self.strategy_requested
|
||||||
# A check never silently replays an uncertain write.
|
and not self._closing and not self.manager._closing and job.generation == self._generation)
|
||||||
|
if resume_pending:
|
||||||
|
job.consuming = True
|
||||||
|
self.check_intent()
|
||||||
|
if callable(getattr(self.engine, "pending_battle_recovery", None)):
|
||||||
|
value = self.engine.poll(defer_hatch=True, resume_pending=resume_pending)
|
||||||
|
else:
|
||||||
|
# Older Engine doubles use auto to authorize saved results.
|
||||||
|
if resume_pending:
|
||||||
|
auto = self._set_auto(True)
|
||||||
value = self.engine.poll(defer_hatch=True)
|
value = self.engine.poll(defer_hatch=True)
|
||||||
self.schedule.poll_finished(self.config)
|
self.schedule.poll_finished(self.config)
|
||||||
else:
|
else:
|
||||||
@@ -1140,7 +1194,9 @@ class AccountWorker:
|
|||||||
# by the current Engine generation turns that switch off.
|
# by the current Engine generation turns that switch off.
|
||||||
if auto and job.generation == self._generation and not self.engine.auto:
|
if auto and job.generation == self._generation and not self.engine.auto:
|
||||||
if self._pending_execution_reason():
|
if self._pending_execution_reason():
|
||||||
self.stop()
|
# A pending barrier pauses execution, not user intent
|
||||||
|
# or the generation of other queued local edits.
|
||||||
|
self._refresh_execution()
|
||||||
else:
|
else:
|
||||||
self._execution_failed(ValueError(value[2] or "策略暂不可用"))
|
self._execution_failed(ValueError(value[2] or "策略暂不可用"))
|
||||||
elif auto and job.generation == self._generation:
|
elif auto and job.generation == self._generation:
|
||||||
|
|||||||
@@ -415,7 +415,7 @@ async function exportYields(account=current()) {
|
|||||||
async function command(name,account=current()) {
|
async function command(name,account=current()) {
|
||||||
try {
|
try {
|
||||||
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
||||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.9'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
|
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.10'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
|
||||||
if(name==='updates')return await showUpdates();
|
if(name==='updates')return await showUpdates();
|
||||||
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
||||||
if(!account)throw new Error('请先新增或选择账号。');
|
if(!account)throw new Error('请先新增或选择账号。');
|
||||||
@@ -640,7 +640,7 @@ async function bootstrap() {
|
|||||||
$('#app').hidden=false;
|
$('#app').hidden=false;
|
||||||
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
||||||
if(state.redirecting)return;
|
if(state.redirecting)return;
|
||||||
$('#app-version').textContent=meta.version || '2.0.9';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
$('#app-version').textContent=meta.version || '2.0.10';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||||
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
||||||
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
</div></details>
|
</div></details>
|
||||||
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
||||||
</nav>
|
</nav>
|
||||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.9</span></span>
|
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.10</span></span>
|
||||||
<span id="access-mode" class="muted"></span>
|
<span id="access-mode" class="muted"></span>
|
||||||
</header>
|
</header>
|
||||||
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
"""Web authorization of Engine-classified recovery, using offline clients only."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Snapshot
|
||||||
|
from ranch_web.service import AccountWorker
|
||||||
|
from ranch_web.tests import test_lifecycle_recovery as lifecycle
|
||||||
|
from ranch_web.tests import test_service as fixtures
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryGuardContractTests(unittest.TestCase):
|
||||||
|
def worker(self, runtime):
|
||||||
|
worker = AccountWorker.__new__(AccountWorker)
|
||||||
|
worker.active_identity, worker._legacy_pending = None, {}
|
||||||
|
record = {"kind": "stage_battle", "stage_id": "0102", "phase": "unknown",
|
||||||
|
"execution_status": "timed_out", "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"path": "stageService/stageStart"}
|
||||||
|
worker.engine = SimpleNamespace(snapshot=object(), battles=runtime,
|
||||||
|
battle_journal=SimpleNamespace(pending=lambda snapshot: record),
|
||||||
|
_progression_pending=lambda: record, sweeper=SimpleNamespace(state={}),
|
||||||
|
explore_planner=SimpleNamespace(pending=lambda snapshot: None), _breakthrough_pending=None)
|
||||||
|
return worker, record
|
||||||
|
|
||||||
|
def test_engine_recovery_contract_overrides_old_clock_predicate(self):
|
||||||
|
for allowed in (False, True):
|
||||||
|
with self.subTest(allowed=allowed):
|
||||||
|
runtime = SimpleNamespace(recovery_status=Mock(return_value={
|
||||||
|
"state": "abandon_stage" if allowed else "blocked", "resumable": allowed,
|
||||||
|
"message": "已确认开战,按原客户端协议退出"}),
|
||||||
|
resumable_task_clock=Mock(return_value=not allowed))
|
||||||
|
worker, record = self.worker(runtime)
|
||||||
|
worker.engine.pending_battle_recovery = Mock(return_value=runtime.recovery_status.return_value)
|
||||||
|
self.assertEqual(worker._pending_execution_reason() == "", allowed)
|
||||||
|
worker.engine.pending_battle_recovery.assert_called_once_with()
|
||||||
|
runtime.recovery_status.assert_not_called()
|
||||||
|
runtime.resumable_task_clock.assert_not_called()
|
||||||
|
|
||||||
|
def test_truthy_recovery_flag_does_not_grant_write_permission(self):
|
||||||
|
for flag in (1, "true", None):
|
||||||
|
with self.subTest(flag=flag):
|
||||||
|
worker, _ = self.worker(SimpleNamespace(recovery_status=lambda *args, **kwargs: {
|
||||||
|
"state": "abandon_stage", "resumable": flag, "message": ""},
|
||||||
|
resumable_task_clock=lambda record: True))
|
||||||
|
worker.engine.pending_battle_recovery = lambda: {"state": "abandon_stage", "resumable": flag, "message": ""}
|
||||||
|
self.assertTrue(worker._pending_execution_reason())
|
||||||
|
|
||||||
|
def test_runtime_without_recovery_helper_keeps_old_clock_fallback(self):
|
||||||
|
for allowed in (False, True):
|
||||||
|
with self.subTest(allowed=allowed):
|
||||||
|
worker, _ = self.worker(SimpleNamespace(resumable_task_clock=lambda record: allowed))
|
||||||
|
self.assertEqual(worker._pending_execution_reason() == "", allowed)
|
||||||
|
|
||||||
|
def test_disabled_origin_uses_specific_engine_policy_message(self):
|
||||||
|
worker, _ = self.worker(SimpleNamespace(resumable_task_clock=lambda record: True))
|
||||||
|
message = "对应委托策略已关闭,等待启用委托策略后恢复原战斗"
|
||||||
|
worker.engine.pending_battle_recovery = lambda: {
|
||||||
|
"state": "blocked_policy", "resumable": False, "message": message}
|
||||||
|
self.assertEqual(worker._pending_execution_reason(), message)
|
||||||
|
|
||||||
|
|
||||||
|
class LegacyBattleRecoveryTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ServiceTests.setUp
|
||||||
|
account = fixtures.ServiceTests.account
|
||||||
|
idle = fixtures.ServiceTests.idle
|
||||||
|
job = fixtures.ServiceTests.job
|
||||||
|
connected = lifecycle.LifecycleRecoveryTests.connected
|
||||||
|
tick = lifecycle.LifecycleRecoveryTests.tick
|
||||||
|
paths = lifecycle.LifecycleRecoveryTests.paths
|
||||||
|
|
||||||
|
def login(self, identifier):
|
||||||
|
return fixtures.ServiceTests.login(self, identifier, account="recovery-" + identifier)
|
||||||
|
|
||||||
|
def legacy_timeout(self, *, unaccepted=False):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
engine = worker.engine
|
||||||
|
source_id, source_type, source_step = (0, "4001004", 0) if unaccepted else (51, "1002013", 1)
|
||||||
|
engine.client.raw["currentTasks"] = ([] if unaccepted else [
|
||||||
|
{"id": source_id, "typeId": source_type, "curStep": source_step, "stepValue": 0}])
|
||||||
|
engine.snapshot = Snapshot(deepcopy(engine.client.raw))
|
||||||
|
engine.game_data = ProgressionData({"task_info": {source_type: {"type": 4, "name": "离线材料委托",
|
||||||
|
"steps": [{"statusType": "none", "statusValue": {}}]}}})
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["quest_policy"]["enabled"] = True
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
journal = engine.battle_journal
|
||||||
|
record = journal.begin(engine.snapshot, {"kind": "stage_battle", "stage_id": "0102", "difficulty": 1,
|
||||||
|
"battle_kind": "ordinary_stage", "description": "离线委托材料关卡", "task_id": None,
|
||||||
|
"task_type_id": None, "source_task_id": source_id,
|
||||||
|
"source_task_type_id": source_type, "source_step_number": source_step})
|
||||||
|
journal.update(record, "unknown", path="stageService/stageStart", start_path="stageService/stageStart",
|
||||||
|
start_response={"resCode": 0, "triggerEvent": False, "stageEvent": None},
|
||||||
|
battle_mode="experimental", execution_mode="experimental", execution_status="timed_out", terminal=False,
|
||||||
|
terminal_reason="worker_wall_clock_limit", message="战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self.assertEqual(engine.battles.recovery_status(record, snapshot=engine.snapshot)["state"], "abandon_stage")
|
||||||
|
engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
return identifier, worker
|
||||||
|
|
||||||
|
def test_legacy_timeout_blocked_by_default_when_engine_denies_recovery(self):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
with patch.object(worker.engine, "pending_battle_recovery", return_value={
|
||||||
|
"state": "blocked", "resumable": False, "message": "尚无可验证的安全恢复证据"}):
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
|
||||||
|
def test_strict_safe_legacy_timeout_starts_then_exits_on_reconcile_without_reentry(self):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
self.assert_failure_exit(identifier, worker)
|
||||||
|
|
||||||
|
def test_unaccepted_commission_legacy_timeout_exits_without_reentry_or_reward(self):
|
||||||
|
identifier, worker = self.legacy_timeout(unaccepted=True)
|
||||||
|
self.assert_failure_exit(identifier, worker)
|
||||||
|
|
||||||
|
def assert_failure_exit(self, identifier, worker):
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto, "Start must not dispatch recovery inline")
|
||||||
|
self.assertEqual(len(fixtures.FakeClient.calls), before)
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertEqual(state["strategy_state"], "recovering")
|
||||||
|
self.assertIn("退出", state["strategy_message"])
|
||||||
|
self.assertNotIn("战果已保存", state["strategy_message"])
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
after = self.manager.logs(identifier)["next"]
|
||||||
|
poll = worker.engine.poll
|
||||||
|
|
||||||
|
def recovery_poll(**kwargs):
|
||||||
|
self.assertFalse(worker.engine.auto, "Recovery must not enable other strategies")
|
||||||
|
self.assertIs(kwargs.get("resume_pending"), True)
|
||||||
|
return poll(**kwargs)
|
||||||
|
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=recovery_poll):
|
||||||
|
self.assertEqual(self.tick(identifier, worker)["result"]["kind"], "reconcile")
|
||||||
|
writes = [("/".join(url.rsplit("/", 2)[-2:]),
|
||||||
|
{key: value for key, value in payload.items() if key not in {"token", "reqid", "reqsid"}})
|
||||||
|
for _, url, payload in fixtures.FakeClient.calls[before:]
|
||||||
|
if not url.endswith("masterService/masterQueryDetail")]
|
||||||
|
self.assertEqual(writes, [("battleService/recordBattleResult", {"stageId": "0102", "cityId": "1", "result": 0})])
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
record = worker.engine.battle_journal.records(worker.engine.snapshot)[0]
|
||||||
|
self.assertEqual(record["outcome"], "abandoned")
|
||||||
|
self.assertNotIn("battle_data", record)
|
||||||
|
rows = build_view(worker.engine, "battles", worker.config)["rows"]
|
||||||
|
row = next(row for row in rows if row["outcome"] == "abandoned")
|
||||||
|
self.assertIn("已放弃(本地计算失败)", row["outcome_label"])
|
||||||
|
self.assertNotIn("打不过", row["outcome_label"])
|
||||||
|
logs = self.manager.logs(identifier, after=after)["entries"]
|
||||||
|
self.assertTrue(any("退出" in row["message"] for row in logs))
|
||||||
|
self.assertFalse(any("打不过" in row["message"] for row in logs))
|
||||||
|
|
||||||
|
def test_manual_refresh_never_authorizes_safe_source_zero_recovery(self):
|
||||||
|
identifier, worker = self.legacy_timeout(unaccepted=True)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh"))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
|
||||||
|
def test_manual_stop_prevents_safe_legacy_failure_exit(self):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
|
||||||
|
def test_disabled_source_policy_prevents_safe_legacy_failure_exit(self):
|
||||||
|
identifier, worker = self.legacy_timeout(unaccepted=True)
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["quest_policy"]["enabled"] = False
|
||||||
|
config["config"]["daily_policy"].update(enabled=True, selected=["gift"])
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertFalse(state["running"])
|
||||||
|
self.assertEqual(state["strategy_state"], "blocked")
|
||||||
|
self.assertTrue(state["strategy_requested"])
|
||||||
|
self.assertFalse(state["manual_stop"])
|
||||||
|
recovery = worker.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(recovery["state"], "blocked_policy")
|
||||||
|
self.assertEqual(state["strategy_message"], recovery["message"])
|
||||||
|
self.assertIn("委托", state["strategy_message"])
|
||||||
|
self.assertIn("启用", state["strategy_message"])
|
||||||
|
self.assertFalse(worker.engine.quest_policy.enabled)
|
||||||
|
self.assertTrue(worker.engine.daily_policy.enabled)
|
||||||
|
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["quest_policy"]["enabled"] = True
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
writes = [("/".join(url.rsplit("/", 2)[-2:]), payload.get("result"))
|
||||||
|
for _, url, payload in fixtures.FakeClient.calls[before:]
|
||||||
|
if not url.endswith("masterService/masterQueryDetail")]
|
||||||
|
self.assertEqual(writes, [("battleService/recordBattleResult", 0)])
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
|
||||||
|
def test_unknown_start_settlement_or_failure_reply_never_grants_recovery(self):
|
||||||
|
for changes in ({"start_response": None}, {"settlement_dispatched": True, "path": "battleService/battleEnd"},
|
||||||
|
{"record_dispatched": True}):
|
||||||
|
with self.subTest(changes=changes):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
journal.update(journal.pending(worker.engine.snapshot), "unknown", **changes)
|
||||||
|
evidence = deepcopy(journal.pending(worker.engine.snapshot))
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
self.assertEqual(journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
"""Web recovery through real Engine barriers, temporary stores and offline HTTP."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Snapshot
|
||||||
|
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime
|
||||||
|
from ranch_web.service import WebManager
|
||||||
|
from ranch_web.tests import test_service as fixtures
|
||||||
|
|
||||||
|
|
||||||
|
class LifecycleRecoveryTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ServiceTests.setUp
|
||||||
|
account = fixtures.ServiceTests.account
|
||||||
|
idle = fixtures.ServiceTests.idle
|
||||||
|
job = fixtures.ServiceTests.job
|
||||||
|
login = fixtures.ServiceTests.login
|
||||||
|
|
||||||
|
def connected(self):
|
||||||
|
identifier = self.account(False)
|
||||||
|
self.login(identifier)
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
self.now = 1000.0
|
||||||
|
worker.schedule.clock = lambda: self.now
|
||||||
|
worker.schedule.uniform = lambda low, high: high
|
||||||
|
worker.engine.last_heartbeat = self.now
|
||||||
|
self.enterContext(patch.object(worker.engine, "master_sync_due", return_value=False))
|
||||||
|
self.enterContext(patch.object(worker.engine, "growth_sync_due", return_value=False))
|
||||||
|
return identifier, worker
|
||||||
|
|
||||||
|
def battle(self, identifier, worker, *, timed_out=False):
|
||||||
|
"""Small task fixture already used by Engine's orchestration regressions."""
|
||||||
|
engine = worker.engine
|
||||||
|
raw = engine.client.raw
|
||||||
|
raw["master"].update(ti=1000, money=1000, timeTi=0)
|
||||||
|
raw["currentTasks"] = [{"id": 51, "typeId": "100", "curStep": 1, "stepValue": 0}]
|
||||||
|
raw["history"] = {"unlockCity": {"1": True}, "unlockStage": {"0101": [1, 2, 3]}}
|
||||||
|
raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [raw["monsters"][0]["id"]]}]
|
||||||
|
raw["taskStepValue"] = 0
|
||||||
|
engine.snapshot = Snapshot(deepcopy(raw))
|
||||||
|
engine.game_data = ProgressionData({
|
||||||
|
"task_info": {"100": {"type": 1, "name": "离线任务", "steps": [
|
||||||
|
{"statusType": "passStage", "statusValue": {"stage": "0101", "level": 1}}]}},
|
||||||
|
"game_setting": {"cityInfo": {"1": {"name": "离线城市"}}},
|
||||||
|
"stage_info": {"0101": {"city": 1, "cost": {"ti": 6}, "level": {
|
||||||
|
str(n): {"cost": 0, "battle": {"fixture": True}} for n in (1, 2, 3)}}}})
|
||||||
|
runtime = ExperimentalRuntime()
|
||||||
|
original = runtime._run
|
||||||
|
if timed_out:
|
||||||
|
runtime.run.return_value = {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal_reason": "worker_wall_clock_limit"}
|
||||||
|
runtime.run.side_effect = None
|
||||||
|
else:
|
||||||
|
runtime.run.side_effect = lambda request, cancel_event: original(request, cancel_event=cancel_event) | {
|
||||||
|
"requires_realtime_wait": True, "model_elapsed_ms": 10000}
|
||||||
|
engine._battle_runtimes["experimental"] = runtime
|
||||||
|
engine.battles.request_builder = None
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["progression_policy"].update(enabled=True, battle_mode="experimental", reserve_ti=0)
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
return runtime
|
||||||
|
|
||||||
|
def tick(self, identifier, worker):
|
||||||
|
return self.job(identifier, worker.enqueue("__tick"))
|
||||||
|
|
||||||
|
def paths(self, start=0):
|
||||||
|
return ["/".join(url.rsplit("/", 2)[-2:]) for _, url, _ in fixtures.FakeClient.calls[start:]]
|
||||||
|
|
||||||
|
def interrupted_clock(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
runtime = self.battle(identifier, worker)
|
||||||
|
entered = threading.Event()
|
||||||
|
original = worker.engine.battles.wait_for_battle_clock
|
||||||
|
|
||||||
|
def computed_wait(record, request, result, data, started, cancel):
|
||||||
|
wait = cancel.wait
|
||||||
|
|
||||||
|
def clock_wait(timeout):
|
||||||
|
entered.set()
|
||||||
|
return wait(timeout)
|
||||||
|
|
||||||
|
with patch.object(cancel, "wait", side_effect=clock_wait):
|
||||||
|
return original(record, request, result, data, started, cancel)
|
||||||
|
|
||||||
|
with patch.object(worker.engine.battles, "wait_for_battle_clock", side_effect=computed_wait):
|
||||||
|
tick = worker.enqueue("__tick")
|
||||||
|
self.assertTrue(entered.wait(3), "Offline battle never entered the computed clock wait")
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
changed = self.manager.set_config(identifier, config["config"], config["revision"])
|
||||||
|
self.job(identifier, tick)
|
||||||
|
self.job(identifier, changed["job"])
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertTrue(worker.engine.battles.resumable_task_clock(record), record)
|
||||||
|
self.assertTrue(worker.engine._progression_cancel.is_set())
|
||||||
|
return identifier, worker, runtime, record
|
||||||
|
|
||||||
|
def ready(self, worker):
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.pending(worker.engine.snapshot)
|
||||||
|
journal.update(record, record["phase"], battle_ready_at=1)
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
|
||||||
|
def test_config_cancelled_computed_clock_resumes_on_reconcile_without_new_start(self):
|
||||||
|
identifier, worker, runtime, record = self.interrupted_clock()
|
||||||
|
saved = deepcopy(record["battle_data"])
|
||||||
|
self.ready(worker)
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.assertEqual(self.tick(identifier, worker)["result"]["kind"], "reconcile")
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
writes = [path for path in self.paths(before) if path != "masterService/masterQueryDetail"]
|
||||||
|
self.assertEqual(writes, ["taskService/taskCompleteStep"])
|
||||||
|
payload = next(payload for _, url, payload in fixtures.FakeClient.calls[before:]
|
||||||
|
if url.endswith("taskService/taskCompleteStep"))
|
||||||
|
self.assertEqual(payload["battleData"], saved)
|
||||||
|
self.assertEqual(runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["strategy_requested"])
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
|
||||||
|
def test_start_accepts_saved_computed_result_but_does_not_settle_inline(self):
|
||||||
|
identifier, worker, _, _ = self.interrupted_clock()
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertEqual(len(fixtures.FakeClient.calls), before)
|
||||||
|
self.assertEqual(self.manager.status(identifier)["strategy_state"], "recovering")
|
||||||
|
|
||||||
|
def test_computed_result_waits_for_deadline_and_manual_refresh_stays_read_only(self):
|
||||||
|
identifier, worker, runtime, _ = self.interrupted_clock()
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.pending(worker.engine.snapshot)
|
||||||
|
journal.update(record, record["phase"], battle_ready_at=time.time() + 3600)
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh"))
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertIsNotNone(journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertEqual(runtime.run.call_count, 1)
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertEqual(self.manager.status(identifier)["strategy_state"], "recovering")
|
||||||
|
|
||||||
|
def test_lost_resumed_settlement_reply_becomes_query_only_without_replay(self):
|
||||||
|
identifier, worker, runtime, _ = self.interrupted_clock()
|
||||||
|
self.ready(worker)
|
||||||
|
post = worker.engine.client.http.post
|
||||||
|
attempted = []
|
||||||
|
|
||||||
|
def lost_reply(url, *args, **kwargs):
|
||||||
|
if url.endswith("taskService/taskCompleteStep"):
|
||||||
|
attempted.append(url)
|
||||||
|
raise requests.ReadTimeout("offline lost settlement reply")
|
||||||
|
return post(url, *args, **kwargs)
|
||||||
|
|
||||||
|
with patch.object(worker.engine.client.http, "post", side_effect=lost_reply):
|
||||||
|
self.job(identifier, worker.enqueue("__tick"), status="failed")
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertTrue(record["settlement_dispatched"])
|
||||||
|
self.assertFalse(worker.engine.battles.resumable_task_clock(record))
|
||||||
|
for _ in range(3):
|
||||||
|
self.now += 121
|
||||||
|
worker.engine.last_heartbeat = self.now
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(attempted), 1)
|
||||||
|
self.assertEqual(runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
|
||||||
|
def test_manual_stop_keeps_computed_result_unsent_through_config_and_restart(self):
|
||||||
|
identifier, worker, _, _ = self.interrupted_clock()
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
self.ready(worker)
|
||||||
|
journal_path = worker.engine.battle_journal.path
|
||||||
|
evidence = journal_path.read_bytes()
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(journal_path.read_bytes(), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
self.manager.close()
|
||||||
|
self.manager = WebManager(self.root, start_scheduler=False, login_factory=fixtures.FakeLogin)
|
||||||
|
self.addCleanup(self.manager.close)
|
||||||
|
self.idle(identifier)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
self.assertEqual(journal_path.read_bytes(), evidence)
|
||||||
|
|
||||||
|
def test_stop_racing_authorized_reconcile_cancels_settlement_before_dispatch(self):
|
||||||
|
identifier, worker, _, _ = self.interrupted_clock()
|
||||||
|
self.ready(worker)
|
||||||
|
entered, release = threading.Event(), threading.Event()
|
||||||
|
poll = worker.engine.poll
|
||||||
|
journal_path = worker.engine.battle_journal.path
|
||||||
|
evidence = journal_path.read_bytes()
|
||||||
|
|
||||||
|
def held_poll(**kwargs):
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertIs(kwargs.get("resume_pending"), True)
|
||||||
|
entered.set()
|
||||||
|
self.assertTrue(release.wait(3))
|
||||||
|
return poll(**kwargs)
|
||||||
|
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=held_poll):
|
||||||
|
tick = worker.enqueue("__tick")
|
||||||
|
try:
|
||||||
|
self.assertTrue(entered.wait(3), self.manager.job(identifier, tick["id"]))
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
finally:
|
||||||
|
release.set()
|
||||||
|
self.job(identifier, tick, status="cancelled")
|
||||||
|
self.assertEqual(len(fixtures.FakeClient.calls), before)
|
||||||
|
self.assertEqual(journal_path.read_bytes(), evidence)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
|
||||||
|
def test_runtime_recovery_timeout_stays_blocked_after_single_local_retry(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
runtime = self.battle(identifier, worker, timed_out=True)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertEqual(record["execution_status"], "timed_out")
|
||||||
|
self.assertFalse(worker.engine.battles.resumable_task_clock(record))
|
||||||
|
self.assertNotIn("battle_data", record)
|
||||||
|
self.assertTrue(worker.engine.pending_battle_recovery()["resumable"])
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertEqual(record["runtime_recovery_attempts"], 1)
|
||||||
|
self.assertFalse(worker.engine.pending_battle_recovery()["resumable"])
|
||||||
|
evidence = worker.engine.battle_journal.path.read_bytes()
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
for _ in range(3):
|
||||||
|
self.now += 121
|
||||||
|
worker.engine.last_heartbeat = self.now
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertEqual(worker.engine.battle_journal.path.read_bytes(), evidence)
|
||||||
|
self.assertEqual(runtime.run.call_count, 2)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertFalse(state["running"])
|
||||||
|
self.assertTrue(state["strategy_requested"])
|
||||||
|
self.assertFalse(state["manual_stop"])
|
||||||
|
self.assertIn("本地战斗计算超时", state["strategy_message"])
|
||||||
|
self.assertIn("尚未提交结算", state["strategy_message"])
|
||||||
|
|
||||||
|
def test_stage_farming_timeout_reports_its_operation_without_promising_resolution(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
fixtures.ServiceTests.enable(self, identifier)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.begin(worker.engine.snapshot, {"kind": "stage_battle", "stage_id": "0102",
|
||||||
|
"difficulty": 1, "path": "stageService/stageStart", "task_id": 0})
|
||||||
|
journal.update(record, "unknown", start_response={"resCode": 0, "triggerEvent": False, "stageEvent": None},
|
||||||
|
execution_status="timed_out", terminal_reason="worker_wall_clock_limit",
|
||||||
|
message="战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertTrue(state["connected"])
|
||||||
|
self.assertFalse(state["running"])
|
||||||
|
self.assertIn("0102", state["strategy_message"])
|
||||||
|
self.assertIn("本地战斗计算超时", state["strategy_message"])
|
||||||
|
worker.schedule.monitor(False)
|
||||||
|
reason = worker._pending_execution_reason()
|
||||||
|
self.assertNotIn("后台继续", reason)
|
||||||
|
self.assertNotIn("自动恢复", reason)
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
self.assertEqual(worker.config["policy"]["keep_money"], config["config"]["policy"]["keep_money"])
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
intent = json.loads((worker.profile_root / "run_intent.json").read_text(encoding="utf-8"))
|
||||||
|
self.assertTrue(intent["roles"][worker.active_identity])
|
||||||
|
|
||||||
|
def test_config_cancellation_before_start_dispatch_replans_without_unknown_barrier(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
runtime = self.battle(identifier, worker, timed_out=True)
|
||||||
|
update = worker.engine.battle_journal.update
|
||||||
|
changed = []
|
||||||
|
|
||||||
|
def cancel_before_send(record, phase, **fields):
|
||||||
|
update(record, phase, **fields)
|
||||||
|
if phase == "start_pending":
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
changed.append(self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
|
||||||
|
with patch.object(worker.engine.battle_journal, "update", side_effect=cancel_before_send):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.job(identifier, changed[0])
|
||||||
|
self.assertNotIn("battleService/battleStart", self.paths())
|
||||||
|
self.assertFalse(worker.engine._progression_pending())
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertIsNone(worker.engine.progression_planner.pending(worker.engine.snapshot))
|
||||||
|
runtime.run.assert_not_called()
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
|
||||||
|
def test_internal_pending_pause_does_not_revoke_generation_or_persist_manual_stop(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
generation = worker._generation
|
||||||
|
|
||||||
|
def paused(**kwargs):
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.begin(worker.engine.snapshot, {"kind": "stage_battle", "stage_id": "0102"})
|
||||||
|
journal.update(record, "unknown", message="请求结果未知")
|
||||||
|
worker.engine.auto = False
|
||||||
|
return worker.engine.snapshot, [], "请求结果未知"
|
||||||
|
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=paused):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(worker._generation, generation)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
self.assertFalse(self.manager.status(identifier)["manual_stop"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Public account summaries preserve execution intent without private recovery data."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from ranch_web.tests import test_api as fixtures
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryStatusApiTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ApiTests.setUp
|
||||||
|
|
||||||
|
def test_accounts_and_status_preserve_blocked_intent_and_explicit_stop(self):
|
||||||
|
source = self.manager.accounts[self.account_id]
|
||||||
|
fields = {"strategy_requested": True, "manual_stop": False, "strategy_state": "blocked",
|
||||||
|
"strategy_message": "本地战斗计算超时,尚未提交结算", "strategy_retry_at": None}
|
||||||
|
source.update(fields, running=False, journal={"payload": "PRIVATE_RECOVERY"})
|
||||||
|
for values in (fields, fields | {"strategy_requested": False, "manual_stop": True,
|
||||||
|
"strategy_state": "stopped", "strategy_message": "已按用户选择停止策略"}):
|
||||||
|
source.update(values)
|
||||||
|
for url in ("/api/accounts", self.url + "/status"):
|
||||||
|
with self.subTest(url=url, state=values["strategy_state"]):
|
||||||
|
response = self.client.get(url)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
body = response.json()
|
||||||
|
summary = body[0] if isinstance(body, list) else body
|
||||||
|
for field, expected in values.items():
|
||||||
|
self.assertEqual(summary.get(field), expected, field)
|
||||||
|
self.assertFalse(summary["running"])
|
||||||
|
self.assertNotIn("journal", summary)
|
||||||
|
self.assertNotIn("PRIVATE_RECOVERY", response.text)
|
||||||
|
|
||||||
|
def test_strategy_message_uses_the_connection_error_redactor(self):
|
||||||
|
source = self.manager.accounts[self.account_id]
|
||||||
|
for message in ("本地计算失败 token=STATUS_PRIVATE C:/private/battle.json", "Traceback: STATUS_PRIVATE"):
|
||||||
|
source.update(strategy_message=message, connection_message=message)
|
||||||
|
response = self.client.get(self.url + "/status")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
body = response.json()
|
||||||
|
self.assertIsInstance(body.get("strategy_message"), str)
|
||||||
|
self.assertEqual(body["strategy_message"], body["connection_message"])
|
||||||
|
self.assertNotIn("STATUS_PRIVATE", response.text)
|
||||||
|
self.assertNotIn("C:/private", response.text)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
+1
-1
@@ -463,7 +463,7 @@ STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行
|
|||||||
STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "unlocked", "unaccepted": "unlocked", "offered": "unlocked", "ready": "ready_to_reward",
|
STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "unlocked", "unaccepted": "unlocked", "offered": "unlocked", "ready": "ready_to_reward",
|
||||||
"completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
|
"completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
|
||||||
STATE_FILTERS = [("current", "当前(进行中 + 待接取 + 待领奖)"), ("received", "进行中"), ("unlocked", "待接取"), ("ready_to_reward", "待领奖"), ("finished", "已完成"), ("locked", "未解锁"), ("", "全部状态")]
|
STATE_FILTERS = [("current", "当前(进行中 + 待接取 + 待领奖)"), ("received", "进行中"), ("unlocked", "待接取"), ("ready_to_reward", "待领奖"), ("finished", "已完成"), ("locked", "未解锁"), ("", "全部状态")]
|
||||||
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件", "completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"}
|
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件", "completed": "已完成", "cancelled": "已取消", "abandoned": "已放弃(本地计算失败)", "timeout": "超时", "unknown": "结果待核对"}
|
||||||
CHINA_TIME = timezone(timedelta(hours=8))
|
CHINA_TIME = timezone(timedelta(hours=8))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user