A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Saves: a reload right after End turn keeps that turn (Fixes #1228) (#1261)
Eyal Golandd0cf9f838f7
diff --git a/changelog.d/1228.md b/changelog.d/1228.mdnew file mode 100644index 000000000..090d2a25d--- /dev/null+++ b/changelog.d/1228.md@@ -0,0 +1 @@+- Web autosaves report their exact IndexedDB commit generation; persistence checks reload on that acknowledgement and fail on missing or failed commits instead of treating End turn as proof of persistence.diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 2dbf23da3..7eed61673 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -35,6 +35,7 @@ macOS IL2CPP parity check is not an MVP release gate.uv run tools/web_check.py unity/Builds/Web-gzip --startscreen recording --timeout 300 --stall 90uv run tools/web_check.py unity/Builds/Web-gzip --startscreen new --query lang=he --timeout 300 --stall 90uv run tools/web_check.py unity/Builds/Web-gzip --startscreen recording --query lang=he --timeout 300 --stall 90+ uv run tools/web_check.py unity/Builds/Web-gzip --persistence --timeout 300 --stall 90bash scripts/oss/package_web.sh unity/Builds/Web-gzip unity/Builds/statecraft-israel-vX.Y.Z-web.zip```@@ -48,6 +49,9 @@ macOS IL2CPP parity check is not an MVP release gate.first, which the golden and smoke run skips: New game, and Play the recording then New game, in English and inHebrew. Each must print `PASS`. A console exception, `RECORDING failed` or `BOOT FAIL` fails it (#908).+ The English-only `--persistence` pass waits for each save's matching IndexedDB commit and checks that both reloads+ restore its date, turn and state hash.+For the website's playable demo, build a second web variant with Unity's Decompression Fallback - GitHub Pagescannot set response headers, so the loader must decompress the files itself (the site's Play page explains) -check it and package it the same way:@@ -61,6 +65,7 @@ macOS IL2CPP parity check is not an MVP release gate.uv run tools/web_check.py unity/Builds/Web-pages --startscreen recording --timeout 300 --stall 90uv run tools/web_check.py unity/Builds/Web-pages --startscreen new --query lang=he --timeout 300 --stall 90uv run tools/web_check.py unity/Builds/Web-pages --startscreen recording --query lang=he --timeout 300 --stall 90+ uv run tools/web_check.py unity/Builds/Web-pages --persistence --timeout 300 --stall 90bash scripts/oss/package_web.sh unity/Builds/Web-pages unity/Builds/statecraft-israel-vX.Y.Z-web-pages.zip```diff --git a/tools/tests/test_autosave_persistence.py b/tools/tests/test_autosave_persistence.pynew file mode 100644index 000000000..cc6b28895--- /dev/null+++ b/tools/tests/test_autosave_persistence.py@@ -0,0 +1,125 @@+"""Execute the game's actual WebGL commit observer with held IDBFS callbacks; no browser or Unity needed."""+import shutil+import subprocess+from pathlib import Path++import pytest++PLUGIN = Path(__file__).resolve().parents[2] / "unity/Assets/Scripts/UI/AutosavePersistence.jslib"+pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="needs node to execute the game's jslib")+++def run(body):+ driver = r'''+const assert = require("node:assert/strict");+const mount = {}, other = {}, calls = [], logs = [], errors = [], callbacks = [];+const Module = { __unityIdbfsMount: { mount }, autoSyncPersistentDataPath: true };+const LibraryManager = { library: {} };+function mergeInto(target, value) { Object.assign(target, value); }+function UTF8ToString(value) { return value; }+const console = { log: value => logs.push(value), error: value => errors.push(value) };+const IDBFS = { syncfs(target, populate, callback) {+ assert.equal(this, IDBFS);+ calls.push({ target, populate, callback });+ return "existing sync result";+} };+''' + PLUGIN.read_text() + r'''+const StatecraftAutosave = LibraryManager.library.$StatecraftAutosave;+const request = LibraryManager.library.StatecraftPersistAutosave;+const one = "1 1948-06-15 turn 1 hash aa", two = "2 1948-07-15 turn 2 hash bb";+function flush(target = mount, populate = false) {+ return IDBFS.syncfs(target, populate, error => callbacks.push(error));+}+''' + body+ return subprocess.run(["node", "-e", driver], capture_output=True, text=True, check=True)+++def test_save_ack_waits_for_the_existing_sync_callback_and_starts_no_sync():+ run(r'''+request(one);+assert.equal(calls.length, 0); // file close already queued Unity's timer; the observer must not launch a competing sync+assert.deepEqual(logs, []);+assert.equal(flush(), "existing sync result");+assert.deepEqual(logs, []);+calls[0].callback(null);+assert.deepEqual(logs, ["AUTOSAVE OK " + one]);+assert.deepEqual(callbacks, [null]);+assert.deepEqual(errors, []);+''')+++def test_a_first_request_during_an_older_sync_waits_for_the_followup():+ run(r'''+flush(); // Unity was already syncing before our observer was installed+request(one);+calls[0].callback(null);+assert.deepEqual(logs, []);+flush();+calls[1].callback(null);+assert.deepEqual(logs, ["AUTOSAVE OK " + one]);+assert.equal(calls.length, 2);+''')+++def test_each_generation_belongs_to_the_snapshot_that_started_after_its_request():+ run(r'''+request(one);+IDBFS.syncfs(mount, false, error => { callbacks.push(error); flush(); }); // Unity's 'again' callback starts the next sync+request(two); // writes made while the first snapshot is in flight+calls[0].callback(null);+assert.equal(calls.length, 2);+assert.deepEqual(logs, []); // a superseded snapshot must not claim either exact file state+calls[1].callback(null);+assert.deepEqual(logs, ["AUTOSAVE OK " + two]);+assert.deepEqual(callbacks, [null, null]);+''')+++def test_sync_errors_are_not_success_and_do_not_poison_the_next_save():+ run(r'''+request(one);+flush();+const error = new Error("storage denied");+calls[0].callback(error);+assert.deepEqual(logs, []);+assert.deepEqual(errors, ["AUTOSAVE FAIL " + one]);+assert.equal(callbacks[0], error);+request(two);+flush();+calls[1].callback(null);+assert.deepEqual(logs, ["AUTOSAVE OK " + two]);+''')+++def test_boot_populate_and_other_mounts_pass_through_without_taking_save_requests():+ run(r'''+request(one);+assert.equal(flush(mount, true), "existing sync result");+flush(other);+calls[0].callback(null); calls[1].callback(null);+assert.deepEqual(logs, []);+flush(); calls[2].callback(null);+assert.deepEqual(logs, ["AUTOSAVE OK " + one]);+assert.equal(calls[0].populate, true);+assert.equal(calls[1].target, other);+''')++[email protected]("disable", ["Module.autoSyncPersistentDataPath = false;", "delete Module.__unityIdbfsMount;"])+def test_missing_autosync_fails_instead_of_announcing_durability(disable):+ run(disable + r'''+request(one);+assert.deepEqual(errors, ["AUTOSAVE FAIL " + one]);+assert.deepEqual(logs, []);+assert.equal(calls.length, 0);+''')+++def test_multiple_writes_before_one_flush_acknowledge_only_the_latest_file_contents():+ run(r'''+request(one);+request(two); // one file path now contains two's bytes, not one's+flush();+calls[0].callback(null);+assert.deepEqual(logs, ["AUTOSAVE OK " + two]);+''')diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.pyindex 3c53298e2..a552494f4 100644--- a/tools/tests/test_web_check.py+++ b/tools/tests/test_web_check.py@@ -243,67 +243,66 @@ def test_page_query_adds_navlog_only_to_the_start_screen_runs():assert wc.page_query(_args("--query", "golden")) == "golden"+def _committed_turn(check, generation, date, turn, digest):+ receipt = f"{generation} {date} turn {turn} hash {digest}"+ check.feed("AUTOSAVE PENDING " + receipt)+ check.feed(f"TURN {turn} {date} hash {digest}")+ check.feed("AUTOSAVE OK " + receipt)++def test_persistence_check_reloads_after_a_settled_and_an_immediate_autosave(capsys):actions, sleeps = [], []- buttons = _buttons()- check = wc.PersistenceCheck(actions.append, buttons, sleeps.append)+ check = wc.PersistenceCheck(actions.append, _buttons(), sleeps.append)check.feed("GAME OK 1948-05-15 turn 0 hash aa00")- check.feed("TURN 1 1948-06-01 turn 1 hash one") # unrelated malformed diagnostic is ignored- check.feed("TURN 1 1948-06-01 hash aaa1")- assert buttons.centres == {}, "a reload forgets the old page's layout"- buttons.feed(LAID_OUT) # the reloaded page logs its own+ check.feed("TURN 1 1948-06-01 turn 1 hash one") # malformed diagnostic is ignored+ _committed_turn(check, 1, "1948-06-01", 1, "aaa1")+ assert check.buttons.centres == {}, "a reload forgets the old page's layout"+ check.buttons.feed(LAID_OUT) # the reloaded page reports its own layoutcheck.feed("GAME OK 1948-06-01 turn 1 hash aaa1")- check.feed("TURN 2 1948-07-01 hash aaa2")+ _committed_turn(check, 1, "1948-07-01", 2, "aaa2") # a reload resets the page's counter+ check.buttons.feed(LAID_OUT) # the reloaded page reports its own layoutcheck.feed("GAME OK 1948-07-01 turn 2 hash aaa2")new_game, cont, end_turn = _clicks(AT["start-new-game"], AT["start-continue"], wc.END_TURN)assert actions == [new_game, end_turn, "reload", cont, end_turn, "reload"]- assert sleeps == [3, 2, 2, 3, 2] # no wait between the second TURN and its reload+ assert sleeps == [3, 2, 3, 2] # UI layout only; neither commit uses a settling delayassert check.doneassert "settled reload OK" in capsys.readouterr().out-def test_persistence_check_fails_when_the_immediate_reload_did_not_load_the_saved_turn():- buttons = _buttons()- check = wc.PersistenceCheck(lambda action: action == "reload" and buttons.feed(LAID_OUT), buttons, lambda seconds: None)- for text in ("GAME OK 1948-05-15 turn 0 hash aa", "TURN 1 1948-06-01 hash bb",- "GAME OK 1948-06-01 turn 1 hash bb", "TURN 2 1948-07-01 hash cc"):- check.feed(text)- try:- check.feed("GAME OK 1948-06-01 turn 1 hash bb")- except ValueError as e:- assert "PERSISTENCE FAIL immediate reload" in str(e) and "file a follow-up" in str(e)- else:- raise AssertionError("a lost immediate autosave must fail")+def _played_to_the_settled_reload(check):+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")+ _committed_turn(check, 1, "1948-06-15", 1, "bb")-def _played_to_the_settled_reload(check):- for text in ("GAME OK 1948-05-15 turn 0 hash aa", "TURN 1 1948-06-15 hash bb"):- check.feed(text)+def test_persistence_check_fails_when_the_immediate_reload_did_not_load_the_saved_turn():+ check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)+ _played_to_the_settled_reload(check)+ check.buttons.feed(LAID_OUT) # the reloaded page reports its own layout+ check.feed("GAME OK 1948-06-15 turn 1 hash bb")+ _committed_turn(check, 1, "1948-07-15", 2, "cc")+ with pytest.raises(ValueError, match="PERSISTENCE FAIL immediate reload"):+ check.feed("GAME OK 1948-06-15 turn 1 hash bb")def test_persistence_check_fails_when_the_settled_reload_did_not_load_the_saved_turn():check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)_played_to_the_settled_reload(check)with pytest.raises(ValueError, match="PERSISTENCE FAIL settled reload got 1948-05-15 turn 0"):- check.feed("GAME OK 1948-05-15 turn 0 hash aa") # the reload came up with no save: a fresh game- assert not check.done+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")def test_persistence_check_fails_when_continue_started_a_new_game():- """A click that misses Continue and starts a new game must not pass: the turn after Continue is the reloaded- game's next turn (2), not a new game's turn 1."""check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)_played_to_the_settled_reload(check)- check.buttons.feed(LAID_OUT)+ check.buttons.feed(LAID_OUT) # the reloaded page reports its own layoutcheck.feed("GAME OK 1948-06-15 turn 1 hash bb")- with pytest.raises(ValueError, match="PERSISTENCE FAIL End turn after Continue: turn 1 .*expected turn 2"):- check.feed("TURN 1 1948-06-15 hash cc")- assert not check.done+ with pytest.raises(ValueError, match="expected turn 2"):+ check.feed("TURN 1 1948-06-15 hash bb")def test_persistence_check_fails_when_the_first_boot_is_not_a_fresh_game():check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)- with pytest.raises(ValueError, match="PERSISTENCE FAIL first boot"):+ with pytest.raises(ValueError, match="expected turn 0"):check.feed("GAME OK 1948-06-15 turn 1 hash bb")@@ -470,3 +469,81 @@ def test_mobile_only_flips_the_emulation_flag():assert wc.viewport_override(1920, 1080, 1.0)["mobile"] is False # the desktop default (review ruling 1)phone = wc.viewport_override(390, 844, 3.0, True)assert phone == {"width": 390, "height": 844, "deviceScaleFactor": 3.0, "mobile": True}+++def test_persistence_check_does_not_reload_turn_two_before_its_commit_ack():+ actions = []+ check = wc.PersistenceCheck(actions.append, _buttons(), lambda seconds: None)+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")+ check.feed("AUTOSAVE PENDING 1 1948-06-15 turn 1 hash bb")+ check.feed("TURN 1 1948-06-15 hash bb")+ check.feed("AUTOSAVE OK 1 1948-06-15 turn 1 hash bb")+ check.buttons.feed(LAID_OUT) # the reloaded page reports its own layout+ check.feed("GAME OK 1948-06-15 turn 1 hash bb")+ assert actions.count("reload") == 1+ check.feed("AUTOSAVE PENDING 2 1948-07-15 turn 2 hash cc")+ check.feed("TURN 2 1948-07-15 hash cc")+ assert actions.count("reload") == 1, "TURN is not an IndexedDB commit acknowledgement"+ check.feed("AUTOSAVE OK 2 1948-07-15 turn 2 hash cc")+ assert actions.count("reload") == 2+ check.buttons.feed(LAID_OUT) # the reloaded page reports its own layout+ check.feed("GAME OK 1948-07-15 turn 2 hash cc")+ assert check.done++[email protected]("ack", [+ "AUTOSAVE OK 1 1948-07-15 turn 2 hash cc", # old generation, identical state+ "AUTOSAVE OK 2 1948-07-15 turn 2 hash dd", # wrong hash+ "AUTOSAVE OK 2 1948-06-15 turn 1 hash bb", # old turn/date+])+def test_a_stale_or_mismatched_save_ack_cannot_authorize_reload(ack):+ actions = []+ check = wc.PersistenceCheck(actions.append, _buttons(), lambda seconds: None)+ _played_to_the_settled_reload(check)+ check.buttons.feed(LAID_OUT) # the reloaded page reports its own layout+ check.feed("GAME OK 1948-06-15 turn 1 hash bb")+ check.feed("AUTOSAVE PENDING 2 1948-07-15 turn 2 hash cc")+ check.feed("TURN 2 1948-07-15 hash cc")+ check.feed(ack)+ assert actions.count("reload") == 1+ assert not check.done+ check.feed("AUTOSAVE OK 2 1948-07-15 turn 2 hash cc")+ assert actions.count("reload") == 2+++def test_a_commit_timeout_fails_even_without_any_further_console_line():+ clock = [0.0]+ check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None, now=lambda: clock[0], save_timeout=5)+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")+ check.feed("TURN 1 1948-06-15 hash bb")+ clock[0] = 5+ with pytest.raises(ValueError, match="no matching IndexedDB commit within 5s"):+ _ = check.done+++def test_an_indexeddb_failure_fails_the_driver_loudly():+ check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)+ with pytest.raises(ValueError, match="IndexedDB autosave failed"):+ check.feed("AUTOSAVE FAIL 1 1948-06-15 turn 1 hash bb")+++def test_commit_ack_before_turn_diagnostic_is_not_lost():+ actions = []+ check = wc.PersistenceCheck(actions.append, _buttons(), lambda seconds: None)+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")+ check.feed("AUTOSAVE PENDING 1 1948-06-15 turn 1 hash bb")+ check.feed("AUTOSAVE OK 1 1948-06-15 turn 1 hash bb")+ assert "reload" not in actions+ check.feed("TURN 1 1948-06-15 hash bb")+ assert actions.count("reload") == 1+++def test_commit_timeout_is_polled_while_an_unrelated_expectation_is_still_missing():+ clock = [0.0]+ check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None, now=lambda: clock[0], save_timeout=5)+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")+ check.feed("TURN 1 1948-06-15 hash bb")+ with pytest.raises(ValueError, match="no matching IndexedDB commit within 5s"):+ wc.watch(queue.Queue(), lambda: None, lambda: None, ["UNRELATED"], re.compile("BOOT FAIL"), 20,+ now=lambda: clock[0], sleep=lambda seconds: clock.__setitem__(0, clock[0] + 1),+ complete=lambda: check.done)diff --git a/tools/web_check.py b/tools/web_check.pyindex 44700c57b..084003329 100644--- a/tools/web_check.py+++ b/tools/web_check.py@@ -13,8 +13,8 @@ Options: --query Q (page URL query, without '?'), --expect TEXT (repeatable), ----timeout SECONDS (default 300), --stall SECONDS (fail when no console message arrives for that long; 0 = off),--swiftshader (software WebGL when there is no GPU), --dpr N (default 1), --shots DIR (reassemble the player's"SHOT" console lines, from ?shot, into DIR/<pose>.png; a "SHOT done" with an unfinished shot fails the run),---persistence (play one normal turn, reload and Continue after a settling delay, then play another turn and reload-immediately; both reloads must report the saved date, turn and hash), --startscreen new|recording (#908: on a fresh+--persistence (play one normal turn, wait for its matching IndexedDB commit, reload and Continue, then play another+turn and reload as soon as its matching commit arrives; both reloads must report the saved date, turn and hash), --startscreen new|recording (#908: on a freshprofile, the real start screen every player sees first: "new" presses New game, "recording" first presses Play therecording and waits for RECORDING playing; then End turn must log TURN 1; any console Exception, RECORDING failed orBOOT FAIL fails the run; add --query lang=he for the Hebrew layout). Both runs add ?navlog and click the start screen's@@ -389,6 +389,7 @@ START_BUTTON = re.compile(r"(\S+)=(\d+(?:\.\d+)?),(\d+(?:\.\d+)?)")NAVLOG = "navlog"GAME_STATE = re.compile(r"^GAME OK (\d{4}-\d{2}-\d{2}) turn (\d+) hash ([0-9a-f]+)$")TURN_STATE = re.compile(r"^TURN (\d+) (\d{4}-\d{2}-\d{2}) hash ([0-9a-f]+)$")+SAVE_STATE = re.compile(r"^AUTOSAVE (PENDING|OK|FAIL) ([1-9]\d*) (\d{4}-\d{2}-\d{2}) turn (\d+) hash ([0-9a-f]+)$")class StartButtons:@@ -438,14 +439,47 @@ def click_button(action, buttons: StartButtons, name: str) -> None:class PersistenceCheck:"""Drives and checks the two reloads of issue #910. `action` is Page.command (injected, so the unit tests need no- browser); a reload keeps the page's profile and origin, so its IndexedDB autosave. `buttons` says where the start- screen's buttons are."""-- def __init__(self, action, buttons: StartButtons, settle=time.sleep):- self.action, self.buttons, self.settle = action, buttons, settle- self.stage, self.saved, self.done = "first_boot", None, False+ browser); a reload keeps the page's profile and origin, so its IndexedDB autosave."""++ def __init__(self, action, buttons: StartButtons, settle=time.sleep, now=time.monotonic, save_timeout=15.0):+ self.action, self.buttons, self.settle, self.now, self.save_timeout = action, buttons, settle, now, save_timeout+ self.stage, self.saved, self._done = "first_boot", None, False+ self.pending, self.acknowledged, self.deadline = None, None, None++ @property+ def done(self) -> bool:+ # watch polls this even when no more console lines arrive.+ if self.deadline is not None and self.now() >= self.deadline:+ raise ValueError(f"PERSISTENCE FAIL no matching IndexedDB commit within {self.save_timeout:g}s: "+ f"{self.saved}; pending receipt {self.pending}")+ return self._done++ def _reload_when_durable(self) -> None:+ if self.stage not in ("first_commit", "second_commit"):+ return+ if self.pending is None or self.pending[1:] != self.saved or self.acknowledged != self.pending:+ return+ first = self.stage == "first_commit"+ self.deadline = None+ self.stage = "settled_reload" if first else "immediate_reload"+ self.buttons.clear()+ self.action("reload")def feed(self, text: str) -> None:+ _ = self.done # fail a missing acknowledgement before processing later diagnostics+ receipt = SAVE_STATE.match(text)+ if receipt:+ kind, generation, date, turn, digest = receipt.groups()+ value = (int(generation), date, int(turn), digest)+ if kind == "FAIL":+ raise ValueError(f"PERSISTENCE FAIL IndexedDB autosave failed: {value}")+ if kind == "PENDING":+ if self.pending is None or value[0] > self.pending[0]:+ self.pending, self.acknowledged = value, None+ elif value == self.pending:+ self.acknowledged = value+ self._reload_when_durable()+ returngame, turn = GAME_STATE.match(text), TURN_STATE.match(text)if game:state, kind = (game.group(1), int(game.group(2)), game.group(3)), "GAME"@@ -456,37 +490,34 @@ class PersistenceCheck:if self.stage == "first_boot" and kind == "GAME":self._turn(state, 0, "first boot (a fresh profile has no save)")self.settle(3) # the start screen lays out and takes input- self.click(NEW_GAME) # normal mode: no ?smoke and no ?nostart+ self.click(NEW_GAME)self.settle(2)- self.click(END_TURN)self.stage = "first_turn"+ self.click(END_TURN)elif self.stage == "first_turn" and kind == "TURN":self._turn(state, 1, "first End turn after New game")- self.saved = state- self.settle(2) # ordinary reload: give IDBFS autosync time to settle- self.buttons.clear()- self.action("reload")- self.stage = "settled_reload"+ self.saved, self.stage = state, "first_commit"+ self.deadline = self.now() + self.save_timeout+ self._reload_when_durable()elif self.stage == "settled_reload" and kind == "GAME":self._same(state, "settled")print(f"PERSISTENCE settled reload OK {state[0]} turn {state[1]} hash {state[2]}")+ # A new page starts its generation counter again; old-page receipts cannot acknowledge its save.+ self.pending, self.acknowledged = None, Noneself.settle(3)self.click(CONTINUE)self.settle(2)- self.click(END_TURN)self.stage = "second_turn"+ self.click(END_TURN)elif self.stage == "second_turn" and kind == "TURN":- # Continue must have resumed the reloaded game: its next turn, not a new game's turn 1 (a click on the wrong- # button would otherwise pass).self._turn(state, self.saved[1] + 1, "End turn after Continue")- self.saved = state- self.buttons.clear()- self.action("reload") # deliberately no settling delay after the TURN acknowledgement- self.stage = "immediate_reload"+ self.saved, self.stage = state, "second_commit"+ self.deadline = self.now() + self.save_timeout+ self._reload_when_durable()elif self.stage == "immediate_reload" and kind == "GAME":self._same(state, "immediate")print(f"PERSISTENCE immediate reload OK {state[0]} turn {state[1]} hash {state[2]}")- self.done = True+ self._done = Truedef click(self, target: str | tuple[int, int]) -> None:if isinstance(target, str):@@ -584,7 +615,8 @@ def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=if status == "fail":print(f"FAIL: {texts[-1]}")return 1- if status == "pass" and (complete is None or complete()):+ finished = complete is None or complete() # poll the deadline while other expectations are pending too+ if status == "pass" and finished:if passes_at is None:passes_at = now() + graceif now() >= passes_at:diff --git a/unity/Assets/Scripts/SaveStore.cs b/unity/Assets/Scripts/SaveStore.csindex 120ed7639..70a64c77d 100644--- a/unity/Assets/Scripts/SaveStore.cs+++ b/unity/Assets/Scripts/SaveStore.cs@@ -7,7 +7,8 @@ namespace Statecraft.Game/// <summary>Where the autosave lives (spec section 7: autosave every turn). On WebGL it is a fixed folder under the/// /idbfs IndexedDB mount, not Application.persistentDataPath, because that path hashes the page's URL and itch.io/// serves every upload from a new URL, which would hide old saves (tech notes section 3). The template sets- /// autoSyncPersistentDataPath, so closing the file persists it. Writes go to a .tmp file first, then replace.</summary>+ /// autoSyncPersistentDataPath, so closing the file queues an asynchronous persist. GameStart acknowledges the+ /// IndexedDB commit separately. Writes go to a .tmp file first, then replace.</summary>public class SaveStore{public const string WebDirectory = "/idbfs/statecraft-saves";diff --git a/unity/Assets/Scripts/UI/AutosavePersistence.jslib b/unity/Assets/Scripts/UI/AutosavePersistence.jslibnew file mode 100644index 000000000..0a5e072ca--- /dev/null+++ b/unity/Assets/Scripts/UI/AutosavePersistence.jslib@@ -0,0 +1,37 @@+// Observe Unity 6000.3's existing autosync, never start a concurrent FS.syncfs. SaveStore has already closed and+// renamed the file; autoPersist queued that mount. Capture requests when its next flush starts, so a request made+// during an older in-flight flush cannot be acknowledged by the older snapshot. TURN remains a sim diagnostic.+mergeInto(LibraryManager.library, {+ $StatecraftAutosave: { pending: null, latest: null, installed: false },+ StatecraftPersistAutosave__deps: ["$StatecraftAutosave", "$IDBFS"],+ StatecraftPersistAutosave: function (receiptPtr) {+ var receipt = UTF8ToString(receiptPtr);+ var mount = Module.__unityIdbfsMount && Module.__unityIdbfsMount.mount;+ if (!mount || !Module.autoSyncPersistentDataPath) {+ console.error("AUTOSAVE FAIL " + receipt);+ return;+ }+ var saves = StatecraftAutosave;+ if (!saves.installed) {+ var sync = IDBFS.syncfs;+ IDBFS.syncfs = function (target, populate, callback) {+ if (populate || target !== mount) return sync.call(this, target, populate, callback);+ var saved = saves.pending;+ saves.pending = null;+ return sync.call(this, target, populate, function (error) {+ // Unity's callback owns its idb/again state and starts a queued follow-up flush. Leave it intact.+ try { callback(error); }+ finally {+ if (saved) {+ if (error) console.error("AUTOSAVE FAIL " + saved);+ else if (saved === saves.latest) console.log("AUTOSAVE OK " + saved);+ }+ }+ });+ };+ saves.installed = true;+ }+ // Multiple writes before the queued flush overwrite the same autosave path: only its latest bytes can be durable.+ saves.pending = saves.latest = receipt;+ },+});diff --git a/unity/Assets/Scripts/UI/AutosavePersistence.jslib.meta b/unity/Assets/Scripts/UI/AutosavePersistence.jslib.metanew file mode 100644index 000000000..d0c0377f0--- /dev/null+++ b/unity/Assets/Scripts/UI/AutosavePersistence.jslib.meta@@ -0,0 +1,32 @@+fileFormatVersion: 2+guid: 3ba9f49777c74a0484b27f6a6b288a97+PluginImporter:+ externalObjects: {}+ serializedVersion: 2+ iconMap: {}+ executionOrder: {}+ defineConstraints: []+ isPreloaded: 0+ isOverridable: 0+ isExplicitlyReferenced: 0+ validateReferences: 1+ platformData:+ - first:+ Any:+ second:+ enabled: 0+ settings: {}+ - first:+ Editor: Editor+ second:+ enabled: 0+ settings:+ DefaultValueInitialized: true+ - first:+ WebGL: WebGL+ second:+ enabled: 1+ settings: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/UI/GameStart.cs b/unity/Assets/Scripts/UI/GameStart.csindex 0d599c7e0..2206af939 100644--- a/unity/Assets/Scripts/UI/GameStart.cs+++ b/unity/Assets/Scripts/UI/GameStart.cs@@ -12,6 +12,8 @@ namespace Statecraft.Game.UI/// session never touches the player's save, and tests use it. New Game goes through SimBridge.Replace instead.</summary>public static class GameStart{+ static long saveGeneration;+public static ulong NewSeed() => (ulong)DateTime.UtcNow.Ticks;public static GameSession Begin(Content c, SaveStore store, Func<ulong> newSeed, List<string> notes, UiText text, bool fresh = false) =>@@ -64,7 +66,20 @@ namespace Statecraft.Game.UI{void Save(IReadOnlyList<Rejection> _){- try { store.WriteAutosave(bridge.Session.Save.Write()); }+ try+ {+ store.WriteAutosave(bridge.Session.Save.Write());+ // Capture this save, not the mutable session at an asynchronous commit's completion.+ var state = bridge.State;+ var generation = System.Threading.Interlocked.Increment(ref saveGeneration);+ var receipt = FormattableString.Invariant($"{generation} {state.Date:yyyy-MM-dd} turn {state.Turn} hash {state.Hash()}");+ UnityEngine.Debug.Log("AUTOSAVE PENDING " + receipt);+#if UNITY_WEBGL && !UNITY_EDITOR+ StatecraftPersistAutosave(receipt);+#else+ UnityEngine.Debug.Log("AUTOSAVE OK " + receipt);+#endif+ }catch (Exception e){UnityEngine.Debug.LogWarning("Autosave could not be written: " + e);@@ -75,6 +90,11 @@ namespace Statecraft.Game.UIreturn new Unsubscribe(() => bridge.TurnEnded -= Save);}+#if UNITY_WEBGL && !UNITY_EDITOR+ [System.Runtime.InteropServices.DllImport("__Internal")]+ static extern void StatecraftPersistAutosave(string receipt);+#endif+sealed class Unsubscribe : IDisposable{readonly Action undo;diff --git a/unity/Assets/Tests/EditMode/SaveUiTests.cs b/unity/Assets/Tests/EditMode/SaveUiTests.csindex e428f6147..44ad402b0 100644--- a/unity/Assets/Tests/EditMode/SaveUiTests.cs+++ b/unity/Assets/Tests/EditMode/SaveUiTests.cs@@ -57,6 +57,38 @@ public class SaveUiTestsAssert.AreEqual(2, resumed.State.Turn);}+ [Test]+ public void AutosaveReceiptsKeepTheirGenerationAndSavedState()+ {+ var store = TempStore();+ var bridge = new SimBridge(GameStart.Begin(C, store, () => 77UL, new List<string>(), Text), Text);+ var lines = new List<string>();+ void Logged(string message, string stack, LogType kind)+ {+ if (message.StartsWith("AUTOSAVE ", System.StringComparison.Ordinal)) lines.Add(message);+ }+ Application.logMessageReceived += Logged;+ try+ {+ using var save = GameStart.Autosave(bridge, store, Text);+ bridge.EndTurn();+ var first = bridge.State.Hash();+ bridge.EndTurn();+ Assert.AreEqual(4, lines.Count);+ var receipt1 = lines[0].Substring("AUTOSAVE PENDING ".Length);+ var receipt2 = lines[2].Substring("AUTOSAVE PENDING ".Length);+ Assert.AreEqual("AUTOSAVE OK " + receipt1, lines[1]);+ Assert.AreEqual("AUTOSAVE OK " + receipt2, lines[3]);+ var g1 = long.Parse(receipt1.Split(' ')[0], System.Globalization.CultureInfo.InvariantCulture);+ var g2 = long.Parse(receipt2.Split(' ')[0], System.Globalization.CultureInfo.InvariantCulture);+ Assert.Greater(g2, g1);+ StringAssert.EndsWith("turn 1 hash " + first, receipt1);+ StringAssert.EndsWith("turn 2 hash " + bridge.State.Hash(), receipt2);+ Assert.AreEqual(bridge.State.Hash(), GameStart.Begin(C, store, () => 1UL, new List<string>(), Text).State.Hash());+ }+ finally { Application.logMessageReceived -= Logged; }+ }+[Test]public void AnUnreadableAutosaveIsSetAsideAndANewGameStarts(){diff --git a/unity/Assets/WebGLTemplates/Statecraft/index.html b/unity/Assets/WebGLTemplates/Statecraft/index.htmlindex 54e05278f..3ecb7a6fa 100644--- a/unity/Assets/WebGLTemplates/Statecraft/index.html+++ b/unity/Assets/WebGLTemplates/Statecraft/index.html@@ -41,7 +41,8 @@companyName: {{{ JSON.stringify(COMPANY_NAME) }}},productName: {{{ JSON.stringify(PRODUCT_NAME) }}},productVersion: {{{ JSON.stringify(PRODUCT_VERSION) }}},- // Persist writes under /idbfs to IndexedDB when a file is closed (tech notes section 3): saves need no manual sync.+ // Queue IndexedDB persistence when a file under /idbfs closes; completion is asynchronous.+ // GameStart's save receipt observes that commit, without starting a concurrent manual sync.autoSyncPersistentDataPath: true,};// Issue #437: the Build/ files are named by their content hash, and this page names its build's files. A browser may