fix: continue hidden sweep battles safely in Web 2.0.12

This commit is contained in:
AttilaNet
2026-11-14 12:41:11 +08:00
parent 7ca2ee13e3
commit 69b59e18dd
21 changed files with 1691 additions and 102 deletions
+275 -57
View File
@@ -30,7 +30,7 @@ from .drop_statistics import event_reward
from .maps import stages
from .resource_stages import resource_entry_reason, item_requirements, available_item_count
from .quests import indexed, stage_has_level
from .sweeping import SweepPolicy
from .sweeping import SweepPolicy, hidden_stage_id
from .team_availability import team_availability_reason
@@ -87,6 +87,8 @@ def gameplay_response(response):
_locks_guard = threading.Lock()
_locks = {}
SWEEP_KINDS = ("map_sweep", "sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep")
COMBAT_KINDS = ("progression_battle", "map_battle", "stage_battle", "battle", "task_battle") + SWEEP_KINDS
def account_lock(path):
@@ -155,7 +157,7 @@ class BattleJournal:
self.reload()
return deepcopy(list(reversed(self.role(snapshot)["records"])))
def begin(self, snapshot, intent, *, kind=None):
def begin(self, snapshot, intent, *, kind=None, sweep_entry=None, sweep_phase=None):
if self.pending(snapshot):
raise ValueError("有待核对的任务 / 战斗,禁止重复开始")
record = {name: public_data(value(intent, name)) for name in (
@@ -170,6 +172,12 @@ class BattleJournal:
"loop_time": snapshot.raw.get("history", {}).get("loopTaskTime"),
"passed": stage_has_level(snapshot.raw.get("history", {}), "passStage",
value(intent, "stage_id", ""), value(intent, "difficulty", "1"))})
if sweep_entry is not None:
legacy_archive = sweep_phase == "legacy_hidden_archived" and sweep_entry.get("role_id") is None
if (not legacy_archive and str(sweep_entry.get("role_id")) != role_id(snapshot)) or not sweep_entry.get("sampleId"):
raise ValueError("扫荡交接角色或原始编号缺失")
record.update(sweep_sample_id=sweep_entry["sampleId"], sweep_entry=public_data(sweep_entry),
sweep_entry_digest=digest(public_data(sweep_entry)), phase=sweep_phase or record["phase"])
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"):
@@ -190,9 +198,10 @@ class BattleJournal:
record.update(phase="done", outcome=outcome, message=message, finished_at=time.time())
if state["pending"] == record["attempt_id"]:
state["pending"] = None
if outcome == "loss" and record.get("kind") != "map_battle":
shared_loss_budget = record.get("kind") != "map_battle" and not record.get("sweep_sample_id")
if outcome == "loss" and shared_loss_budget:
state["losses"] += 1
elif outcome == "win" and record.get("kind") != "map_battle":
elif outcome == "win" and shared_loss_budget:
state["losses"] = 0
self.save()
@@ -455,7 +464,11 @@ class BattleOrchestrator:
def save_combat_request(self, record, request):
if request.get("battle_mode") != "experimental":
return {}
if request.get("battle_kind") != "hidden":
return {}
combat = public_data(request)
return {"combat_request": combat, "combat_request_digest": digest(combat),
"combat_resource_digest": self.combat_resource_digest()}
from .battle_simulator import _transport_request
combat = public_data(_transport_request(request))
raw = combat.get("roster")
@@ -560,9 +573,12 @@ class BattleOrchestrator:
response = record.get("start_response")
task = bool(record.get("task_id"))
path = "battleService/battleStart" if task else "stageService/stageStart"
hidden = hidden_stage_id(response)
confirmed_hidden = (not task and hidden is not None and record.get("battle_kind") == "hidden"
and hidden == str(record.get("stage_id")) and str(record.get("difficulty")) == "1")
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))
or type(response.get("triggerEvent")) is int and response["triggerEvent"] == 0 or confirmed_hidden))
@staticmethod
def source_matches(record, snapshot):
@@ -595,7 +611,7 @@ class BattleOrchestrator:
@staticmethod
def resumable_task_clock(record):
common = bool(record and record.get("kind") in ("progression_battle", "map_battle", "stage_battle", "battle", "task_battle")
common = bool(record and record.get("kind") in COMBAT_KINDS
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)
@@ -628,7 +644,7 @@ class BattleOrchestrator:
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"):
if record.get("kind") not in COMBAT_KINDS:
return status("blocked", record.get("message") or "任务请求待核对,不能按战斗恢复")
if snapshot and str(record.get("role_id")) != role_id(snapshot):
return status("blocked", "角色与原入场记录不匹配,保留待核对记录")
@@ -650,6 +666,9 @@ class BattleOrchestrator:
return status("unsent", "开战请求尚未发送,可取消本地准备记录")
if not self.confirmed_start(record):
return status("blocked", "开战请求结果未确认,禁止重新入场或自动退出")
if (record.get("sweep_sample_id") and record.get("runtime_not_started") is True
and not record.get("combat_request") and self.hidden_sweep_inputs(record)):
return status("prepare_hidden_sweep", "隐藏入场及原始队伍已保存,可继续本次战斗")
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"):
@@ -665,7 +684,8 @@ class BattleOrchestrator:
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")
if (record.get("battle_mode") != "experimental" and record.get("battle_kind") != "hidden"
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", "入场已确认且结算未发送,可用保存的原始输入恢复一次本地战斗")
@@ -728,7 +748,7 @@ class BattleOrchestrator:
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)
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
if not self.accept_runtime_result(record, request, result, started, cancel):
return record["message"]
except Exception as error:
@@ -763,6 +783,7 @@ class BattleOrchestrator:
if self.observer:
self.observer("loss", intent, None)
self.journal.finish(snapshot, record, "loss", "打不过(保存的模拟结果);未提交胜利结算")
self._finish_hidden_sweep(snapshot, record)
return record["message"]
response = record.get("response") if record.get("settlement_confirmed") else None
if response is None:
@@ -771,9 +792,10 @@ class BattleOrchestrator:
if task_battle:
payload.update(taskId=int(record["task_id"]), taskTypeId=str(record["task_type_id"]), removeIds=None)
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, require_code=record.get("battle_kind") == "hidden")
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"))
self._remember_hidden_sweep(snapshot, record)
if not task_battle and not record.get("record_confirmed"):
self._record(client, record, record["stage_id"], True, cancel=cancel)
if self.observer:
@@ -781,6 +803,7 @@ class BattleOrchestrator:
elif task_battle:
self.journal.checkpoint(snapshot, intent, response)
self.journal.finish(snapshot, record, "win", "已恢复此入场的战果并确认结算;未重新开战")
self._finish_hidden_sweep(snapshot, record)
return record["message"]
except CancelledBeforeDispatch:
if not record.get("settlement_confirmed"):
@@ -861,54 +884,15 @@ class BattleOrchestrator:
if flag is not False and not (type(flag) is int and flag == 0):
event = started.get("stageEvent")
if isinstance(event, dict) and event.get("hideStageId") is not None:
hidden = str(event["hideStageId"])
fields = asdict(intent) if is_dataclass(intent) else dict(intent) if isinstance(intent, dict) else vars(intent).copy()
fields.update(stage_id=hidden, difficulty="1", battle_kind="hidden")
request = self.request(snapshot, fields, policy)
request = self._hidden_request(record, snapshot, intent, policy, started)
if request is None:
return self._unknown(record, "隐藏关卡编号或原入场证据无效,等待核对")
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.save_combat_request(record, request))
else:
return self._unknown(record, "探索事件或开战状态未知,等待核对")
if cancel.is_set():
return self._unknown(record, "开战后已取消,等待服务器状态核对")
self.journal.update(record, "running", runtime_not_started=False)
result = self.runtime.run(request.get("runtime_request", request), cancel_event=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)
if self.observer:
self.observer("loss", intent, None)
label = "实验模型战败(近似)" if mode == "experimental" else "实际战败"
self.journal.finish(snapshot, record, "loss", label + ";未提交胜利结算或推进任务")
return label + ";已停止此轮任务推进"
if value(intent, "task_id"):
path, payload = "taskService/taskCompleteStep", {"taskId": int(value(intent, "task_id")),
"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, 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"))
if value(intent, "task_id"):
if self.observer:
self.observer("settled", intent, response)
else:
self.journal.checkpoint(snapshot, intent, response)
else:
self._record(client, record, request["stage_id"], True,
cancel=None if value(intent, "kind") == "map_battle" else cancel)
if self.observer:
self.observer("settled", intent, response)
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
self.journal.finish(snapshot, record, "win", label + ",结算接口已确认;后续进度以服务器快照核对")
return label + ",已确认对应结算"
return self._fight(client, snapshot, intent, request, record, battle_started, cancel)
except CancelledBeforeDispatch:
if not record.get("settlement_confirmed"):
self.journal.update(record, "waiting_for_battle_clock", path=record["start_path"],
@@ -918,6 +902,225 @@ class BattleOrchestrator:
self._unknown(record, "任务 / 战斗请求或运行未确认;禁止自动重试", error_type=type(error).__name__)
raise
def _hidden_request(self, record, snapshot, intent, policy, started):
hidden = hidden_stage_id(started)
if hidden is None:
return None
fields = asdict(intent) if is_dataclass(intent) else dict(intent) if isinstance(intent, dict) else vars(intent).copy()
fields.update(stage_id=hidden, difficulty="1", battle_kind="hidden")
# Preserve the source intent for policies/observers, and the actual
# hidden BattlePosition for every runtime/settlement/recovery path.
self.journal.update(record, "hidden_started",
parent_stage_id=record.get("parent_stage_id") or record["stage_id"],
parent_difficulty=record.get("parent_difficulty") or record["difficulty"],
stage_id=hidden, difficulty="1", battle_kind="hidden", runtime_not_started=True)
request = self.request(snapshot, fields, policy)
self.journal.update(record, "hidden_started", **self.save_combat_request(record, request),
team=policy.team, battle_mode=request.get("battle_mode", "original"))
return request
def _remember_hidden_sweep(self, snapshot, record):
if (self.sweeper is not None and record.get("sweep_sample_id")
and record.get("settlement_confirmed") is True):
self.sweeper.remember_map_reward(snapshot, record, record.get("response"))
self.sweeper.last_outcome = "hidden_win"
def _finish_hidden_sweep(self, snapshot, record):
if not self.sweeper or not record.get("sweep_sample_id") or record.get("outcome") not in ("win", "loss"):
return
if str(record.get("role_id")) != role_id(snapshot):
return
self._remember_hidden_sweep(snapshot, record)
self.sweeper.last_outcome = "hidden_" + record["outcome"]
def handoff_sweep(self, snapshot):
"""Move a confirmed hidden entry into the journal without a game write."""
if self.sweeper is None:
return None
with self.journal.lock:
self.journal.reload()
pending = self.sweeper.state.get("pending")
if not isinstance(pending, dict):
return None
hidden = hidden_stage_id(pending.get("start_response"))
if (not hidden or pending.get("hidden_stage_id") not in (None, hidden)
or str(pending.get("role_id")) != role_id(snapshot)
or pending.get("start_confirmed") is not True
or pending.get("start_path") != "stageService/stageStart"
or pending.get("phase") not in ("hidden_started", "开始请求待确认") or not pending.get("sampleId")):
return None
if pending.get("phase") != "hidden_started" or pending.get("hidden_stage_id") is None:
pending.update(phase="hidden_started", hidden_stage_id=hidden)
self.sweeper.save()
record = self.journal.pending(snapshot)
completed = next((row for row in self.journal.role(snapshot)["records"]
if row.get("sweep_sample_id") == pending["sampleId"] and row.get("phase") == "done"), None)
if completed:
if (record or completed.get("sweep_entry") != pending or completed.get("outcome") not in ("win", "loss")
or completed.get("record_confirmed") is not True
or completed.get("outcome") == "win" and completed.get("settlement_confirmed") is not True):
return None
self._finish_hidden_sweep(snapshot, completed)
self.sweeper.state["pending"] = None
self.sweeper.save()
return completed
install = not record or record.get("sweep_sample_id") != pending["sampleId"]
origin = pending.get("origin") or ({name: record.get(name) for name in ("kind", "stage_id", "difficulty",
"battle_kind", "task_id", "task_type_id", "step_number", "source_task_id", "source_task_type_id", "source_step_number",
"battle_mode")} if record else {"kind": "map_sweep", "stage_id": pending["stage"],
"difficulty": str(pending["level"]), "battle_kind": "sweep"})
if record and record.get("sweep_sample_id") == pending["sampleId"]:
if record.get("sweep_entry") != pending:
return None
install = record.get("phase") == "prepared" and not record.get("start_dispatched")
else:
if record:
if (record.get("kind") not in SWEEP_KINDS or record.get("sweep_sample_id")
or str(record.get("stage_id")) != str(pending["stage"])
or str(record.get("difficulty")) != str(pending["level"])
or record.get("phase") not in ("prepared", "sweep_pending", "unknown")
or record.get("start_dispatched") or record.get("settlement_dispatched") or record.get("record_dispatched")):
return None
else:
record = self.journal.begin(snapshot, origin, sweep_entry=pending)
if install:
self.journal.update(record, "hidden_started", sweep_sample_id=pending["sampleId"],
sweep_entry=deepcopy(pending), parent_stage_id=str(pending["stage"]), parent_difficulty=str(pending["level"]),
stage_id=hidden, difficulty="1", battle_kind="hidden", team=pending.get("team") or "teamA",
battle_mode=origin.get("battle_mode", "experimental"), start_path=pending["start_path"],
path=pending["start_path"], start_response=pending["start_response"], start_confirmed=True,
start_confirmed_at=pending.get("start_confirmed_at"), start_dispatched=True,
runtime_not_started=True, settlement_dispatched=False, record_dispatched=False,
sweep_entry_digest=digest(pending))
# The journal now owns both the response and original inputs. This
# also lets the existing Web Start gate use battle recovery.
self.sweeper.state["pending"] = None
self.sweeper.save()
return record
def archive_cancelled_sweep(self, snapshot):
"""Release only an explicitly cancelled, never-settled sweep entry."""
pending = self.sweeper.state.get("pending") if self.sweeper else None
if not isinstance(pending, dict) or pending.get("phase") != "cancelled_before_sweep_settlement":
return ""
response = pending.get("start_response") or {}
flag = response.get("triggerEvent")
if (pending.get("role_id") != role_id(snapshot) or pending.get("start_confirmed") is not True
or pending.get("start_path") != "stageService/stageStart" or pending.get("settlement_dispatched") is not False
or pending.get("record_dispatched") is not False or hidden_stage_id(response) is not None
or not (flag is False or type(flag) is int and flag == 0)
or response.get("resCode", 0) not in (0, "0") or not pending.get("sampleId")):
return ""
with self.journal.lock:
self.journal.reload()
record = self.journal.pending(snapshot)
if record and (record.get("kind") not in SWEEP_KINDS
or str(record.get("stage_id")) != str(pending["stage"])
or str(record.get("difficulty")) != str(pending["level"])
or record.get("settlement_dispatched") or record.get("record_dispatched")
or record.get("phase") not in ("sweep_pending", "unknown", "cancelled_sweep_archived")):
return ""
done = next((row for row in self.journal.role(snapshot)["records"]
if row.get("sweep_sample_id") == pending["sampleId"] and row.get("sweep_entry") == pending
and row.get("outcome") == "abandoned_cancelled_sweep"), None)
message = "扫荡入场已确认,结算尚未发送,停止后已本地放弃;未结算奖励"
if done is None:
record = record or self.journal.begin(snapshot, pending.get("origin") or {
"kind": "map_sweep", "stage_id": pending["stage"], "difficulty": pending["level"]},
sweep_entry=pending, sweep_phase="cancelled_sweep_archived")
self.journal.update(record, "cancelled_sweep_archived", sweep_sample_id=pending["sampleId"],
sweep_entry=deepcopy(pending), archival_evidence={"role_id": role_id(snapshot), "snapshot_read_at": time.time(),
"settlement_never_dispatched": True})
self.journal.finish(snapshot, record, "abandoned_cancelled_sweep", message)
self.sweeper.state["pending"] = None
self.sweeper.save()
return message
@staticmethod
def hidden_sweep_inputs(record):
entry = record.get("sweep_entry") or {}
raw = entry.get("entry_snapshot")
return (record.get("sweep_sample_id") and entry.get("sampleId") == record["sweep_sample_id"]
and digest(entry) == record.get("sweep_entry_digest") and isinstance(raw, dict)
and str((raw.get("master") or {}).get("id")) == str(record.get("role_id"))
and entry.get("team") == record.get("team") and hidden_stage_id(entry.get("start_response")) == record.get("stage_id"))
def continue_sweep(self, client, snapshot, policy, *, cancel=None):
"""Complete an already entered hidden sweep; never dispatch stageStart."""
cancel = cancel or threading.Event()
with self.journal.lock:
self.handoff_sweep(snapshot)
record = self.journal.pending(snapshot)
if not record or not record.get("sweep_sample_id") or not policy.enabled or cancel.is_set():
return ""
status = self.recovery_status(record, snapshot=snapshot)
if not status["resumable"]:
return status["message"]
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number", "stage_category",
"stage_id", "difficulty", "battle_kind", "team", "source_task_id", "source_task_type_id", "source_step_number")}
if status["state"] != "prepare_hidden_sweep":
return self.resume_task_clock(client, snapshot, intent, policy, cancel=cancel)
entry = record["sweep_entry"]
original = SimpleNamespace(raw=deepcopy(entry["entry_snapshot"]), now=entry.get("entry_snapshot_now", snapshot.now))
chosen = SimpleNamespace(**(vars(policy) | {"team": record["team"], "battle_mode": record["battle_mode"]}))
try:
request = self._hidden_request(record, original, intent, chosen, record["start_response"])
supported, reason = self.inspect(request)
if not supported:
return self._unknown(record, "隐藏关卡待处理:" + reason)
return self._fight(client, snapshot, intent, request, record, self.clock(), cancel)
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
def _fight(self, client, snapshot, intent, request, record, battle_started, cancel):
if cancel.is_set():
return self._unknown(record, "开战后已取消,等待服务器状态核对")
self.journal.update(record, "running", runtime_not_started=False)
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
if not self.accept_runtime_result(record, request, result, battle_started, cancel):
return record["message"]
data = record["battle_data"]
mode = request.get("battle_mode", "original")
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)
if self.observer:
self.observer("loss", intent, None)
label = "实验模型战败(近似)" if mode == "experimental" else "实际战败"
self.journal.finish(snapshot, record, "loss", label + ";未提交胜利结算或推进任务")
self._finish_hidden_sweep(snapshot, record)
return label + ";已停止此轮任务推进"
if value(intent, "task_id"):
path, payload = "taskService/taskCompleteStep", {"taskId": int(value(intent, "task_id")),
"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, settlement_dispatched=True)
response = self._call(client, path, payload, cancel=cancel, require_code=record.get("battle_kind") == "hidden")
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"))
self._remember_hidden_sweep(snapshot, record)
if value(intent, "task_id"):
if self.observer:
self.observer("settled", intent, response)
else:
self.journal.checkpoint(snapshot, intent, response)
else:
self._record(client, record, request["stage_id"], True,
cancel=None if value(intent, "kind") == "map_battle" else cancel)
if self.observer:
self.observer("settled", intent, response)
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
self.journal.finish(snapshot, record, "win", label + ",结算接口已确认;后续进度以服务器快照核对")
self._finish_hidden_sweep(snapshot, record)
return label + ",已确认对应结算"
def _sweep(self, client, snapshot, intent, policy, cancel):
if not policy.allow_sweep or self.sweeper is None or value(intent, "task_id"):
return "任务战斗或当前策略不允许普通扫荡"
@@ -927,6 +1130,10 @@ class BattleOrchestrator:
return "仅三个难度全通且客户端允许的普通关卡可扫荡"
if cancel.is_set():
return "扫荡已取消,未开始"
origin = {name: public_data(value(intent, name)) for name in ("kind", "task_id", "task_type_id", "step_number",
"stage_id", "difficulty", "battle_kind", "source_task_id", "source_task_type_id", "source_step_number")}
origin["battle_mode"] = value(policy, "battle_mode", "experimental")
battle_policy = policy
policy = SweepPolicy(enabled=True, team=policy.team, keep_stamina=policy.reserve_ti,
rules={stage.stage_id: {"enabled": True, "level": stage.level, "limit": self.sweeper.used(snapshot, stage) + 1}})
record = self.journal.begin(snapshot, intent)
@@ -934,29 +1141,40 @@ class BattleOrchestrator:
try:
if self.observer:
self.observer("started", intent, None)
response = self.sweeper.run(client, snapshot, stage, policy)
response = self.sweeper.run(client, snapshot, stage, policy, cancel=cancel, origin=origin)
if self.sweeper.last_outcome == "hidden":
return self.continue_sweep(client, snapshot, battle_policy, cancel=cancel)
if self.observer:
self.observer("event" if self.sweeper.last_outcome == "event" else "settled", intent, response)
self.journal.finish(snapshot, record, "event" if self.sweeper.last_outcome == "event" else "sweep", "复用客户端已有扫荡路径")
return "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡已完成"
except CancelledBeforeDispatch:
if self.sweeper.state.get("pending") is None:
self.journal.finish(snapshot, record, "cancelled", "扫荡入场尚未发送,已取消")
return "扫荡已停止,已保留未确认记录"
except Exception as error:
record = self.journal.pending(snapshot) or record
self._unknown(record, "扫荡结果未确认,禁止自动重试", error_type=type(error).__name__)
raise
@staticmethod
def _call(client, path, payload, *, cancel=None):
def _call(client, path, payload, *, cancel=None, require_code=False):
if cancel is not None and cancel.is_set():
raise CancelledBeforeDispatch()
response = client.call(path, payload)
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
raise ValueError("游戏接口未返回可信的成功响应")
if require_code and not (type(response.get("resCode")) is int and response["resCode"] == 0
or type(response.get("resCode")) is str and response["resCode"] == "0"):
raise ValueError("隐藏关卡写请求缺少明确成功回包,保留待核对且禁止重发")
return response
def _record(self, client, record, stage, win, *, cancel=None):
phase = record["phase"]
self.journal.update(record, "record_pending", record_dispatched=True, record_result=win)
try:
response = 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, require_code=record.get("battle_kind") == "hidden")
except CancelledBeforeDispatch:
self.journal.update(record, phase, record_dispatched=False)
raise
+99 -2
View File
@@ -134,6 +134,8 @@ class Engine:
self._battle_roster = None
self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime}
self._selected_battle_mode = "original"
self._sweep_recovery_cache = {}
self._sweep_recovery_message = ""
def _map_catalog(self):
if self.resource_catalog is None:
@@ -597,7 +599,7 @@ class Engine:
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
origin = ("自动扫荡" if record.get("kind") in ("map_battle", "map_sweep") else
"自动委托" if self._is_commission(record) else "自动主线")
return {"state": "blocked_policy", "resumable": False,
"message": "等待启用" + origin + "来源策略;已保留待核对战斗"}
@@ -622,6 +624,9 @@ class Engine:
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", "source_task_id", "source_task_type_id", "source_step_number")}
policy = self._intent_policy(intent)
if record.get("sweep_sample_id"):
self._select_battle_runtime(record["battle_mode"])
return self.battles.continue_sweep(self.client, self.snapshot, policy, cancel=cancel)
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)
@@ -868,6 +873,8 @@ class Engine:
return value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep"
def _intent_policy(self, intent):
if value(intent, "kind") == "map_sweep":
return SimpleNamespace(**(vars(self._map_policy()) | {"enabled": self.sweep_policy.enabled}))
if value(intent, "kind") == "map_battle":
return self._map_policy()
if not self._is_commission(intent):
@@ -1227,11 +1234,84 @@ class Engine:
finally:
self._sync_commission_history()
def _recover_sweep_entry(self):
"""Worker-only local migration, immediately after a successful read."""
pending = self.sweeper.state.get("pending")
if not isinstance(pending, dict):
return
message = self.battles.archive_cancelled_sweep(self.snapshot)
if message:
self._sweep_recovery_message = message
return
if self.battles.handoff_sweep(self.snapshot):
return
phases = ("遭遇隐藏关卡,请在游戏内手动战斗", "遇到事件或响应缺少事件状态,请在游戏内处理", "开始请求待确认")
if pending.get("phase") not in phases or pending.get("start_response"):
return
from .sweep_recovery import scan_trace, role_path_matches
owner = str(self.snapshot.raw["master"]["id"])
path = getattr(getattr(self.client, "trace", None), "path", None)
key = owner + ":" + digest(pending)
if key not in self._sweep_recovery_cache:
evidence = scan_trace(path, owner)
recovered = (evidence["valid"] and (pending.get("role_id") is not None
or role_path_matches(self.sweeper.path, getattr(self.client, "session", None), owner, path))
and self.sweeper.recover_hidden_start(self.snapshot, path, events=evidence["events"]))
# Keep only bounded evidence after the one scan. Presentation and
# subsequent snapshots never rescan the 16 MB rotated logs.
evidence.pop("events", None)
self._sweep_recovery_cache[key] = evidence
if recovered:
self.battles.handoff_sweep(self.snapshot)
return
else:
# An unsuccessful legacy proof is not retried on every refresh.
# A completed archive still repairs a crash before sweep.save.
if not any(row.get("sweep_sample_id") == pending.get("sampleId")
and (row.get("outcome") == "abandoned_missing_hidden_id" or row.get("phase") == "legacy_hidden_archived")
and row.get("sweep_entry") == pending
for row in self.battle_journal.role(self.snapshot)["records"]):
return
evidence = self._sweep_recovery_cache[key]
if (pending.get("phase") != phases[0] or set(pending) != {"stage", "level", "phase", "sampleId"}
or not all(isinstance(pending.get(field), str) and pending[field] for field in ("stage", "level", "sampleId"))
or not evidence["valid"] or not evidence["owner_read"] or not evidence["no_consumption"]
or self.snapshot.raw.get("masterCurrentEvent")
or not role_path_matches(self.sweeper.path, getattr(self.client, "session", None), owner, path)
or any(state.get("pending") and not any(row.get("attempt_id") == state["pending"]
and row.get("phase") == "legacy_hidden_archived" and row.get("sweep_entry") == pending
and row.get("sweep_sample_id") == pending["sampleId"]
and str(row.get("role_id")) == owner
for row in state.get("records", [])) for state in self.battle_journal.state["roles"].values())):
return
reservations = [str(key).split(":") for key, count in self.sweeper.state.get("counts", {}).items()
if type(count) is int and count > 0 and str(key).split(":")[-2:] == [pending["stage"], pending["level"]]]
if not reservations or any(len(parts) != 4 or parts[0] != owner for parts in reservations):
return
# Archive before releasing the guard. A crash between these two atomic
# saves is repaired by the sample ID on the next trusted read.
existing = next((row for row in self.battle_journal.role(self.snapshot)["records"]
if row.get("sweep_sample_id") == pending["sampleId"]
and row.get("outcome") == "abandoned_missing_hidden_id" and row.get("sweep_entry") == pending), None)
message = "旧版未保存隐藏关卡编号,本次未完成已放弃;未结算奖励"
if existing is None:
record = self.battle_journal.pending(self.snapshot) or self.battle_journal.begin(self.snapshot,
{"kind": "map_sweep", "stage_id": pending["stage"], "difficulty": pending["level"], "battle_kind": "sweep"},
sweep_entry=pending, sweep_phase="legacy_hidden_archived")
self.battle_journal.update(record, "legacy_hidden_archived", sweep_sample_id=pending["sampleId"],
sweep_entry=deepcopy(pending), archival_evidence={"role_id": owner, "snapshot_read_at": time.time(),
"role_path_bound": True, "trace_files": evidence["files"], "no_later_consumption": True})
self.battle_journal.finish(self.snapshot, record, "abandoned_missing_hidden_id", message)
self.sweeper.state["pending"] = None
self.sweeper.save()
self._sweep_recovery_message = message
@account_serial
def read_snapshot(self, *, sync_master=True):
if self._progression_pending():
self.last_pending_check = time.monotonic()
self.snapshot = self.client.snapshot()
self._recover_sweep_entry()
self._reconcile_procurement()
pending = self.battle_journal.pending(self.snapshot)
pending_id = pending.get("attempt_id") if pending else None
@@ -1384,6 +1464,9 @@ class Engine:
if not hatch_only:
settled = self.settle_pending_growth()
message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "")
if self._sweep_recovery_message:
message += ";" + self._sweep_recovery_message
self._sweep_recovery_message = ""
if self.sweeper.recovered_event:
message += ";已解除旧版对已结算奖励事件的误阻塞"
self.sweeper.recovered_event = False
@@ -1451,7 +1534,21 @@ class Engine:
stage = self.sweeper.next(self.snapshot, self.sweep_policy)
if self.demo:
return self.snapshot, plans, "扫荡需要登录真实账号;演示不会提交战斗"
result = self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy)
origin = {"kind": "map_sweep", "stage_id": stage.stage_id, "difficulty": stage.level,
"battle_kind": "sweep", "battle_mode": "experimental"}
try:
result = self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy,
cancel=self._progression_cancel, origin=origin)
except CancelledBeforeDispatch:
return self.snapshot, [], "扫荡已停止,未确认的入场已保留"
if self.sweeper.last_outcome == "hidden":
self.battles.handoff_sweep(self.snapshot)
self._select_battle_runtime("experimental")
message = self.battles.continue_sweep(self.client, self.snapshot, self._intent_policy(origin),
cancel=self._progression_cancel)
if not self._progression_cancel.is_set():
self.read_snapshot(sync_master=False)
return self.snapshot, self.plans(), "扫荡遭遇隐藏关卡;" + (message or "隐藏入场已保存,等待来源策略开启后继续")
self.read_snapshot()
label = "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡完成"
message = f"{label}:{stage.number} {stage.name} / 难度{stage.level};" + reward_text(self.sweeper.last_reward)
+5 -4
View File
@@ -16,10 +16,10 @@ from .battle_messages import battle_message
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)",
"bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"}
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗",
"battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡", "map_reward_event": "地图奖励事件",
"battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡", "hidden": "隐藏关卡战斗", "map_reward_event": "地图奖励事件",
"ordinary_stage": "普通关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event",
"reward_event": "map_reward_event", "normal": "battle"}
"reward_event": "map_reward_event", "normal": "battle", "map_sweep": "sweep"}
BATTLE_MODES = {"original": "原版运行时(以能力检查为准)", "experimental": "实验模拟(近似,未完整验证)"}
STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中",
"ready": "待交付", "completed": "已完成", "complete": "已完成", "claimed": "已领奖",
@@ -32,7 +32,8 @@ STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "
"ready": "ready_to_reward", "completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
CURRENT_STATES = {"received", "unlocked", "ready_to_reward"}
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件",
"completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"}
"completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对",
"abandoned_missing_hidden_id": "未完成,已放弃", "abandoned_unsettled_sweep": "未完成,已放弃", "cancelled_unsent_sweep": "未完成,已取消"}
def category(value):
@@ -99,7 +100,7 @@ def prepare_progression_views(engine, *, tasks=True, records=True):
kind = "map_reward_event"
elif row.get("task_id") and kind == "battle":
kind = "task_battle"
elif row.get("kind") == "sweep":
elif row.get("kind") in ("sweep", "map_sweep") and kind != "hidden":
kind = "sweep"
stamp = row.get("finished_at") or row.get("started_at") or row.get("timestamp", row.get("time", row.get("at")))
if type(stamp) in (int, float) and 0 <= stamp <= 253402271999:
+68
View File
@@ -0,0 +1,68 @@
"""Read-only evidence shared by hidden-entry migration and legacy archival."""
import hashlib
import json
from pathlib import Path
def scan_trace(path, owner):
"""Called once per pending by the account worker, never by presentation."""
evidence = {"events": [], "files": [], "valid": False, "owner_read": False, "no_consumption": True}
if not isinstance(path, (str, Path)):
return evidence
path = Path(path)
role = None
safe = {"读取角色", "masterService/masterQueryDetail", "heartBeatService/keepAlive",
"渠道账号验证", "获取官方区服", "进入选中区服", "本地区服整理"}
def unique(pairs):
result = {}
for key, item in pairs:
if key in result:
raise ValueError("调试记录字段重复")
result[key] = item
return result
try:
for file in (path.with_name("network_debug.previous.jsonl"), path):
if not file.exists():
continue
raw = file.read_bytes()
evidence["files"].append({"name": file.name, "sha256": hashlib.sha256(raw).hexdigest()})
for line in raw.decode("utf-8").splitlines():
if not line.strip():
continue
event = json.loads(line, object_pairs_hook=unique)
if not isinstance(event, dict):
return evidence
# Client.enter_server emits this local signature diagnostic
# before entering the server; it dispatches no game request.
if (event.get("kind") == "info" and event.get("operation") == "进入参数检查"
and event.get("scope") == "local"):
continue
if event.get("kind") not in ("request", "response", "error"):
return evidence
evidence["events"].append(event)
operation, kind, body = event.get("operation"), event.get("kind"), event.get("body")
if operation in ("读取角色", "masterService/masterQueryDetail") and kind == "response":
role = str((body.get("master") or {}).get("id")) if isinstance(body, dict) else None
if role != owner or event.get("http_status", 200) != 200 or body.get("resCode", 0) not in (0, "0"):
evidence["no_consumption"] = False
else:
evidence["owner_read"] = True
elif operation not in safe:
# A missing role or an unrecognised operation cannot prove
# that no later consuming request was dispatched.
evidence["no_consumption"] = False
evidence["valid"] = bool(evidence["files"]) and role == owner
except (OSError, ValueError, TypeError, AttributeError):
pass
return evidence
def role_path_matches(sweep_path, session, owner, trace_path):
from .api import Session
from .sessions import identity
if not isinstance(session, Session) or str(session.role_id) != owner or not sweep_path:
return False
root = Path(sweep_path).parent
return (root.parent.name == "roles" and root.name == identity(session)
and root.resolve() == root.absolute() and isinstance(trace_path, (str, Path))
and Path(trace_path).parent.resolve() == root.parent.parent.resolve())
+209 -2
View File
@@ -1,9 +1,13 @@
"""The built-in three-difficulty-cleared sweep path from StageStartPanel."""
from dataclasses import dataclass, field
from contextlib import nullcontext
from datetime import datetime
from types import SimpleNamespace
import json
import math
from pathlib import Path
import sqlite3
import time
import uuid
from .daily import day
@@ -17,6 +21,34 @@ def settled_reward_event(response):
return event_reward(response) is not None
def successful_response(response):
if not isinstance(response, dict):
return False
if "resCode" not in response:
# Existing in-process adapters may already have checked resCode.
return (type(response.get("triggerEvent")) is bool
or type(response.get("triggerEvent")) is int and response["triggerEvent"] in (0, 1)
or isinstance(response.get("reward"), dict))
return (type(response["resCode"]) is int and response["resCode"] == 0
or type(response["resCode"]) is str and response["resCode"] == "0")
def hidden_stage_id(response):
"""Return the original hidden ID only for an explicit hidden event."""
if not isinstance(response, dict):
return None
flag = response.get("triggerEvent")
event = response.get("stageEvent")
if not (flag is True or type(flag) is int and flag == 1) or not isinstance(event, dict):
return None
identifier = event.get("hideStageId")
if isinstance(identifier, str) and identifier.strip():
return identifier
if type(identifier) is int and identifier > 0:
return str(identifier)
return None
@dataclass
class SweepPolicy:
enabled: bool = False
@@ -133,6 +165,140 @@ class SweepRunner:
return True
return False
def recover_hidden_start(self, snapshot, trace_path, *, events=None):
"""Recover entry evidence only; never replay entry or infer settlement.
Old journals lack entry snapshots. Trace proof deliberately does not
manufacture runtime inputs from the current, post-entry snapshot.
"""
from .battles import gameplay_response
pending = self.state.get("pending")
old_phases = {"遭遇隐藏关卡,请在游戏内手动战斗", "遇到事件或响应缺少事件状态,请在游戏内处理"}
if not isinstance(pending, dict) or not trace_path:
return False
if (pending.get("phase") not in old_phases
and not (pending.get("phase") == "开始请求待确认" and "start_response" not in pending)):
return False
owner = snapshot.raw.get("master", {}).get("id")
if owner is None or (pending.get("role_id") is not None and str(pending["role_id"]) != str(owner)):
return False
owner = str(owner)
parent, level = pending.get("stage"), pending.get("level")
if parent is None or level is None:
return False
reservation = pending.get("counts_key")
if pending.get("role_id") is None:
# Multiple dates or roles cannot identify which entry this block owns.
reservations = [(key, count) for key, count in self.state.get("counts", {}).items()
if isinstance(key, str) and len(key.split(":")) == 4
and key.split(":")[2:] == [str(parent), str(level)] and count != 0]
if (len(reservations) != 1 or reservations[0][0].split(":")[0] != owner
or type(reservations[0][1]) is not int or reservations[0][1] <= 0):
return False
reservation = reservations[0][0]
if reservation is not None:
parts = reservation.split(":") if isinstance(reservation, str) else []
if len(parts) != 4 or parts[0] != owner or parts[2:] != [str(parent), str(level)]:
return False
try:
datetime.strptime(parts[1], "%Y-%m-%d")
except ValueError:
return False
role, latest, candidate = None, None, None
requests, responses = {}, set()
# Everything outside these explicit reads is an uncertain write.
reads = {"读取角色", "masterService/masterQueryDetail"}
def unambiguous_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate trace field")
result[key] = value
return result
path = Path(trace_path)
try:
for file in ((None,) if events is not None else (path.with_name("network_debug.previous.jsonl"), path)):
if file is not None and not file.exists():
continue
with (nullcontext(events) if file is None else file.open(encoding="utf-8")) as stream:
for line in stream:
if isinstance(line, str) and not line.strip():
continue
event = line if isinstance(line, dict) else json.loads(line, object_pairs_hook=unambiguous_object)
if not isinstance(event, dict):
return False
operation, kind = event.get("operation"), event.get("kind")
body, identifier = event.get("body"), event.get("request_id")
if not isinstance(operation, str) or kind not in ("request", "response", "error"):
return False
if operation in reads:
if kind == "response":
master = body.get("master") if isinstance(body, dict) else None
observed = master.get("id") if isinstance(master, dict) else None
if (type(observed) not in (int, str) or not str(observed).strip()
or event.get("http_status", 200) != 200
or "resCode" in body and not successful_response(body)):
observed = None
observed = str(observed) if observed is not None else None
if role != observed:
latest, candidate = None, None
role = observed
elif kind == "error":
role, latest, candidate = None, None, None
continue
if not isinstance(identifier, str) or not identifier or not isinstance(body, dict):
return False
if kind == "request":
if identifier in requests:
return False
requests[identifier] = (operation, role)
if role is None or role == owner:
latest, candidate = None, None
if (role == owner and operation == "stageService/stageStart"
and str(body.get("stageTypeId")) == str(parent)
and str(body.get("stageLevel")) == str(level)):
latest = identifier
elif kind == "response":
if identifier in responses:
return False
responses.add(identifier)
if (identifier == latest and requests.get(identifier) == (operation, owner)
and role == owner and operation == "stageService/stageStart"
and event.get("http_status") == 200 and body.get("resCode") in (0, "0") and successful_response(body)
and hidden_stage_id(body) is not None and not settled_reward_event(body)):
candidate = event
elif role is None or role == owner:
latest, candidate = None, None
elif role is None or role == owner:
latest, candidate = None, None
except (OSError, ValueError, TypeError, AttributeError):
return False
if candidate is None or role != owner:
return False
confirmed_at = None
try:
stamp = candidate.get("time")
parsed = datetime.fromisoformat(stamp) if isinstance(stamp, str) else None
if parsed is not None and parsed.tzinfo is not None:
confirmed_at = parsed.timestamp()
if confirmed_at is not None and (not math.isfinite(confirmed_at) or confirmed_at <= 0):
confirmed_at = None
except (ValueError, OverflowError, OSError):
pass
update = {"role_id": owner, "phase": "hidden_started", "start_path": "stageService/stageStart",
"start_dispatched": True, "start_confirmed": True,
"start_response": gameplay_response(candidate["body"]),
"hidden_stage_id": hidden_stage_id(candidate["body"]),
"start_request_id": candidate["request_id"], "evidence_status": "trace_confirmed_hidden_start"}
if reservation is not None:
update["counts_key"] = reservation
if confirmed_at is not None:
update["start_confirmed_at"] = confirmed_at
pending.update(update)
self.save()
return True
def save(self):
if self.path:
self.path.parent.mkdir(parents=True, exist_ok=True)
@@ -202,7 +368,9 @@ class SweepRunner:
return stage
return None
def run(self, client, snapshot, stage, policy):
def run(self, client, snapshot, stage, policy, *, cancel=None, origin=None):
from .battles import CancelledBeforeDispatch, gameplay_response, public_data
self.last_outcome = ""
self.last_reward = None
rule = policy.rules.get(stage.stage_id) or {}
@@ -212,10 +380,42 @@ class SweepRunner:
if reason:
raise ValueError(reason)
key = self.key(snapshot, stage)
previous_count = self.state["counts"].get(key)
self.state["counts"][key] = self.used(snapshot, stage) + 1
self.state["pending"] = {"stage": stage.stage_id, "level": stage.level, "phase": "开始请求待确认", "sampleId": uuid.uuid4().hex}
self.state["pending"] = {"stage": stage.stage_id, "level": stage.level,
"phase": "开始请求待确认", "sampleId": uuid.uuid4().hex,
"role_id": str(snapshot.raw["master"]["id"]), "team": policy.team, "counts_key": key,
"entry_snapshot": public_data(snapshot.raw), "entry_snapshot_now": snapshot.now,
"origin": public_data(origin) if isinstance(origin, dict) else {},
"start_path": "stageService/stageStart", "start_dispatched": False, "start_confirmed": False,
"settlement_dispatched": False, "record_dispatched": False}
self.save() # Reserve before the first non-retryable write, including timeouts.
self.state["pending"]["start_dispatched"] = True
self.save()
if cancel is not None and cancel.is_set():
if previous_count is None:
self.state["counts"].pop(key, None)
else:
self.state["counts"][key] = previous_count
self.state["pending"] = None
self.save()
raise CancelledBeforeDispatch()
started = client.call("stageService/stageStart", {"stageTypeId": stage.stage_id, "stageLevel": stage.level})
if not successful_response(started):
raise ValueError("扫荡开始未返回可信的成功响应,禁止自动重试")
self.state["pending"].update(start_response=gameplay_response(started),
start_confirmed=True, start_confirmed_at=time.time())
self.save()
hidden = hidden_stage_id(started)
if hidden is not None and not settled_reward_event(started):
self.state["pending"].update(phase="hidden_started", hidden_stage_id=hidden)
self.save()
self.last_outcome = "hidden"
if origin is None:
# Callers without the orchestrator handoff must retain the
# historical stop signal, while preserving the new evidence.
raise ValueError("隐藏关卡已入场,等待战斗接续")
return started
if settled_reward_event(started):
# StageCenter.startStageHandler applies stageEvent.result directly;
# StageStartPanel shows it and returns, without battleEnd.
@@ -239,8 +439,15 @@ class SweepRunner:
"win": True, "cheatNum": 0, "cheatRecords": "", "killMonster": {}, "battleMonIds": self.team_ids(snapshot, policy),
**{name: 0 for name in ("leftTime", "killNum", "totalDamage", "bossDamage", "deadNum", "aliveNum", "apLeft")}}
self.state["pending"]["phase"] = "扫荡结算待确认"
self.state["pending"].update(settlement_dispatched=True, sweep_battle_data=battle)
self.save()
if cancel is not None and cancel.is_set():
self.state["pending"].update(phase="cancelled_before_sweep_settlement", settlement_dispatched=False)
self.save()
raise CancelledBeforeDispatch()
result = client.call("battleService/battleEnd", {"battleData": battle})
if not successful_response(result):
raise ValueError("扫荡结算未返回可信的成功响应,禁止自动重试")
self.remember_reward(client, snapshot, stage, "sweep", result.get("reward"), result)
self.state["pending"] = None
self.save()
@@ -0,0 +1,291 @@
"""Hidden sweep handoff/recovery regressions; every game operation is mocked."""
from copy import deepcopy
import threading
import unittest
from unittest.mock import Mock
from ranch_assistant.battles import BattleJournal, BattleOrchestrator
from ranch_assistant.sweeping import SweepRunner
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime, fixture, intent, policy
from ranch_assistant.tests.test_core import workspace_temp
class HiddenSweepBattleTests(unittest.TestCase):
def setUp(self):
self.folder = self.enterContext(workspace_temp())
self.catalog, self.snapshot = fixture()
self.snapshot.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
self.runtime = ExperimentalRuntime()
self.client = Mock()
self.start = {"resCode": 0, "triggerEvent": True,
"stageEvent": {"hideStageId": "0102", "result": {"money": 999}, "costTi": 99}}
self.client.call.side_effect = lambda path, payload: deepcopy(self.start) if path.endswith("stageStart") else {
"resCode": 0, "reward": {"money": 17}, "costTi": 6}
self.chosen = policy(battle_mode="experimental")
self.action = intent(kind="sweep", battle_kind="sweep", difficulty="3")
self.restart()
def restart(self):
self.sweeper = SweepRunner(self.catalog, self.folder / "sweep_runs.json")
self.runner = BattleOrchestrator(self.catalog, BattleJournal(self.folder / "journal.json"),
self.runtime, self.sweeper)
def run_sweep(self, cancel=None):
return self.runner.run(self.client, self.snapshot, self.action, self.chosen, cancel=cancel)
def paths(self):
return [call.args[0] for call in self.client.call.call_args_list]
def test_hidden_win_uses_hidden_inputs_metadata_and_record_with_one_entry(self):
self.run_sweep()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
request = self.runtime.run.call_args.args[0]
self.assertEqual((request["stage_id"], request["difficulty"], request["battle_kind"]), ("0102", "1", "hidden"))
data = self.client.call.call_args_list[1].args[1]["battleData"]
self.assertEqual(data["battlePosition"]["stageId"], "0102")
self.assertEqual(data["totalDamage"], 47)
self.assertEqual(self.client.call.call_args_list[2].args[1], {"stageId": "0102", "cityId": "1", "result": 1})
record = self.runner.journal.records(self.snapshot)[0]
self.assertEqual((record["stage_id"], record["difficulty"], record["battle_kind"]), ("0102", "1", "hidden"))
self.assertEqual((record["parent_stage_id"], record["parent_difficulty"], record["outcome"]), ("0101", "3", "win"))
self.assertEqual(sum(self.sweeper.state["counts"].values()), 1)
self.assertIsNone(self.sweeper.state["pending"])
totals = self.sweeper.statistics.snapshot(7)["totals"]
self.assertEqual(totals["0102:1:sweep"]["n"], 1)
self.assertNotIn("0101:3:event", totals)
self.assertEqual(self.sweeper.last_reward["money"], 17)
def test_hidden_loss_records_hidden_id_without_victory_settlement(self):
self.runtime.win = False
self.run_sweep()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/recordBattleResult"])
self.assertEqual(self.client.call.call_args.args[1], {"stageId": "0102", "cityId": "1", "result": 0})
self.assertIsNone(self.sweeper.state["pending"])
self.assertEqual(self.runner.journal.records(self.snapshot)[0]["outcome"], "loss")
self.assertEqual(self.runner.journal.role(self.snapshot)["losses"], 0)
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"], {})
def test_stop_during_computation_resumes_saved_result_without_second_worker_or_entry(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.run_sweep(cancel)
self.assertEqual(self.paths(), ["stageService/stageStart"])
self.restart()
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
self.assertEqual(self.runtime.run.call_count, 1)
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertIsNone(self.sweeper.state["pending"])
self.assertEqual(sum(self.sweeper.state["counts"].values()), 1)
def test_stop_after_start_keeps_original_inputs_for_restart(self):
cancel = threading.Event()
def start(path, payload):
cancel.set()
return deepcopy(self.start)
self.client.call.side_effect = start
self.run_sweep(cancel)
self.runtime.run.assert_not_called()
self.snapshot.raw["monsters"][0]["level"] = 999
self.restart()
self.client.call.side_effect = lambda path, payload: {"resCode": 0, "reward": {}}
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
request = self.runtime.run.call_args.args[0]
self.assertNotIn("level", request.get("roster", request["snapshot"])["monsters"][0])
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
self.assertIsNone(self.sweeper.state["pending"])
def test_unknown_settlement_is_never_replayed_or_cleared(self):
def call(path, payload):
if path.endswith("battleEnd"):
raise TimeoutError("offline lost settlement response")
return deepcopy(self.start)
self.client.call.side_effect = call
with self.assertRaises(TimeoutError):
self.run_sweep()
self.restart()
before = deepcopy(self.sweeper.state)
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
self.assertEqual(self.sweeper.state, before)
self.assertIsNotNone(self.runner.pending(self.snapshot))
def test_unknown_record_keeps_confirmed_rewards_and_never_replays(self):
def call(path, payload):
if path.endswith("recordBattleResult"):
raise TimeoutError("offline lost record response")
return deepcopy(self.start) if path.endswith("stageStart") else {"resCode": 0, "reward": {"money": 17}}
self.client.call.side_effect = call
with self.assertRaises(TimeoutError):
self.run_sweep()
self.restart()
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
self.assertEqual(len(self.paths()), 3)
self.assertIsNotNone(self.runner.pending(self.snapshot)["sweep_entry"])
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"]["0102:1:sweep"]["n"], 1)
def test_role_mismatch_cannot_adopt_hidden_sweep(self):
cancel = threading.Event()
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
self.run_sweep(cancel)
self.restart()
self.snapshot.raw["master"]["id"] = 8
before = deepcopy(self.sweeper.state)
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
self.assertEqual(self.sweeper.state, before)
self.assertEqual(len(self.paths()), 1)
self.runtime.run.assert_not_called()
def test_no_hidden_evidence_keeps_legacy_pending_and_journal(self):
self.sweeper.state["pending"] = {"stage": "0101", "level": "3", "sampleId": "old",
"phase": "遭遇隐藏关卡,请在游戏内手动战斗"}
self.sweeper.save()
before = deepcopy(self.sweeper.state)
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
self.assertEqual(self.sweeper.state, before)
self.client.call.assert_not_called()
self.runtime.run.assert_not_called()
def test_cross_day_handoff_and_completed_journal_cleanup_keep_original_reservation(self):
cancel = threading.Event()
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
self.run_sweep(cancel)
record = self.runner.pending(self.snapshot)
entry = deepcopy(record["sweep_entry"])
counts = deepcopy(self.sweeper.state["counts"])
# Emulate a crash after journal.save but before sweep.save.
self.sweeper.state["pending"] = deepcopy(entry)
self.sweeper.save()
self.snapshot.server_offset += 86400
self.restart()
self.runner.handoff_sweep(self.snapshot)
self.assertIsNone(self.sweeper.state["pending"])
self.assertEqual(self.sweeper.state["counts"], counts)
self.client.call.side_effect = lambda *args: {"resCode": 0, "reward": {"money": 17}}
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
self.sweeper.state["pending"] = deepcopy(entry)
self.sweeper.save()
self.restart()
self.runner.handoff_sweep(self.snapshot)
self.assertIsNone(self.sweeper.state["pending"])
self.assertEqual(self.sweeper.state["counts"], counts)
self.assertEqual(len(self.runner.journal.records(self.snapshot)), 1)
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"]["0102:1:sweep"]["n"], 1)
def test_runtime_clock_stop_and_resume_does_not_resimulate_or_enter(self):
cancel = threading.Event()
cancel.wait = Mock(side_effect=lambda timeout: cancel.set() or True)
self.runner.clock = lambda: 0
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.run_sweep(cancel)
self.assertEqual(self.paths(), ["stageService/stageStart"])
self.restart()
record = self.runner.pending(self.snapshot)
self.assertEqual(record["battle_clock_seconds"], 10)
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
self.runner.journal.update(record, record["phase"], battle_ready_at=1)
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
self.assertEqual(self.runtime.run.call_count, 1)
self.assertEqual(len(self.paths()), 3)
def test_confirmed_hidden_start_does_not_recover_with_wrong_hidden_id(self):
cancel = threading.Event()
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
self.run_sweep(cancel)
record = self.runner.pending(self.snapshot)
self.runner.journal.update(record, record["phase"], stage_id="0101")
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
self.assertEqual(self.paths(), ["stageService/stageStart"])
self.runtime.run.assert_not_called()
def test_empty_settlement_or_record_response_never_confirms_or_retries_hidden_write(self):
for target in ("battleEnd", "recordBattleResult"):
with self.subTest(target=target):
self.setUp()
def call(path, payload):
if path.endswith(target):
return {}
return deepcopy(self.start) if path.endswith("stageStart") else {"resCode": 0, "reward": {}}
self.client.call.side_effect = call
with self.assertRaises(ValueError):
self.run_sweep()
count = len(self.paths())
self.restart()
record = self.runner.pending(self.snapshot)
self.assertFalse(self.runner.recovery_status(record)["resumable"])
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
self.assertEqual(len(self.paths()), count)
def test_crash_after_trusted_response_save_derives_hidden_only_from_response(self):
cancel = threading.Event()
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
self.run_sweep(cancel)
entry = deepcopy(self.runner.pending(self.snapshot)["sweep_entry"])
self.runner.journal.state = {"version": 1, "roles": {}}
self.runner.journal.save()
entry.pop("hidden_stage_id")
entry["phase"] = "开始请求待确认"
self.sweeper.state["pending"] = entry
self.sweeper.save()
self.restart()
self.client.call.side_effect = lambda *args: {"resCode": 0, "reward": {}}
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
self.assertEqual(self.runner.journal.records(self.snapshot)[0]["stage_id"], "0102")
def test_crash_after_new_journal_begin_keeps_sample_role_and_recovers_same_record(self):
cancel = threading.Event()
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
self.run_sweep(cancel)
entry = deepcopy(self.runner.pending(self.snapshot)["sweep_entry"])
self.runner.journal.state = {"version": 1, "roles": {}}
self.runner.journal.save()
self.sweeper.state["pending"] = entry
self.sweeper.save()
begin = self.runner.journal.begin
def crash(*args, **kwargs):
record = begin(*args, **kwargs)
self.assertEqual((record["sweep_sample_id"], record["role_id"]), (entry["sampleId"], "7"))
raise OSError("offline crash after durable begin")
self.runner.journal.begin = crash
with self.assertRaises(OSError):
self.runner.handoff_sweep(self.snapshot)
self.restart()
self.client.call.side_effect = lambda *args: {"resCode": 0, "reward": {}}
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
self.assertIsNone(self.runner.pending(self.snapshot))
self.assertEqual(len(self.runner.journal.records(self.snapshot)), 1)
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
def test_commission_farming_sweep_keeps_source_and_single_entry_during_resume(self):
self.action.update(kind="progression_farm_sweep", task_id=0, task_type_id="", step_number=0,
source_task_id=51, source_task_type_id="400", source_step_number=1)
self.snapshot.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
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.run_sweep(cancel)
self.restart()
record = self.runner.pending(self.snapshot)
self.assertEqual((record["kind"], record["source_task_id"], record["source_task_type_id"]),
("progression_farm_sweep", 51, "400"))
self.runner.continue_sweep(self.client, self.snapshot, policy(enabled=False, battle_mode="experimental"))
self.assertEqual(len(self.paths()), 1)
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
self.assertEqual(self.runtime.run.call_count, 1)
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(sum(self.sweeper.state["counts"].values()), 1)
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"]["0102:1:sweep"]["n"], 1)
self.assertEqual(self.runner.journal.role(self.snapshot)["losses"], 0)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,331 @@
"""Account-worker sweep recovery, with local files and mocked transport only."""
from copy import deepcopy
import json
import threading
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.api import Session
from ranch_assistant.engine import Engine
from ranch_assistant.game_data import ProgressionData
from ranch_assistant.model import Policy, Snapshot
from ranch_assistant.sessions import identity
from ranch_assistant.sweeping import SweepPolicy
from ranch_assistant.maps import stages
from ranch_assistant.tests.test_activities import scenario
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime
from ranch_assistant.tests.test_core import workspace_temp
class HiddenSweepEngineTests(unittest.TestCase):
def setUp(self):
self.folder = self.enterContext(workspace_temp())
self.catalog, self.snapshot = scenario()
self.raw = deepcopy(self.snapshot.raw)
self.raw["master"].update(id=7, ti=100, timeTi=0)
self.raw["currentTasks"] = []
self.session = Session(account_id="offline", role_id=7, server_id=1)
self.root = self.folder / "roles" / identity(self.session)
self.trace = self.folder / "network_debug.jsonl"
self.client = Mock()
self.client.session = self.session
self.client.trace = Mock(path=self.trace, events=[])
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw))
self.runtime = ExperimentalRuntime()
data = {"stage_info": deepcopy(self.catalog.data["stage_info"]), "game_setting": self.catalog.data["game_setting"],
"task_info": {}, "stage_battles": {}}
data["stage_info"]["0102"]["level"]["1"]["battle"] = {"fixture_hidden": True}
self.engine = Engine(self.catalog, self.client, self.root / "purchase.json",
game_data=ProgressionData(data), experimental_runtime=self.runtime)
self.engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
self.engine.progression_policy.enabled = False
self.engine.sweep_policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}}, allow_challenge=False)
self.engine.master_sync.settle = Mock()
self.engine.snapshot = Snapshot(deepcopy(self.raw))
def legacy(self, phase="遭遇隐藏关卡,请在游戏内手动战斗"):
pending = {"stage": "0101", "level": "3", "phase": phase, "sampleId": "legacy-entry"}
self.engine.sweeper.state = {"counts": {"7:2026-11-13:0101:3": 1}, "pending": pending}
self.engine.sweeper.save()
events = [{"kind": "response", "operation": "读取角色", "http_status": 200,
"body": {"resCode": 0, "master": {"id": 7}}}]
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
return deepcopy(pending)
def test_exact_legacy_missing_id_is_archived_after_trusted_read_without_reward_or_write(self):
original = self.legacy()
self.engine.sweep_policy.enabled = False
self.engine.cancel_progression()
self.engine.read_snapshot(sync_master=False)
self.assertIsNone(self.engine.sweeper.state["pending"])
record = self.engine.battle_journal.records(self.engine.snapshot)[0]
self.assertEqual(record["outcome"], "abandoned_missing_hidden_id")
self.assertEqual(record["sweep_entry"], original)
self.assertIn("旧版未保存隐藏关卡编号,本次未完成已放弃;未结算奖励", record["message"])
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
self.client.call.assert_not_called()
self.assertEqual(self.engine.sweeper.statistics.snapshot(7)["totals"], {})
self.engine.read_snapshot(sync_master=False)
self.assertEqual(len(self.engine.battle_journal.records(self.engine.snapshot)), 1)
def test_legacy_archive_accepts_exact_local_login_info_then_role_read_and_heartbeat(self):
original = self.legacy()
events = [{"kind": "info", "operation": "进入参数检查", "scope": "local",
"sign_date": "20261114", "date_format": "yyyyMMdd", "signature_rule": "2|2|1|2|3",
"tj_channel": "unknow", "platform": "ANDROID", "channel": "DYD", "uid_length": 7, "token_length": 16},
{"kind": "response", "operation": "读取角色", "http_status": 200,
"body": {"resCode": 0, "master": {"id": 7}}},
{"kind": "request", "operation": "heartBeatService/keepAlive", "request_id": "heartbeat", "body": {}},
{"kind": "response", "operation": "heartBeatService/keepAlive", "request_id": "heartbeat",
"http_status": 200, "body": {"resCode": 0}}]
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
self.engine.read_snapshot(sync_master=False)
self.assertIsNone(self.engine.sweeper.state["pending"])
record = self.engine.battle_journal.records(self.engine.snapshot)[0]
self.assertEqual(record["outcome"], "abandoned_missing_hidden_id")
self.assertEqual(record["sweep_entry"], original)
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
self.assertTrue(next(iter(self.engine._sweep_recovery_cache.values()))["valid"])
self.client.call.assert_not_called()
self.runtime.run.assert_not_called()
self.assertEqual(self.engine.sweeper.statistics.snapshot(7)["totals"], {})
def test_unknown_info_or_login_info_without_local_scope_blocks_legacy_archive(self):
for info in ({"kind": "info", "operation": "未知信息", "scope": "local"},
{"kind": "info", "operation": "进入参数检查", "scope": "network"},
{"kind": "info", "operation": "进入参数检查"}):
with self.subTest(info=info):
original = self.legacy()
self.engine._sweep_recovery_cache.clear()
events = [info, {"kind": "response", "operation": "读取角色", "http_status": 200,
"body": {"resCode": 0, "master": {"id": 7}}}]
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.sweeper.state["pending"], original)
self.assertFalse(next(iter(self.engine._sweep_recovery_cache.values()))["valid"])
self.assertEqual(self.engine.battle_journal.records(self.engine.snapshot), [])
self.client.call.assert_not_called()
self.runtime.run.assert_not_called()
def test_uncertain_phases_are_never_archived(self):
for phase in ("开始请求待确认", "扫荡结算待确认", "start_pending", "settlement_pending"):
original = self.legacy(phase)
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.sweeper.state["pending"], original)
self.client.call.assert_not_called()
def test_archive_requires_role_path_binding_and_fresh_read(self):
original = self.legacy()
self.engine.sweeper.path = self.folder / "other" / "sweep_runs.json"
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.sweeper.state["pending"], original)
self.client.snapshot.side_effect = TimeoutError("offline read failed")
with self.assertRaises(TimeoutError):
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.sweeper.state["pending"], original)
def test_later_consumption_or_conflicting_journal_blocks_archive(self):
original = self.legacy()
with self.trace.open("a", encoding="utf-8") as stream:
stream.write(json.dumps({"kind": "request", "operation": "battleService/battleEnd",
"request_id": "later", "body": {"battleData": {}}}) + "\n")
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.sweeper.state["pending"], original)
self.legacy()
self.engine.battle_journal.begin(self.engine.snapshot, {"kind": "battle", "stage_id": "0102", "difficulty": "1"})
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.sweeper.state["pending"], original)
self.client.call.assert_not_called()
def test_map_sweep_origin_uses_enabled_sweep_with_challenges_disabled(self):
self.assertTrue(self.engine._intent_policy({"kind": "map_sweep"}).enabled)
self.engine.sweep_policy.enabled = False
self.assertFalse(self.engine._intent_policy({"kind": "map_sweep"}).enabled)
def test_commission_farming_origin_uses_quest_policy(self):
self.engine.game_data.tasks["400"] = {"type": 4}
self.engine.quest_policy.enabled = True
origin = {"kind": "progression_farm_sweep", "source_task_type_id": "400"}
self.assertTrue(self.engine._intent_policy(origin).enabled)
self.engine.quest_policy.enabled = False
self.engine.progression_policy.enabled = True
self.assertFalse(self.engine._intent_policy(origin).enabled)
def prepare_hidden(self):
response = {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": "0102", "result": {"money": 999}}}
self.client.call.side_effect = lambda path, payload: deepcopy(response) if path.endswith("stageStart") else {
"resCode": 0, "reward": {"money": 17}}
stage = next(s for s in stages(self.catalog, self.engine.snapshot) if s.stage_id == "0101" and s.level == "3")
self.engine.sweeper.run(self.client, self.engine.snapshot, stage, self.engine.sweep_policy,
origin={"kind": "map_sweep", "stage_id": "0101", "difficulty": "3", "battle_kind": "sweep", "battle_mode": "experimental"})
self.engine.read_snapshot(sync_master=False)
def test_worker_migrates_before_web_start_and_resumes_without_challenge_or_mainline(self):
self.prepare_hidden()
self.assertIsNone(self.engine.sweeper.state["pending"])
self.assertEqual(self.engine.pending_battle_recovery()["state"], "prepare_hidden_sweep")
self.engine.poll(resume_pending=True)
self.assertFalse(self.engine.auto)
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"])
request = self.runtime.run.call_args.args[0]
self.assertEqual((request["stage_id"], request["difficulty"]), ("0102", "1"))
self.assertEqual(request["roster"]["teams"][0]["monsters"], [900, 0])
self.assertEqual(sum(self.engine.sweeper.state["counts"].values()), 1)
totals = self.engine.sweeper.statistics.snapshot(7)["totals"]
self.assertEqual(totals["0102:1:sweep"]["n"], 1)
self.assertNotIn("0101:3:sweep", totals)
def test_stop_disabled_source_and_stale_generation_do_not_resume_consumption(self):
self.prepare_hidden()
self.engine.cancel_progression()
self.engine.poll(resume_pending=False)
self.engine.sweep_policy.enabled = False
self.assertEqual(self.engine.pending_battle_recovery()["state"], "blocked_policy")
self.engine.poll(resume_pending=True)
self.engine.sweep_policy.enabled = True
self.assertEqual(self.engine._resume_pending_task_clock(running=True,
generation=self.engine._progression_cancel_generation - 1), "")
self.runtime.run.assert_not_called()
self.assertEqual(self.client.call.call_count, 1)
self.engine.poll(resume_pending=True)
self.assertEqual(self.client.call.call_count, 3)
def test_legacy_scan_is_cached_and_never_runs_in_recovery_presentation(self):
self.legacy()
with patch("ranch_assistant.sweep_recovery.scan_trace", wraps=__import__(
"ranch_assistant.sweep_recovery", fromlist=["scan_trace"]).scan_trace) as scan:
for _ in range(3):
self.engine.pending_battle_recovery()
self.assertEqual(scan.call_count, 0)
self.engine.read_snapshot(sync_master=False)
self.engine.read_snapshot(sync_master=False)
self.assertEqual(scan.call_count, 1)
def test_archive_crash_after_journal_finish_repairs_without_second_record(self):
original = self.legacy()
self.engine.read_snapshot(sync_master=False)
self.engine.sweeper.state["pending"] = original
self.engine.sweeper.save()
self.engine.read_snapshot(sync_master=False)
self.assertIsNone(self.engine.sweeper.state["pending"])
self.assertEqual(len(self.engine.battle_journal.records(self.engine.snapshot)), 1)
self.client.call.assert_not_called()
def test_archive_crash_after_begin_recovers_same_sample_without_generic_prepared_record(self):
original = self.legacy()
begin = self.engine.battle_journal.begin
def crash(*args, **kwargs):
begin(*args, **kwargs)
raise OSError("offline interrupted archive")
self.engine.battle_journal.begin = crash
with self.assertRaises(OSError):
self.engine.read_snapshot(sync_master=False)
self.engine.battle_journal.begin = begin
self.engine.read_snapshot(sync_master=False)
self.assertIsNone(self.engine.sweeper.state["pending"])
records = self.engine.battle_journal.records(self.engine.snapshot)
self.assertEqual(len(records), 1)
self.assertEqual(records[0]["sweep_entry"], original)
self.assertEqual(records[0]["outcome"], "abandoned_missing_hidden_id")
def test_normal_sweep_stop_before_dispatch_archives_but_unknown_dispatch_stays_pending(self):
cancel = threading.Event()
stage = next(s for s in stages(self.catalog, self.engine.snapshot) if s.stage_id == "0101" and s.level == "3")
def start(path, payload):
cancel.set()
return {"resCode": 0, "triggerEvent": False}
self.client.call.side_effect = start
from ranch_assistant.battles import CancelledBeforeDispatch
with self.assertRaises(CancelledBeforeDispatch):
self.engine.sweeper.run(self.client, self.engine.snapshot, stage, self.engine.sweep_policy,
cancel=cancel, origin={"kind": "map_sweep"})
pending = deepcopy(self.engine.sweeper.state["pending"])
self.assertIs(pending["settlement_dispatched"], False)
self.engine.read_snapshot(sync_master=False)
self.assertIsNone(self.engine.sweeper.state["pending"])
self.assertEqual(self.engine.battle_journal.records(self.engine.snapshot)[0]["outcome"], "abandoned_cancelled_sweep")
self.assertEqual(self.client.call.call_count, 1)
for dispatched in (True, None):
unknown = dict(pending, phase="扫荡结算待确认")
unknown.pop("settlement_dispatched")
if dispatched is not None:
unknown["settlement_dispatched"] = dispatched
self.engine.sweeper.state["pending"] = unknown
self.engine.sweeper.save()
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.sweeper.state["pending"], unknown)
def test_ordinary_automatic_entry_runs_hidden_battle_and_counts_once(self):
self.client.call.side_effect = lambda path, payload=None: {"resCode": 0, "triggerEvent": True,
"stageEvent": {"hideStageId": "0102", "result": {"money": 999}}} if path.endswith("stageStart") else {
"resCode": 0, "reward": {"money": 17}}
self.engine.auto = True
_, _, message = self.engine.poll()
self.assertIn("隐藏关卡", message)
self.assertEqual([call.args[0] for call in self.client.call.call_args_list], [
"stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(sum(self.engine.sweeper.state["counts"].values()), 1)
def test_trace_proven_legacy_hidden_id_runs_first_computation_without_new_entry(self):
self.legacy()
original_roster = deepcopy(self.raw)
self.engine.sweeper.state["pending"].update(entry_snapshot=original_roster,
entry_snapshot_now=self.engine.snapshot.now, team="teamA")
self.engine.sweeper.save()
next(mon for mon in self.raw["monsters"] if mon["id"] == 900)["level"] = 999
events = [{"kind": "response", "operation": "读取角色", "http_status": 200,
"body": {"resCode": 0, "master": {"id": 7}}},
{"kind": "request", "operation": "stageService/stageStart", "request_id": "old-start",
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
{"kind": "response", "operation": "stageService/stageStart", "request_id": "old-start", "http_status": 200,
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": "0102"}}}]
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
self.client.call.return_value = {"resCode": 0, "reward": {"money": 17}}
self.engine.read_snapshot(sync_master=False)
self.assertEqual(self.engine.pending_battle_recovery()["state"], "prepare_hidden_sweep")
self.engine.poll(resume_pending=True)
self.assertEqual([call.args[0] for call in self.client.call.call_args_list], [
"battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
saved = self.engine.battle_journal.records(self.engine.snapshot)[0]["sweep_entry"]
self.assertEqual(saved["entry_snapshot"], original_roster)
runtime_roster = self.runtime.run.call_args.args[0]["roster"]
self.assertEqual(next(mon for mon in runtime_roster["monsters"] if mon["id"] == 900)["level"], 20)
def test_legacy_hidden_id_without_original_inputs_blocks_changed_current_roster(self):
self.legacy()
next(mon for mon in self.raw["monsters"] if mon["id"] == 900)["level"] = 999
events = [{"kind": "response", "operation": "读取角色", "http_status": 200,
"body": {"resCode": 0, "master": {"id": 7}}},
{"kind": "request", "operation": "stageService/stageStart", "request_id": "old-start",
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
{"kind": "response", "operation": "stageService/stageStart", "request_id": "old-start", "http_status": 200,
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": "0102"}}}]
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
self.engine.read_snapshot(sync_master=False)
record = self.engine.battle_journal.pending(self.engine.snapshot)
self.assertEqual(record["stage_id"], "0102")
self.assertEqual(record["sweep_sample_id"], "legacy-entry")
self.assertNotIn("entry_snapshot", record["sweep_entry"])
self.assertNotIn("entry_snapshot_now", record["sweep_entry"])
self.assertNotIn("input_evidence", record["sweep_entry"])
self.assertNotIn("combat_request", record)
self.assertNotIn("combat_request_digest", record)
recovery = self.engine.pending_battle_recovery()
self.assertEqual(recovery["state"], "blocked")
self.assertFalse(recovery["resumable"])
self.assertIn("缺少原始战斗输入", recovery["message"])
for _ in range(2):
self.engine.poll(resume_pending=True)
self.runtime.inspect.assert_not_called()
self.runtime.run.assert_not_called()
self.client.call.assert_not_called()
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
self.assertEqual(self.engine.sweeper.statistics.snapshot(7)["totals"], {})
self.assertEqual(self.engine.battle_journal.pending(self.engine.snapshot), record)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,322 @@
"""Offline coverage for the durable sweep-to-hidden-battle handoff."""
from copy import deepcopy
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from threading import Event
from types import SimpleNamespace
import unittest
from unittest.mock import Mock
from ranch_assistant.battles import CancelledBeforeDispatch
from ranch_assistant.sweeping import SweepPolicy, SweepRunner, hidden_stage_id
class HiddenSweepHandoffTests(unittest.TestCase):
def setUp(self):
self.temp = TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.folder = Path(self.temp.name)
self.catalog = SimpleNamespace(data={})
self.snapshot = SimpleNamespace(now=1794618000, monsters={9: {}}, raw={
"master": {"id": 17, "sessionKey": "never-save"},
"teams": [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [9]}],
"nested": {"token": "never-save", "safe": 1}})
self.stage = SimpleNamespace(stage_id="0101", level="3")
self.policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 4}})
self.runner = SweepRunner(self.catalog, self.folder / "sweeps.json")
self.runner.reason = Mock(return_value="")
self.response = {"resCode": 0, "triggerEvent": True, "stageEvent": {
"hideStageId": "00109", "costTi": 16, "result": {"money": 999}}}
self.client = Mock()
self.client.call.return_value = self.response
def test_hidden_handoff_counts_once_without_settlement_or_reward(self):
result = self.runner.run(self.client, self.snapshot, self.stage, self.policy, origin={"kind": "map_sweep"})
self.assertIs(result, self.response)
self.client.call.assert_called_once_with("stageService/stageStart", {
"stageTypeId": "0101", "stageLevel": "3"})
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
self.assertEqual(self.runner.last_outcome, "hidden")
self.assertIsNone(self.runner.last_reward)
self.assertEqual(self.runner.statistics.snapshot(17)["totals"], {})
pending = self.runner.state["pending"]
self.assertEqual((pending["phase"], pending["hidden_stage_id"]), ("hidden_started", "00109"))
def test_restart_has_sanitized_entry_and_trusted_start_evidence(self):
self.response["sessionKey"] = "never-save"
self.runner.run(self.client, self.snapshot, self.stage, self.policy,
origin={"kind": "sweep", "secret": "never-save"})
restored = SweepRunner(self.catalog, self.runner.path)
pending = restored.state["pending"]
self.assertEqual(pending["role_id"], "17")
self.assertEqual((pending["stage"], pending["level"], pending["team"]), ("0101", "3", "teamA"))
self.assertEqual(pending["counts_key"], self.runner.key(self.snapshot, self.stage))
self.assertTrue(pending["sampleId"])
self.assertEqual(pending["entry_snapshot_now"], self.snapshot.now)
self.assertEqual(pending["entry_snapshot"]["nested"], {"safe": 1})
self.assertEqual(pending["origin"], {"kind": "sweep"})
self.assertEqual(pending["start_path"], "stageService/stageStart")
self.assertTrue(pending["start_dispatched"])
self.assertTrue(pending["start_confirmed"])
self.assertGreater(pending["start_confirmed_at"], 0)
self.assertNotIn("sessionKey", pending["start_response"])
self.assertNotIn("never-save", restored.path.read_text(encoding="utf-8"))
def test_hidden_ids_and_trigger_require_exact_protocol_types(self):
for identifier, expected in (("00109", "00109"), (109, "109"), (" hidden ", " hidden "),
(None, None), ("", None), (" ", None), (0, None), (-1, None),
(True, None), (1.0, None), ({}, None), ([], None)):
with self.subTest(identifier=identifier):
response = dict(self.response, stageEvent={"hideStageId": identifier})
self.assertEqual(hidden_stage_id(response), expected)
for flag in (False, 0, "1", 1.0, None):
self.assertIsNone(hidden_stage_id(dict(self.response, triggerEvent=flag)))
self.assertEqual(hidden_stage_id(dict(self.response, triggerEvent=1)), "00109")
def test_ordinary_and_settled_event_paths_still_complete(self):
self.client.call.side_effect = [{"resCode": 0, "triggerEvent": False},
{"resCode": 0, "reward": {"money": 1}}, {"resCode": 0}]
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
self.assertEqual([call.args[0] for call in self.client.call.call_args_list], [
"stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.runner.last_outcome, "sweep")
self.assertIsNone(self.runner.state["pending"])
self.client.reset_mock(side_effect=True)
self.client.call.return_value = {"resCode": 0, "triggerEvent": True,
"stageEvent": {"hideStageId": None, "result": {"money": 2}}}
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
self.assertEqual(self.client.call.call_count, 1)
self.assertEqual(self.runner.last_outcome, "event")
self.assertIsNone(self.runner.state["pending"])
self.assertEqual(self.runner.used(self.snapshot, self.stage), 2)
def test_timeout_preserves_dispatched_pending_and_cannot_reenter(self):
self.client.call.side_effect = TimeoutError("entry not confirmed")
with self.assertRaises(TimeoutError):
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
restored = SweepRunner(self.catalog, self.runner.path)
self.assertTrue(restored.state["pending"]["start_dispatched"])
self.assertFalse(restored.state["pending"]["start_confirmed"])
self.assertNotIn("start_response", restored.state["pending"])
with self.assertRaises(ValueError):
restored.run(self.client, self.snapshot, self.stage, self.policy)
self.assertEqual(self.client.call.call_count, 1)
def test_malformed_and_unsuccessful_start_keeps_pending(self):
for response in (None, [], {}, {"resCode": False, "triggerEvent": False},
{"resCode": 9, "triggerEvent": False}, {"resCode": 0, "triggerEvent": "1"},
{"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": []}}):
with self.subTest(response=response):
self.runner.state = {"counts": {}, "pending": None}
self.client.reset_mock()
self.client.call.return_value = response
with self.assertRaises(ValueError):
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
self.assertIsNotNone(SweepRunner(self.catalog, self.runner.path).state["pending"])
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
self.assertEqual(self.client.call.call_count, 1)
def test_cancel_after_reservation_rolls_back_only_unissued_entry(self):
cancel = Event()
original_save = self.runner.save
def save_and_stop():
original_save()
cancel.set()
self.runner.save = save_and_stop
before = deepcopy(self.runner.state)
with self.assertRaises(CancelledBeforeDispatch):
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
self.client.call.assert_not_called()
self.assertEqual(self.runner.state, before)
self.assertEqual(SweepRunner(self.catalog, self.runner.path).state, before)
def test_cancel_after_start_preserves_pending_without_settlement(self):
cancel = Event()
def start(*args):
cancel.set()
return {"resCode": 0, "triggerEvent": False}
self.client.call.side_effect = start
with self.assertRaises(CancelledBeforeDispatch):
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
self.assertEqual(self.client.call.call_count, 1)
self.assertTrue(self.runner.state["pending"]["start_confirmed"])
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
def test_cancel_at_dispatch_boundary_restores_existing_quota(self):
key = self.runner.key(self.snapshot, self.stage)
self.runner.state["counts"][key] = 2
before = deepcopy(self.runner.state)
cancel = Event()
original_save = self.runner.save
def save_and_stop():
original_save()
if (self.runner.state.get("pending") or {}).get("start_dispatched"):
cancel.set()
self.runner.save = save_and_stop
with self.assertRaises(CancelledBeforeDispatch):
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
self.client.call.assert_not_called()
self.assertEqual(self.runner.state, before)
def test_stop_at_settlement_boundary_keeps_entry_reserved(self):
cancel = Event()
self.client.call.return_value = {"resCode": 0, "triggerEvent": False}
original_save = self.runner.save
def save_and_stop():
original_save()
if self.runner.state["pending"]["phase"] == "扫荡结算待确认":
cancel.set()
self.runner.save = save_and_stop
with self.assertRaises(CancelledBeforeDispatch):
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
self.assertEqual(self.client.call.call_count, 1)
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
def test_invalid_or_failed_settlement_remains_pending(self):
for result in (None, [], {}, {"resCode": 7}):
with self.subTest(result=result):
self.runner.state = {"counts": {}, "pending": None}
self.client.reset_mock()
self.client.call.side_effect = [{"resCode": 0, "triggerEvent": False}, result]
with self.assertRaises(ValueError):
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
self.assertIsNotNone(self.runner.state["pending"])
self.assertEqual(self.client.call.call_count, 2)
def trace_rows(self):
return [{"kind": "response", "operation": "读取角色", "body": {"master": {"id": 17}}},
{"kind": "request", "operation": "stageService/stageStart", "request_id": "start-1",
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
{"kind": "response", "operation": "stageService/stageStart", "request_id": "start-1",
"http_status": 200, "time": "2026-11-14T09:00:00+08:00", "body": deepcopy(self.response)}]
def legacy_pending(self, phase="遭遇隐藏关卡,请在游戏内手动战斗"):
self.runner.state = {"counts": {self.runner.key(self.snapshot, self.stage): 1}, "pending": {
"stage": "0101", "level": "3", "phase": phase, "sampleId": "old"}}
self.runner.save()
def write_trace(self, rows):
trace = self.folder / "network_debug.jsonl"
trace.write_text("\n".join(json.dumps(row) for row in rows), encoding="utf-8")
return trace
def test_valid_rotated_trace_recovers_without_new_write_or_count(self):
self.legacy_pending()
rows = self.trace_rows()
trace = self.write_trace(rows[2:])
trace.with_name("network_debug.previous.jsonl").write_text(
"\n".join(json.dumps(row) for row in rows[:2]), encoding="utf-8")
counts = deepcopy(self.runner.state["counts"])
self.assertTrue(self.runner.recover_hidden_start(self.snapshot, trace))
pending = SweepRunner(self.catalog, self.runner.path).state["pending"]
self.assertEqual((pending["role_id"], pending["hidden_stage_id"]), ("17", "00109"))
self.assertEqual(pending["phase"], "hidden_started")
self.assertEqual(pending["start_request_id"], "start-1")
self.assertTrue(pending["start_confirmed"])
self.assertEqual(pending["start_confirmed_at"], self.snapshot.now)
self.assertEqual(self.runner.state["counts"], counts)
self.assertNotIn("entry_snapshot", pending)
self.assertNotIn("entry_snapshot_now", pending)
self.client.call.assert_not_called()
def test_unknown_entry_and_old_event_phase_can_recover(self):
for phase in ("开始请求待确认", "遇到事件或响应缺少事件状态,请在游戏内处理"):
with self.subTest(phase=phase):
self.legacy_pending(phase)
self.assertTrue(self.runner.recover_hidden_start(self.snapshot, self.write_trace(self.trace_rows())))
def test_only_latest_matching_start_can_supply_recovery_id(self):
self.legacy_pending()
rows = self.trace_rows()
newer = deepcopy(rows[1:])
for row in newer:
row["request_id"] = "latest"
newer[1]["body"]["stageEvent"]["hideStageId"] = "new-hidden"
self.assertTrue(self.runner.recover_hidden_start(self.snapshot, self.write_trace(rows + newer)))
self.assertEqual(self.runner.state["pending"]["hidden_stage_id"], "new-hidden")
self.assertEqual(self.runner.state["pending"]["start_request_id"], "latest")
def test_bound_pending_role_must_match_snapshot(self):
self.legacy_pending()
self.runner.state["pending"]["role_id"] = "18"
before = deepcopy(self.runner.state)
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, self.write_trace(self.trace_rows())))
self.assertEqual(self.runner.state, before)
def test_nonlegacy_or_persisted_unknown_response_is_not_recovered(self):
for phase in ("hidden_started", "扫荡结算待确认", "开始请求待确认"):
with self.subTest(phase=phase):
self.legacy_pending(phase)
if phase == "开始请求待确认":
self.runner.state["pending"]["start_response"] = {}
before = deepcopy(self.runner.state)
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, self.write_trace(self.trace_rows())))
self.assertEqual(self.runner.state, before)
def test_subsequent_combat_and_task_writes_always_prevent_recovery(self):
for operation in ("stageService/stageStart", "battleService/battleStart", "battleService/battleEnd",
"battleService/recordBattleResult", "taskService/taskCompleteStep"):
with self.subTest(operation=operation):
self.legacy_pending()
rows = self.trace_rows() + [{"kind": "request", "operation": operation,
"request_id": "later", "body": {}}]
before = deepcopy(self.runner.state)
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, self.write_trace(rows)))
self.assertEqual(self.runner.state, before)
def test_insufficient_trace_proof_never_mutates_journal(self):
for problem in ("role", "request_id", "later_settlement", "uncertain_write", "ambiguous_owner",
"second_reservation", "role_switch", "missing_role", "failed_http", "failed_code",
"wrong_level", "duplicate_response", "newer_unknown_start", "corrupt", "duplicate_field",
"invalid_reservation", "corrupt_other_owner_reservation"):
with self.subTest(problem=problem):
self.legacy_pending()
rows = self.trace_rows()
if problem == "role":
rows[0]["body"]["master"]["id"] = 18
elif problem == "request_id":
rows[2]["request_id"] = "different"
elif problem in ("later_settlement", "uncertain_write"):
rows.append({"kind": "request", "request_id": "later", "body": {}, "operation":
"battleService/battleEnd" if problem == "later_settlement" else "unknownService/doSomething"})
elif problem == "ambiguous_owner":
self.runner.state["counts"][self.runner.key(self.snapshot, self.stage).replace("17:", "18:", 1)] = 1
elif problem == "second_reservation":
self.runner.state["counts"]["17:2026-11-13:0101:3"] = 1
elif problem == "invalid_reservation":
self.runner.state["counts"] = {"17:invalid:0101:3": 1}
elif problem == "corrupt_other_owner_reservation":
self.runner.state["counts"]["18:2026-11-14:0101:3"] = "1"
elif problem == "role_switch":
rows.insert(2, {"kind": "response", "operation": "读取角色", "body": {"master": {"id": 18}}})
elif problem == "missing_role":
rows.pop(0)
elif problem == "failed_http":
rows[2]["http_status"] = 500
elif problem == "failed_code":
rows[2]["body"]["resCode"] = 2
elif problem == "wrong_level":
rows[1]["body"]["stageLevel"] = "1"
elif problem == "duplicate_response":
rows.append(deepcopy(rows[2]))
rows[-1]["body"]["stageEvent"]["hideStageId"] = "another"
elif problem == "newer_unknown_start":
rows.append(dict(rows[1], request_id="newer"))
self.runner.save()
before = deepcopy(self.runner.state)
disk = self.runner.path.read_bytes()
trace = self.write_trace(rows)
if problem == "corrupt":
with trace.open("a", encoding="utf-8") as stream:
stream.write("\n{broken")
elif problem == "duplicate_field":
trace.write_text(trace.read_text(encoding="utf-8").replace(
'"request_id": "start-1"', '"request_id": "other", "request_id": "start-1"'), encoding="utf-8")
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, trace))
self.assertEqual(self.runner.state, before)
self.assertEqual(self.runner.path.read_bytes(), disk)
if __name__ == "__main__":
unittest.main()