fix: recover interrupted Web battles in 2.0.10

This commit is contained in:
AttilaNet
2026-11-14 10:56:43 +08:00
parent bbdf578c87
commit 9f3945a717
24 changed files with 1912 additions and 127 deletions
+16 -9
View File
@@ -1363,6 +1363,8 @@ class ExperimentalBattleRuntime:
diagnostics=[{"code": "static_data", "message": str(exc)}])
def run(self, request, *, cancel_event=None, timeout=30.0):
import tempfile
timeout = _number(timeout, "timeout")
if timeout < 0:
raise SimulationInputError("timeout must be nonnegative")
@@ -1380,13 +1382,18 @@ class ExperimentalBattleRuntime:
started = time.monotonic()
process = None
try:
process = subprocess.Popen(
[sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"],
cwd=str(Path(__file__).resolve().parent.parent),
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
pending_input = wire
# 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(
[sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"],
cwd=str(Path(__file__).resolve().parent.parent),
stdin=input_stream, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
while True:
if cancel_event is not None and cancel_event.is_set():
return _execution_failure("cancelled", "worker_cancelled")
@@ -1394,10 +1401,10 @@ class ExperimentalBattleRuntime:
if left <= 0:
return _execution_failure("timeout", "worker_wall_clock_limit")
try:
stdout, stderr = process.communicate(input=pending_input, timeout=min(.05, left))
stdout, stderr = process.communicate(timeout=min(.05, left))
break
except subprocess.TimeoutExpired:
pending_input = None
pass
if len(stdout) > MAX_WIRE_BYTES or len(stderr) > 65536:
return _execution_failure("error", "worker_output_exceeds_limit")
result = json.loads(stdout)
+268 -49
View File
@@ -172,6 +172,9 @@ class BattleJournal:
value(intent, "stage_id", ""), value(intent, "difficulty", "1"))})
if value(intent, "token") and 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["records"].append(record)
state["pending"] = record["attempt_id"]
@@ -428,7 +431,8 @@ class BattleOrchestrator:
"experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics",
"ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events",
"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")
if trace is None:
trace = value(result, "events")
@@ -441,8 +445,88 @@ class BattleOrchestrator:
evidence["trace"] = public_data(trace)
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):
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
duration = None
for field, scale in (("model_elapsed_ms", .001), ("battle_elapsed_ms", .001), ("elapsed_ms", .001),
@@ -471,39 +555,154 @@ class BattleOrchestrator:
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
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
def resumable_task_clock(record):
common = bool(record and ((record.get("kind") == "progression_battle" and record.get("task_id"))
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("experimental_settlement_eligible") is True and record.get("terminal") is True
and record.get("approximate") is True and record.get("faithful") is False
common = bool(record and record.get("kind") in ("progression_battle", "map_battle", "stage_battle", "battle", "task_battle")
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("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
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)
if not common:
return False
if (record.get("kind") == "map_battle" and record.get("phase") == "settlement_acknowledged"
and record.get("settlement_confirmed") is True):
if record.get("phase") in ("record_pending", "record_unknown"):
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)
and record["response"].get("resCode", 0) in (0, "0"))
return (record.get("phase") in ("unknown", "waiting_for_battle_clock")
and record["response"].get("resCode", 0) in (0, "0")
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 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
record.get("phase") == "runtime_complete" or
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):
"""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:
self.journal.reload()
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 ""
if str(record.get("role_id")) != str(role_id(snapshot)):
return ""
if any(str(record.get(key)) != str(value(intent, key)) for key in
("kind", "task_id", "task_type_id", "step_number")):
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"))
if task_battle:
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")),
"taskTypeId": str(record["task_type_id"]) if task_battle else None,
"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"]
position = data.get("battlePosition")
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")
if ready is None:
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")
if any(type(number) not in (int, float) or not math.isfinite(number) or number < 0
for number in (duration, stamp)):
@@ -536,7 +758,7 @@ class BattleOrchestrator:
return "已核对保存的战果;尚未到结算时间,2分钟内自动复查"
try:
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)
if self.observer:
self.observer("loss", intent, None)
@@ -552,17 +774,18 @@ class BattleOrchestrator:
response = self._call(client, path, payload, cancel=cancel)
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"))
if not task_battle:
self._record(client, record, record["stage_id"], True)
if not task_battle and not record.get("record_confirmed"):
self._record(client, record, record["stage_id"], True, cancel=cancel)
if self.observer:
self.observer("settled", intent, response)
elif task_battle:
self.journal.checkpoint(snapshot, intent, response)
self.journal.finish(snapshot, record, "win", "已自动续交保存的战果;未重新开战或重新模拟")
self.journal.finish(snapshot, record, "win", "已恢复此入场的战果并确认结算;未重新开战")
return record["message"]
except CancelledBeforeDispatch:
self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart" if task_battle else "stageService/stageStart",
settlement_dispatched=False, resume_clock_ready=True)
if not record.get("settlement_confirmed"):
self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart" if task_battle else "stageService/stageStart",
settlement_dispatched=False, resume_clock_ready=True)
return "策略已停止,保存的战果将在重新开启后续交"
except Exception as error:
self._unknown(record, "续交请求结果未确认,将自动查询状态,不重复发送", error_type=type(error).__name__)
@@ -601,24 +824,31 @@ class BattleOrchestrator:
return "任务 / 战斗已取消,未开始"
record = self.journal.begin(snapshot, intent)
try:
self.journal.update(record, "prepared", start_dispatched=False)
if self.observer:
self.observer("started", intent, None)
if value(intent, "task_id"):
path, payload = "battleService/battleStart", {"battleType": "task", "taskTypeId": str(value(intent, "task_type_id"))}
else:
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,
resource_identity=(request.get("original_data") or {}).get("manifest", {}).get("source"))
try:
started = self._call(client, path, payload, cancel=cancel)
except CancelledBeforeDispatch:
self.journal.update(record, "start_pending", start_dispatched=False)
if self.observer:
self.observer("cancelled_before_start", intent, None)
self.journal.finish(snapshot, record, "cancelled", "开战请求尚未发送,已取消;未消耗入场资源")
return record["message"]
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"):
reward = event_reward(started)
if reward is not None:
@@ -638,38 +868,17 @@ class BattleOrchestrator:
supported, reason = self.inspect(request)
if not supported:
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:
return self._unknown(record, "探索事件或开战状态未知,等待核对")
if cancel.is_set():
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)
evidence = self.runtime_evidence(result, mode)
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):
if not self.accept_runtime_result(record, request, result, battle_started, cancel):
return record["message"]
data = record["battle_data"]
if not data["win"]:
if not value(intent, "task_id") or value(intent, "battle_kind") == "passStage":
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}
else:
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)
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"))
@@ -700,6 +909,11 @@ class BattleOrchestrator:
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
self.journal.finish(snapshot, record, "win", 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:
self._unknown(record, "任务 / 战斗请求或运行未确认;禁止自动重试", error_type=type(error).__name__)
raise
@@ -739,12 +953,17 @@ class BattleOrchestrator:
return response
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:
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:
self.journal.update(record, "record_unknown", message="战果记录未确认,不能重放战斗")
raise
self.journal.update(record, "record_acknowledged", record_confirmed=True, record_response=gameplay_response(response))
def _unknown(self, record, message, **fields):
phase = "record_unknown" if record["phase"] == "record_unknown" else "unknown"
+55 -14
View File
@@ -588,14 +588,43 @@ class Engine:
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)
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)
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 ""
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",
"stage_id", "difficulty", "battle_kind", "team", "path")}
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._map_policy(), cancel=self._progression_cancel)
"stage_id", "difficulty", "battle_kind", "team", "path", "source_task_id", "source_task_type_id", "source_step_number")}
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
if not pending or not isinstance(pending.get("intent"), dict):
return ""
@@ -607,8 +636,10 @@ class Engine:
if intent.token in issued and issued[intent.token] != intent.to_dict():
return ""
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),
cancel=self._progression_cancel)
cancel=cancel)
def _battle_capability(self, intent):
try:
@@ -648,7 +679,11 @@ class Engine:
supported, reason = self._commission_offer_checks[key]
if not supported:
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"):
supported, reason = self._battle_capability(intent)
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"))
reason = row.get("block_reason") or row.get("blocked_reason") or ""
if row.get("battle_kind") in battle_kinds:
supported, runtime_reason = reasons.get(str(row.get("task_type_id")),
(False, "战斗运行时能力尚未核对;配置存在不代表已支持实战"))
row["supported"] = bool(source_supported and supported and not reason)
supported, runtime_reason = reasons.get(str(row.get("task_type_id")), (None, ""))
reason = reason or runtime_reason
row["supported"] = False if not source_supported or reason else supported
else:
row["supported"] = bool(source_supported and not 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
def _battle_request(self, snapshot, intent, policy, request):
@@ -1331,7 +1367,10 @@ class Engine:
@single_flight
@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
settled = False
if self.demo:
@@ -1355,7 +1394,7 @@ class Engine:
if self._progression_pending():
self.pending_hatches = []
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:
self.last_executed = True
if not self.battle_journal.pending(self.snapshot):
@@ -1364,7 +1403,9 @@ class Engine:
self.stage_cache.get(self.snapshot, refresh=True)
return self.snapshot, self.plans(), recovered
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)
if explore_pending or self._breakthrough_pending:
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()