Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

fix(unity): a boot download that receives nothing for 30 s is retried, then fails visibly (Fixes #911) (#923)

Eyal Golanac4a8644c6da
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5342e276d..98d67ecd7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -49,6 +49,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
- The map legend is hidden while the decision card is open, so no card, the photograph's included, covers it at any
window, desktop or phone; it comes back when the card is hidden or answered (Fixes #849; the owner's decision of
17 October 2026, "Hide legend under card"). The card and its photograph keep their full size.
+- A boot download that receives nothing for 30 seconds is aborted and retried like a dropped connection (up to four
+ attempts), then shows the boot failure, instead of leaving the loading screen up forever. A slow download that keeps
+ receiving data is never cut off (#911).
- The content loader now checks `name_he_review` on people rows the way it does for parties, governments,
legislatures, offices and settlements: the flag is `agent-checked` or left out, and only beside a `name_he`
(CONTENT_POLICY section 2, rule 6; #862). No people row carries the flag yet, so no row changes.
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index af8af14d0..4d240de0c 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -141,18 +141,37 @@ namespace Statecraft.Game.Boot
result == UnityWebRequest.Result.ConnectionError
|| (result == UnityWebRequest.Result.ProtocolError && (status >= 500 || status == 408 || status == 429));
- /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice) until r is done. On a
- /// transient failure r is released and its URL fetched again after Backoff, up to MaxAttempts in all. Returns the
+ /// <summary>Seconds a download may go without receiving a byte before it is aborted as stalled and retried like a
+ /// dropped connection (#911). A limit on silence, not on the whole download: the 4 MB heightmap on a slow
+ /// connection keeps receiving bytes and is never cut off, while a server that accepts the request and never
+ /// answers reaches the retry and then BOOT FAIL instead of leaving the loading screen up forever. A fixed limit on
+ /// the whole fetch failed slow but healthy fetches before (#503). The value needs the maintainer's sign-off (#911).</summary>
+ internal const float StallSeconds = 30f;
+
+ /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice) until r is done, or
+ /// aborts it when no byte has arrived for <paramref name="stallSeconds"/>. On a transient failure (a stall counts as
+ /// a connection error) r is released and its URL fetched again after Backoff, up to MaxAttempts in all. Returns the
/// request that succeeded (the caller releases it); on a final failure every attempt is released and an
/// IOException names the file. Retrying changes only when a file arrives, never its bytes or the parse order.</summary>
- static async Awaitable<UnityWebRequest> Done(UnityWebRequest r, string name)
+ static async Awaitable<UnityWebRequest> Done(UnityWebRequest r, string name, float stallSeconds)
{
for (var attempt = 1; ; attempt++)
{
- while (!r.isDone) await Awaitable.NextFrameAsync();
- if (r.result == UnityWebRequest.Result.Success) return r;
- var error = $"{name}: {r.error} ({r.url})";
- var retry = attempt < MaxAttempts && Transient(r.result, r.responseCode);
+ var stalled = false;
+ var bytes = r.downloadedBytes;
+ var lastByte = Time.realtimeSinceStartup;
+ while (!r.isDone)
+ {
+ if (r.downloadedBytes != bytes) { bytes = r.downloadedBytes; lastByte = Time.realtimeSinceStartup; }
+ else if (Time.realtimeSinceStartup - lastByte > stallSeconds) { stalled = true; break; }
+ await Awaitable.NextFrameAsync();
+ }
+ if (!stalled && r.result == UnityWebRequest.Result.Success) return r;
+ var error = stalled
+ ? FormattableString.Invariant($"{name}: no data for {stallSeconds:0.#} s ({r.url})")
+ : $"{name}: {r.error} ({r.url})";
+ var retry = attempt < MaxAttempts
+ && (stalled ? Transient(UnityWebRequest.Result.ConnectionError, 0) : Transient(r.result, r.responseCode));
var url = r.url;
Release(r);
if (!retry) throw new IOException(attempt > 1 ? $"{error} after {attempt} attempts" : error);
@@ -163,16 +182,16 @@ namespace Statecraft.Game.Boot
}
}
- static async Awaitable<string> Text(UnityWebRequest r, string name)
+ static async Awaitable<string> Text(UnityWebRequest r, string name, float stallSeconds)
{
- r = await Done(r, name);
+ r = await Done(r, name, stallSeconds);
try { return r.downloadHandler.text; }
finally { Release(r); }
}
- static async Awaitable<byte[]> Bytes(UnityWebRequest r, string name)
+ static async Awaitable<byte[]> Bytes(UnityWebRequest r, string name, float stallSeconds)
{
- r = await Done(r, name);
+ r = await Done(r, name, stallSeconds);
try { return r.downloadHandler.data; }
finally { Release(r); }
}
@@ -187,18 +206,21 @@ namespace Statecraft.Game.Boot
/// <summary>Fetches the manifest, then starts every download before awaiting any (parallel), then loads. A transient
/// failure is retried (Done). When one download fails for good, the others still running are aborted and disposed.
/// Every URL carries <paramref name="buildId"/> (WithBuildId; the player passes Application.buildGUID).</summary>
- public static async Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId = "")
+ public static Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId = "") => FetchAsync(baseUrl, buildId, StallSeconds);
+
+ /// <summary>FetchAsync with another stall limit (the stalled-server test uses a short one).</summary>
+ internal static async Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId, float stallSeconds)
{
- var manifest = ContentManifest.Parse(await Text(Start(WithBuildId(baseUrl + "/content/" + ContentManifest.FileName, buildId)), ContentManifest.FileName));
+ var manifest = ContentManifest.Parse(await Text(Start(WithBuildId(baseUrl + "/content/" + ContentManifest.FileName, buildId)), ContentManifest.FileName, stallSeconds));
var requests = manifest.Select(f => (file: f, request: Start(WithBuildId(baseUrl + "/content/" + f, buildId)))).ToList();
var meta = Start(WithBuildId(baseUrl + "/map/heightmap.json", buildId));
var r16z = Start(WithBuildId(baseUrl + "/map/" + HeightmapCodec.FileName, buildId));
try
{
var texts = new Dictionary<string, string>();
- foreach (var (file, request) in requests) texts[file] = await Text(request, file);
- var metaText = await Text(meta, "heightmap.json");
- var r16zBytes = await Bytes(r16z, HeightmapCodec.FileName);
+ foreach (var (file, request) in requests) texts[file] = await Text(request, file, stallSeconds);
+ var metaText = await Text(meta, "heightmap.json", stallSeconds);
+ var r16zBytes = await Bytes(r16z, HeightmapCodec.FileName, stallSeconds);
DiagLog.BootPhase($"downloaded {texts.Count + 3} files");
var inputs = FromTexts(texts, manifest, metaText, r16zBytes);
DiagLog.BootPhase("content parsed and validated");
diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.cs
index 8268ffb36..4b309e12e 100644
--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs
+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs
@@ -6,6 +6,7 @@ using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
+using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Statecraft.Game;
@@ -117,6 +118,7 @@ public class GameInputsTests
readonly string root;
readonly Dictionary<string, (string fault, int times)> faults;
readonly ConcurrentDictionary<string, int> hits = new ConcurrentDictionary<string, int>();
+ readonly ManualResetEventSlim stopped = new ManualResetEventSlim();
/// <summary>Every request target as sent, query included (e.g. "/content/people.yaml?b=..."), in arrival order.</summary>
public readonly ConcurrentQueue<string> Targets = new ConcurrentQueue<string>();
public readonly string BaseUrl;
@@ -162,6 +164,8 @@ public class GameInputsTests
if (faults.TryGetValue(rel, out var f) && n <= f.times)
{
if (f.fault == "drop") { client.Client.LingerState = new LingerOption(true, 0); client.Client.Close(); return; } // RST
+ if (f.fault == "stall") { stopped.Wait(); return; } // Accept the request but never answer it.
+ if (f.fault == "trickle") { Trickle(stream, File.ReadAllBytes(Path.Combine(root, rel))); return; }
Respond(stream, int.Parse(f.fault), new byte[0]);
return;
}
@@ -178,7 +182,21 @@ public class GameInputsTests
stream.Write(body, 0, body.Length);
}
- public void Dispose() => listener.Stop();
+ /// <summary>A slow but healthy download: the whole file, in TrickleChunks parts TrickleGapMs apart.</summary>
+ static void Trickle(NetworkStream stream, byte[] body)
+ {
+ var head = System.Text.Encoding.ASCII.GetBytes($"HTTP/1.0 200 OK\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
+ stream.Write(head, 0, head.Length);
+ var part = (body.Length + TrickleChunks - 1) / TrickleChunks;
+ for (var at = 0; at < body.Length; at += part)
+ {
+ Thread.Sleep(TrickleGapMs);
+ stream.Write(body, at, Math.Min(part, body.Length - at));
+ stream.Flush();
+ }
+ }
+
+ public void Dispose() { stopped.Set(); listener.Stop(); }
}
/// <summary>Seconds a fetch may go without progress before it counts as hung. Not a limit on the whole fetch: under
@@ -314,6 +332,76 @@ public class GameInputsTests
finally { Directory.Delete(site, true); }
}
+ const int TrickleChunks = 10, TrickleGapMs = 300;
+
+ /// <summary>#911: the stall limit is on silence, not on the whole download. A file that takes 3 s to arrive, a part every
+ /// 0.3 s, passes a 2 s stall limit at its first attempt (a fixed per-request timeout would cut it off).</summary>
+ [UnityTest, Timeout(FetchTestTimeoutMs)]
+ public IEnumerator ASlowDownloadThatKeepsReceivingIsNotCutOff()
+ {
+ var site = StagedSite();
+ try
+ {
+ var faults = new Dictionary<string, (string, int)> { ["content/manifest.json"] = ("trickle", 1) };
+ using (var server = new FlakySite(site, faults))
+ {
+ var started = Time.realtimeSinceStartup;
+ var fetch = GameInputs.FetchAsync(server.BaseUrl, "", 2f).GetAwaiter();
+ yield return Await(fetch);
+ var fetched = fetch.GetResult();
+ Assert.AreEqual(GameInputs.FromDisk(Paths.Content, Paths.StreamingMap).Content.Hash, fetched.Content.Hash);
+ Assert.AreEqual(1, server.Hits("content/manifest.json"), "the slow download was aborted and retried");
+ Assert.Greater(Time.realtimeSinceStartup - started, TrickleChunks * TrickleGapMs / 1000f, "the download was slower than the stall limit");
+ Assert.AreEqual(0, GameInputs.OpenRequests);
+ }
+ }
+ finally { Directory.Delete(site, true); }
+ }
+
+ /// <summary>#911: a server that accepts the request and never answers. Each attempt is aborted after the stall limit
+ /// (1 s here, GameInputs.StallSeconds in the player), retried up to MaxAttempts, and the boot then shows its failure.
+ /// About 8 s (four 1 s stalls and the 0.5, 1 and 2 s backoffs); the 120 s UTF limit only stops a hang.</summary>
+ [UnityTest, Timeout(120_000)]
+ public IEnumerator ARequestThatNeverCompletesRetriesThenRaisesTheVisibleBootFailure()
+ {
+ const float testStallSeconds = 1f;
+ var site = StagedSite();
+ var bootObject = new GameObject("StalledBoot");
+ try
+ {
+ var faults = new Dictionary<string, (string, int)> { ["content/manifest.json"] = ("stall", int.MaxValue) };
+ using (var server = new FlakySite(site, faults))
+ {
+ var boot = bootObject.AddComponent<GameBoot>();
+ string failure = null;
+ boot.Failed += reason => failure = reason;
+ LogAssert.Expect(LogType.Error, new System.Text.RegularExpressions.Regex("BOOT FAIL manifest.json: .* after 4 attempts"));
+ LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("manifest.json: .* after 4 attempts"));
+
+ var started = Time.realtimeSinceStartup;
+ var run = boot.BootAsync(() => GameInputs.FetchAsync(server.BaseUrl, "", testStallSeconds)).GetAwaiter();
+ while (!run.IsCompleted)
+ {
+ UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
+ yield return null;
+ }
+ run.GetResult();
+
+ StringAssert.StartsWith("manifest.json: ", failure);
+ StringAssert.EndsWith($"after {GameInputs.MaxAttempts} attempts", failure);
+ Assert.AreEqual(GameInputs.MaxAttempts, server.Hits("content/manifest.json"));
+ Assert.Less(Time.realtimeSinceStartup - started,
+ GameInputs.MaxAttempts * testStallSeconds + 10f, "boot failure was not visible within the stated retry time");
+ Assert.AreEqual(0, GameInputs.OpenRequests);
+ }
+ }
+ finally
+ {
+ UnityEngine.Object.DestroyImmediate(bootObject);
+ Directory.Delete(site, true);
+ }
+ }
+
/// <summary>Issue #437: StreamingAssets keep fixed names, so a returning browser could pair a new build's code with the
/// previous build's cached content files. Every URL the player fetches carries the build's id; a file path (desktop,
/// the editor) or an empty id is left alone.</summary>