mirror of
https://github.com/db9979/uconsole_asw_game.git
synced 2026-12-05 12:24:25 +01:00
Nightly soak: saves of torpedoes homing on merchants or on a long search run load again
- A hostile torpedo whose seeker holds a merchant (a boat's shot at a convoy) saves it as civilian:<id>; the save used to drop the target and was refused. - A saved torpedo's travel may exceed the catalog range: searching at the quiet seeker speed stretches the store (torpedo_dyn.travel_bound_nm). - Restoring torpedo cues no longer reads a stale loop variable: with no own torpedo in the water every load with an audible intercept was refused. - Soak tool: both loaded copies continue from the same class-wide entity ID counters (sharing them in one process faked a divergence); a diverging save is kept and its first differing field reported. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DtppCtPn57jRcgnW6cBnFR
This commit is contained in:
7 files changed
+179
-20
No files matched your search
+19
-10
@@ -477,6 +477,17 @@ class SaveMixin:
|
||||
"snapshot": dict(pd["snapshot"]),
|
||||
})
|
||||
|
||||
def _enemy_seeker_target_ref(self, target):
|
||||
"""What a hostile torpedo's seeker holds, as a save reference: the
|
||||
frigate, a Nixie, or a merchant a boat's shot homes on (1.3.291)."""
|
||||
if target is self.ship:
|
||||
return "ship"
|
||||
if target in self.nixies:
|
||||
return f"nixie:{target.seq}"
|
||||
if any(target is ship for ship in self.civilians):
|
||||
return f"civilian:{target.id}"
|
||||
return None
|
||||
|
||||
def save_state(self) -> dict:
|
||||
"""Return the complete canonical save state for this release."""
|
||||
opz_map = self._opz_map_save_values()
|
||||
@@ -856,9 +867,7 @@ class SaveMixin:
|
||||
seeker_acquired=t.seeker_acquired,
|
||||
launch_platform_id=t.launch_platform_id,
|
||||
launch_weapon_key=t.launch_weapon_key,
|
||||
seeker_target=("ship" if t._seeker_target is self.ship else
|
||||
f"nixie:{t._seeker_target.seq}"
|
||||
if t._seeker_target in self.nixies else None),
|
||||
seeker_target=self._enemy_seeker_target_ref(t._seeker_target),
|
||||
time_since_launch=t.time_since_launch,
|
||||
energy_s=t.energy_s, motor_fraction=t.motor_fraction,
|
||||
depth_rate=t.depth_rate, target_depth=t.target_depth,
|
||||
@@ -1637,16 +1646,15 @@ class SaveMixin:
|
||||
self.enemy_torpedoes[-1].target_depth = ed["target_depth"]
|
||||
seeker_target = ed["seeker_target"]
|
||||
self.enemy_torpedoes[-1]._seeker_target = (
|
||||
(self.ship if seeker_target == "ship" else
|
||||
next((item for item in self.nixies
|
||||
if seeker_target == f"nixie:{item.seq}"), None))
|
||||
next((item for item in (self.ship, *self.nixies, *self.civilians)
|
||||
if self._enemy_seeker_target_ref(item) == seeker_target), None)
|
||||
if self.enemy_torpedoes[-1].seeker_acquired else None)
|
||||
|
||||
def _restore_links_and_stations(self, data: dict, by_id,
|
||||
restore_platform) -> None:
|
||||
"""Torpedo targets, missiles, buoys, flights, sonar, crew, weapon
|
||||
settings and the torpedo cues (``serial`` keeps the last torpedo
|
||||
of the target loop, as before)."""
|
||||
settings and the torpedo cues (as ``_update_torpedo_cues`` holds
|
||||
them)."""
|
||||
by_id.update((t.id, t) for t in self.enemy_torpedoes)
|
||||
for torpedo, td in zip(self.torpedoes, data["torpedoes_in_flight"]):
|
||||
torpedo.target = by_id.get(td.get("target_id"))
|
||||
@@ -1734,8 +1742,9 @@ class SaveMixin:
|
||||
self.torpedo_cues = []
|
||||
self._torpedo_cues_reported = weakref.WeakKeyDictionary()
|
||||
for cue in self.current_torpedo_cues():
|
||||
self._torpedo_cues_reported.setdefault(cue["owner"], set()).add(cue["report"])
|
||||
self.torpedo_cues.append(dict(cue, serial=id(torpedo)))
|
||||
owner, report = cue.pop("owner"), cue.pop("report")
|
||||
self._torpedo_cues_reported.setdefault(owner, set()).add(report)
|
||||
self.torpedo_cues.append(cue)
|
||||
|
||||
def _restore_rngs(self, data: dict, rng) -> None:
|
||||
# Phase 2: RNG-Zustaende (deterministischer Fortgang)
|
||||
|
||||
@@ -322,18 +322,25 @@ def _check_enemy_torpedo_entry(entry, data, runtime_catalog, group_ids,
|
||||
or not bounded(gy, -1_000_000, 1_000_000)))
|
||||
or type(entry.get("terminal_active", False)) is not bool
|
||||
or type(entry.get("seeker_acquired", False)) is not bool
|
||||
or not bounded(entry.get("travel", 0), 0,
|
||||
profile.range_nm if profile else 10000)):
|
||||
or not bounded(entry.get("travel", 0), 0, torpedo_dyn.travel_bound_nm(
|
||||
profile.range_nm, profile.speed_kn, config.TORP_SPOOLUP_S))):
|
||||
return False
|
||||
seeker = entry.get("seeker_target")
|
||||
nixie_ids = {row["seq"] for row in (
|
||||
data.get("asw", {}).get("nixies", [])
|
||||
if isinstance(data.get("asw"), dict) else [])}
|
||||
# A boat's shot at a convoy may hold a merchant (1.3.291).
|
||||
civilian_ids = {row.get("id") for row in data.get("civilians", [])
|
||||
if isinstance(row, dict)}
|
||||
valid_seeker = (seeker is None or seeker == "ship"
|
||||
or (isinstance(seeker, str)
|
||||
and seeker.startswith("nixie:")
|
||||
and seeker[6:].isdigit()
|
||||
and int(seeker[6:]) in nixie_ids))
|
||||
and int(seeker[6:]) in nixie_ids)
|
||||
or (isinstance(seeker, str)
|
||||
and seeker.startswith("civilian:")
|
||||
and seeker[9:].isdigit()
|
||||
and int(seeker[9:]) in civilian_ids))
|
||||
acquired = entry.get("seeker_acquired", False)
|
||||
launch_platform_id = entry.get("launch_platform_id")
|
||||
launch_weapon_key = entry.get("launch_weapon_key")
|
||||
|
||||
@@ -278,7 +278,9 @@ def check_player_torpedoes(data, torpedoes, entity_ids, runtime_catalog,
|
||||
or not bounded(torpedo.get("speed_kn", Torpedo.SPEED_KN), 0, 10000)
|
||||
or not bounded(torpedo.get("depth", 5), 0, 10000)
|
||||
or not bounded(torpedo.get("target_depth", 5), 0, 10000)
|
||||
or not bounded(torpedo.get("travel", 0), 0, distance)
|
||||
or not bounded(torpedo.get("travel", 0), 0, torpedo_dyn.travel_bound_nm(
|
||||
distance, torpedo.get("speed_kn", Torpedo.SPEED_KN),
|
||||
config.TORP_SPOOLUP_S))
|
||||
or not bounded(torpedo.get("midcourse_timer", 0), 0, Torpedo.WIRE_BREAK_S)
|
||||
or not {"search_phase", "midcourse", "pattern", "enable_nm",
|
||||
"turns_done"} <= set(torpedo)
|
||||
|
||||
@@ -48,6 +48,20 @@ def energy_rate(speed_fraction: float) -> float:
|
||||
return max(0.0, speed_fraction) ** 3
|
||||
|
||||
|
||||
def travel_bound_nm(range_nm: float, speed_kn: float, spoolup_s: float) -> float:
|
||||
"""Longest run one full store allows (bounds a saved ``travel``).
|
||||
|
||||
The store lasts longest at the quiet seeker search speed: cruise-seconds
|
||||
fall with the cube of speed, distance only linearly, so the range there
|
||||
is the catalog range / SEEKER_SEARCH_FRACTION**2. The spool-up and the
|
||||
coast-down to COAST_SINK_FRACTION (ln(1/f)/k cruise-seconds) add their
|
||||
distance on top.
|
||||
"""
|
||||
coast_s = math.log(1.0 / COAST_SINK_FRACTION) / COAST_DRAG_K
|
||||
return (range_nm / SEEKER_SEARCH_FRACTION ** 2
|
||||
+ max(0.0, speed_kn) / 3600.0 * (spoolup_s + coast_s))
|
||||
|
||||
|
||||
def coast_step(fraction: float, dt: float) -> float:
|
||||
"""Exact coast-down of the speed fraction under quadratic drag."""
|
||||
return fraction / (1.0 + COAST_DRAG_K * fraction * dt)
|
||||
|
||||
@@ -237,6 +237,69 @@ def test_terminal_seekers_restore_actual_target_and_command_identity(game):
|
||||
assert game.essms[0].target_id == 39 and game.essms[0].seeker_acquired
|
||||
|
||||
|
||||
def test_enemy_seeker_holding_a_merchant_survives_a_save(game):
|
||||
# A boat's shot at a convoy may home on a merchant; the save used to drop
|
||||
# it, so the save held an acquired seeker without a target and was refused.
|
||||
torpedo = game.enemy_torpedoes[0]
|
||||
torpedo.terminal_active = torpedo.seeker_acquired = True
|
||||
torpedo._seeker_target = game.civilians[0]
|
||||
state = json.loads(json.dumps(game.save_state(), allow_nan=False))
|
||||
assert state["enemy_torpedoes"][0]["seeker_target"] == (
|
||||
f"civilian:{game.civilians[0].id}")
|
||||
game.load_state(state)
|
||||
assert game.enemy_torpedoes[0]._seeker_target is game.civilians[0]
|
||||
state["enemy_torpedoes"][0]["seeker_target"] = "civilian:999999"
|
||||
assert not game._load_save_data(state)
|
||||
|
||||
|
||||
def test_enemy_torpedo_searching_beyond_catalog_range_loads(game):
|
||||
# Searching at the quiet seeker speed stretches the store (power ~ v^3),
|
||||
# so a weapon may run past its catalog range and its save must load.
|
||||
from src.physics import torpedo_dyn
|
||||
torpedo = game.enemy_torpedoes[0]
|
||||
bound = torpedo_dyn.travel_bound_nm(
|
||||
torpedo.range_nm, torpedo.speed_kn, config.TORP_SPOOLUP_S)
|
||||
assert bound > torpedo.range_nm / torpedo_dyn.SEEKER_SEARCH_FRACTION ** 2
|
||||
torpedo.travel = torpedo.range_nm * 1.5
|
||||
game.torpedoes[0].travel = game.torpedoes[0].range_nm * 1.5
|
||||
state = json.loads(json.dumps(game.save_state(), allow_nan=False))
|
||||
game.load_state(state)
|
||||
assert game.enemy_torpedoes[0].travel == torpedo.range_nm * 1.5
|
||||
state["enemy_torpedoes"][0]["travel"] = bound * 1.01
|
||||
assert not game._load_save_data(state)
|
||||
|
||||
|
||||
def test_search_run_travel_stays_within_the_save_bound():
|
||||
# A weapon that only searches burns its whole store at the quiet speed
|
||||
# and coasts down: its run must stay inside travel_bound_nm.
|
||||
from src.physics import torpedo_dyn
|
||||
|
||||
class _Ship:
|
||||
x, y, depth = 500.0, 500.0, 5.0
|
||||
|
||||
torpedo = EnemyTorpedo(0.0, 0.0, 90, 50, 1, guidance_x=0.0, guidance_y=0.0)
|
||||
torpedo.terminal_active = True
|
||||
while torpedo.state == "RUN":
|
||||
torpedo.update(.1, _Ship())
|
||||
assert torpedo.travel > torpedo.range_nm
|
||||
assert torpedo.travel <= torpedo_dyn.travel_bound_nm(
|
||||
torpedo.range_nm, torpedo.speed_kn, config.TORP_SPOOLUP_S)
|
||||
|
||||
|
||||
def test_torpedo_cue_restore_without_own_torpedoes_in_the_water(game):
|
||||
# The cues restored after a load keep their own serial; with no own
|
||||
# torpedo in the water the restore used to raise and refuse the save.
|
||||
game.torpedoes = []
|
||||
torpedo = game.enemy_torpedoes[0]
|
||||
torpedo.x, torpedo.y = game.ship.x + .5, game.ship.y
|
||||
torpedo.terminal_active = True
|
||||
assert any(cue["kind"] == "seeker" for cue in game.current_torpedo_cues())
|
||||
game.load_state(json.loads(json.dumps(game.save_state(), allow_nan=False)))
|
||||
assert [cue["serial"] for cue in game.torpedo_cues] == [
|
||||
id(game.enemy_torpedoes[0])]
|
||||
assert all("owner" not in cue for cue in game.torpedo_cues)
|
||||
|
||||
|
||||
def test_essm_lost_track_retains_observed_datum_without_live_object(game):
|
||||
weapon = game.essms[0]
|
||||
weapon.target = None
|
||||
|
||||
@@ -87,3 +87,39 @@ def test_nightly_workflow_soaks_every_scenario():
|
||||
block = text[text.index("scenario: ["):]
|
||||
block = block[:block.index("]")]
|
||||
assert re.findall(r"[a-z0-9_]+", block.split("[", 1)[1]) == list(config.SCENARIO_ORDER)
|
||||
|
||||
|
||||
def test_continuation_check_gives_both_copies_the_same_entity_ids(monkeypatch):
|
||||
# Both loaded copies share the class-wide ID counters of this process; a
|
||||
# weapon one copy launches must not shift the other's IDs (a false
|
||||
# "diverged" report), and the soak's own game keeps its counters.
|
||||
import argparse
|
||||
|
||||
from src.core.game import Game
|
||||
from src.weapons.torpedo import EnemyTorpedo
|
||||
|
||||
for cls in soak_game.ID_CLASSES:
|
||||
monkeypatch.setattr(cls, "_next_id", cls._next_id)
|
||||
game = Game(seed=3, start_menu=False, show_splash=False, audio_enabled=False,
|
||||
language="en")
|
||||
assert game.start_new_game("s1_patrouille", "fixed", seed=3)
|
||||
game.update(0.1)
|
||||
launches = []
|
||||
original_update = Game.update
|
||||
|
||||
def update(self, dt):
|
||||
original_update(self, dt)
|
||||
if not launches.count(id(self)):
|
||||
launches.append(id(self))
|
||||
self.enemy_torpedoes.append(EnemyTorpedo(
|
||||
self.ship.x + 9, self.ship.y, 270, 50, 1,
|
||||
guidance_x=self.ship.x, guidance_y=self.ship.y))
|
||||
|
||||
monkeypatch.setattr(Game, "update", update)
|
||||
soak = soak_game.Soak(argparse.Namespace(dump_dir=None, check_s=1.0),
|
||||
"s1_patrouille", "frigate", 3)
|
||||
before = [cls._next_id for cls in soak_game.ID_CLASSES]
|
||||
soak.check_continuation(game)
|
||||
assert len(launches) == 2
|
||||
assert soak.failures == []
|
||||
assert [cls._next_id for cls in soak_game.ID_CLASSES] == before
|
||||
+34
-6
@@ -49,8 +49,15 @@ import pygame # noqa: E402
|
||||
from src.core import config # noqa: E402
|
||||
from src.core.game import Game # noqa: E402
|
||||
from src.core.game_save import _same_save_value # noqa: E402
|
||||
from src.enemies.animal import Animal # noqa: E402
|
||||
from src.enemies.decoy import Decoy # noqa: E402
|
||||
from src.enemies.sub import Sub # noqa: E402
|
||||
from src.enemies.surface import SurfaceShip # noqa: E402
|
||||
from src.weapons.torpedo import EnemyTorpedo # noqa: E402
|
||||
|
||||
DT = 0.1
|
||||
# The classes whose entity IDs come from a class-wide counter (as the loader's).
|
||||
ID_CLASSES = (Sub, Animal, SurfaceShip, Decoy, EnemyTorpedo)
|
||||
SIDES = ("frigate", "uboot")
|
||||
_KEYS = ([getattr(pygame, f"K_{n}") for n in range(10)]
|
||||
+ [getattr(pygame, f"K_{c}") for c in "abcdefghijklmnopqrstuvwxyz"]
|
||||
@@ -247,7 +254,8 @@ class Soak:
|
||||
self.failures.append((kind, detail))
|
||||
|
||||
def dump(self, document: dict, game) -> str:
|
||||
"""Keep a refused save in ``--dump-dir``; the report names the file."""
|
||||
"""Keep a refused or diverging save in ``--dump-dir``; the report
|
||||
names the file."""
|
||||
if not self.args.dump_dir:
|
||||
return ""
|
||||
os.makedirs(self.args.dump_dir, exist_ok=True)
|
||||
@@ -263,6 +271,16 @@ class Soak:
|
||||
|
||||
def check_continuation(self, game) -> None:
|
||||
self.checks += 1
|
||||
# The soak's own game resumes from its ID counters as if no check had
|
||||
# run (the loads and both copies allocate from the same counters).
|
||||
before = [cls._next_id for cls in ID_CLASSES]
|
||||
try:
|
||||
self._check_continuation(game)
|
||||
finally:
|
||||
for cls, value in zip(ID_CLASSES, before):
|
||||
cls._next_id = value
|
||||
|
||||
def _check_continuation(self, game) -> None:
|
||||
document = json.loads(json.dumps(game.save_state(), allow_nan=False))
|
||||
twin = Game(seed=1, start_menu=True, show_splash=False, audio_enabled=False,
|
||||
language="en")
|
||||
@@ -275,13 +293,23 @@ class Soak:
|
||||
if not original._load_save_data(json.loads(json.dumps(document))):
|
||||
self.fail("save", f"t={game.sim_t:.0f}s: the save does not load twice")
|
||||
return
|
||||
for _ in range(int(self.args.check_s / DT)):
|
||||
original.update(DT)
|
||||
twin.update(DT)
|
||||
if not _same_save_value(_comparable(original), _comparable(twin)):
|
||||
# Entity IDs come from class-wide counters that every Game in this
|
||||
# process shares, while a player's load runs alone in its process.
|
||||
# So each copy continues from the same counters; run side by side,
|
||||
# a weapon one copy launches would take the next ID and the other's
|
||||
# another, and the ID-keyed sensor noise would differ.
|
||||
counters = [cls._next_id for cls in ID_CLASSES]
|
||||
for loaded in (original, twin):
|
||||
for cls, value in zip(ID_CLASSES, counters):
|
||||
cls._next_id = value
|
||||
for _ in range(int(self.args.check_s / DT)):
|
||||
loaded.update(DT)
|
||||
left, right = _comparable(original), _comparable(twin)
|
||||
if not _same_save_value(left, right):
|
||||
self.fail("determinism",
|
||||
f"t={game.sim_t:.0f}s: two loads of one save diverged within "
|
||||
f"{self.args.check_s:.0f} s")
|
||||
f"{self.args.check_s:.0f} s\nfirst difference: "
|
||||
f"{first_difference(left, right)}" + self.dump(document, game))
|
||||
|
||||
def run(self) -> None:
|
||||
operator = Operator(self.seed)
|
||||
|
||||
Reference in new issue
Block a user