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(boot,tools): a reset connection no longer fails the WebGL boot (BOOT FAIL israel_bonds.yaml under load)

eyalgolan7d3e3825c82c
diff --git a/tools/README.md b/tools/README.md
index 9cc0badf7..b36207895 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -34,7 +34,7 @@ Run from the repo root; this installs every pinned dependency (rasterio included
uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 pytest tools/tests -q
```
-Expected: `143 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
+Expected: `144 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
## Required attribution (Copernicus DEM licence, modified data)
diff --git a/tools/headed.py b/tools/headed.py
index 12c6465ab..133923cfb 100644
--- a/tools/headed.py
+++ b/tools/headed.py
@@ -23,15 +23,12 @@ import argparse
import asyncio
import base64
import statistics
-import functools
-import http.server
import json
import re
import shutil
import subprocess
import sys
import tempfile
-import threading
import time
from pathlib import Path
@@ -122,8 +119,7 @@ class Browser:
async def __aenter__(self):
import websockets # lazy: the normal tools test run does not install it
- self.server = http.server.ThreadingHTTPServer(("127.0.0.1", self.port), functools.partial(web_check.Handler, directory=str(self.build)))
- threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.server = web_check.serve(self.build, self.port)
self.base = f"http://localhost:{self.port}/"
w, h = self.size
flags = browser_flags(self.profile, w, h, self.dpr, self.uncapped, self.keep_awake)
diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.py
index 9c40db997..3b0f9d683 100644
--- a/tools/tests/test_web_check.py
+++ b/tools/tests/test_web_check.py
@@ -3,6 +3,9 @@ import gzip
import http.client
import queue
import re
+import socket
+import threading
+import time
import urllib.request
import web_check as wc
@@ -31,6 +34,44 @@ def test_precompressed_files_get_content_encoding_and_wasm_its_type(tmp_path):
assert urllib.request.urlopen(base + "/index.html").headers["Content-Encoding"] is None
finally:
server.shutdown()
+ server.server_close()
+
+
+def test_a_burst_of_connections_while_the_accept_thread_is_starved_is_served(tmp_path):
+ """The boot fetches every StreamingAssets file at once over HTTP/1.0 (a new connection each), up to 6 at a time per
+ host in Chrome. On a loaded machine the accept thread can lag; macOS answers a connection that overflows the listen
+ backlog with a reset, which the player sees as a failed fetch (BOOT FAIL <file>: Unknown Error). Holding the accept
+ thread while a burst arrives must not lose any connection."""
+ (tmp_path / "a.yaml").write_text("a: 1\n")
+ server = wc.serve(tmp_path)
+ gate, accept = threading.Event(), server.get_request
+ server.get_request = lambda: (gate.wait(10), accept())[1] # the starved accept thread
+ socks, errors = [], {}
+ try:
+ for i in range(16):
+ s = socket.socket()
+ socks.append(s)
+ s.settimeout(10)
+ try:
+ s.connect(("127.0.0.1", server.server_address[1]))
+ s.sendall(b"GET /a.yaml HTTP/1.0\r\nHost: localhost\r\n\r\n")
+ except OSError as e:
+ errors[i] = type(e).__name__
+ time.sleep(0.2)
+ gate.set()
+ statuses = []
+ for i, s in enumerate(socks):
+ try:
+ statuses.append(errors.get(i) or s.recv(64).split(b"\r\n")[0].decode())
+ except OSError as e:
+ statuses.append(type(e).__name__)
+ assert statuses == ["HTTP/1.0 200 OK"] * 16
+ finally:
+ gate.set()
+ for s in socks:
+ s.close()
+ server.shutdown()
+ server.server_close()
FAIL = re.compile(r"GOLDEN FAIL|BOOT FAIL")
diff --git a/tools/web_check.py b/tools/web_check.py
index 42a602346..bb82568e9 100644
--- a/tools/web_check.py
+++ b/tools/web_check.py
@@ -244,8 +244,16 @@ class Page:
self.ready.set()
-def serve(root: Path) -> http.server.ThreadingHTTPServer:
- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Handler, directory=str(root)))
+class Server(http.server.ThreadingHTTPServer):
+ """The static server. socketserver listens with a backlog of 5, and macOS resets a connection that overflows it (no
+ SYN retry). The boot fetches every StreamingAssets file at once, each over a new HTTP/1.0 connection, up to 6 at a
+ time per host in Chrome; on a loaded machine the accept thread lags, a connection is reset and the boot fails
+ (BOOT FAIL <file>: Unknown Error). 128 is macOS's kern.ipc.somaxconn."""
+ request_queue_size = 128
+
+
+def serve(root: Path, port: int = 0) -> Server:
+ server = Server(("127.0.0.1", port), functools.partial(Handler, directory=str(root)))
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index 30691ab73..ea718b962 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -76,21 +76,57 @@ namespace Statecraft.Game.Boot
r.Dispose();
}
- /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice). The caller releases r.</summary>
- static async Awaitable Done(UnityWebRequest r, string name)
+ /// <summary>Attempts per file, the first included. The boot fetches every file at once; one transient failure
+ /// (a reset connection, a busy server) used to fail the whole boot (BOOT FAIL israel_bonds.yaml under load).</summary>
+ internal const int MaxAttempts = 4;
+
+ /// <summary>Seconds to wait before attempt <paramref name="attempt"/> + 1: 0.5, 1, 2.</summary>
+ internal static float Backoff(int attempt) => 0.5f * (1 << (attempt - 1));
+
+ /// <summary>Worth another attempt: no response at all (reset, refused, timed out) or a server-side status (408, 429,
+ /// 5xx). A 404 or any other client error, and a body that failed to decode, fail at once.</summary>
+ internal static bool Transient(UnityWebRequest.Result result, long status) =>
+ 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
+ /// 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)
{
- while (!r.isDone) await Awaitable.NextFrameAsync();
- if (r.result != UnityWebRequest.Result.Success) throw new IOException($"{name}: {r.error} ({r.url})");
+ 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 url = r.url;
+ Release(r);
+ if (!retry) throw new IOException(attempt > 1 ? $"{error} after {attempt} attempts" : error);
+ Debug.LogWarning($"{error}; attempt {attempt + 1} of {MaxAttempts} in {Backoff(attempt):0.#} s");
+ var until = Time.realtimeSinceStartup + Backoff(attempt);
+ while (Time.realtimeSinceStartup < until) await Awaitable.NextFrameAsync();
+ r = Start(url);
+ }
}
static async Awaitable<string> Text(UnityWebRequest r, string name)
{
- try { await Done(r, name); return r.downloadHandler.text; }
+ r = await Done(r, name);
+ try { return r.downloadHandler.text; }
+ finally { Release(r); }
+ }
+
+ static async Awaitable<byte[]> Bytes(UnityWebRequest r, string name)
+ {
+ r = await Done(r, name);
+ try { return r.downloadHandler.data; }
finally { Release(r); }
}
- /// <summary>Fetches the manifest, then starts every download before awaiting any (parallel), then loads. When one
- /// download fails, the others still running are aborted and disposed.</summary>
+ /// <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.</summary>
public static async Awaitable<GameInputs> FetchAsync(string baseUrl)
{
var manifest = ContentManifest.Parse(await Text(Start(baseUrl + "/content/" + ContentManifest.FileName), ContentManifest.FileName));
@@ -102,9 +138,9 @@ namespace Statecraft.Game.Boot
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");
- await Done(r16, "heightmap.r16");
+ var r16Bytes = await Bytes(r16, "heightmap.r16");
DiagLog.BootPhase($"downloaded {texts.Count + 3} files");
- var inputs = FromTexts(texts, manifest, metaText, r16.downloadHandler.data);
+ var inputs = FromTexts(texts, manifest, metaText, r16Bytes);
DiagLog.BootPhase("content parsed and validated");
return inputs;
}
diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.cs
index c566a11f8..71a79b9c3 100644
--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs
+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs
@@ -1,11 +1,18 @@
+using System;
using System.Collections;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading.Tasks;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.Boot;
using Statecraft.Sim;
using UnityEngine;
+using UnityEngine.Networking;
using UnityEngine.TestTools;
public class GameInputsTests
@@ -86,6 +93,179 @@ public class GameInputsTests
Directory.Delete(site, true);
}
+ /// <summary>A minimal HTTP/1.0 server over a staged site (one connection per request, like web_check's) that fails
+ /// chosen files for their first <c>times</c> requests: "drop" resets the connection before any response (what
+ /// macOS did to web_check's server when its listen backlog overflowed on a loaded machine: BOOT FAIL
+ /// israel_bonds.yaml), a number answers with that status. HttpListener cannot model a drop: Mono's Abort() sends an
+ /// empty 200.</summary>
+ sealed class FlakySite : IDisposable
+ {
+ readonly TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
+ readonly string root;
+ readonly Dictionary<string, (string fault, int times)> faults;
+ readonly ConcurrentDictionary<string, int> hits = new ConcurrentDictionary<string, int>();
+ public readonly string BaseUrl;
+
+ public FlakySite(string root, Dictionary<string, (string fault, int times)> faults)
+ {
+ this.root = root; this.faults = faults;
+ listener.Start();
+ BaseUrl = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}";
+ Task.Run(Loop);
+ }
+
+ /// <summary>Requests seen for a site path (e.g. "content/people.yaml").</summary>
+ public int Hits(string rel) => hits.TryGetValue(rel, out var n) ? n : 0;
+
+ async Task Loop()
+ {
+ while (true)
+ {
+ TcpClient client;
+ try { client = await listener.AcceptTcpClientAsync(); }
+ catch (Exception) { return; } // stopped
+ _ = Task.Run(() => Serve(client));
+ }
+ }
+
+ void Serve(TcpClient client)
+ {
+ using (client)
+ {
+ var stream = client.GetStream();
+ var head = new List<byte>();
+ var one = new byte[1];
+ while (head.Count < 4 || head[head.Count - 4] != '\r' || head[head.Count - 3] != '\n' || head[head.Count - 2] != '\r' || head[head.Count - 1] != '\n')
+ {
+ if (stream.Read(one, 0, 1) == 0) return;
+ head.Add(one[0]);
+ }
+ var target = System.Text.Encoding.ASCII.GetString(head.ToArray()).Split(' ')[1];
+ var rel = Uri.UnescapeDataString(target.Split('?')[0].TrimStart('/'));
+ var n = hits.AddOrUpdate(rel, 1, (_, v) => v + 1);
+ 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
+ Respond(stream, int.Parse(f.fault), new byte[0]);
+ return;
+ }
+ var path = Path.Combine(root, rel);
+ if (File.Exists(path)) Respond(stream, 200, File.ReadAllBytes(path));
+ else Respond(stream, 404, new byte[0]);
+ }
+ }
+
+ static void Respond(NetworkStream stream, int status, byte[] body)
+ {
+ var head = System.Text.Encoding.ASCII.GetBytes($"HTTP/1.0 {status} {(status == 200 ? "OK" : "Fault")}\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
+ stream.Write(head, 0, head.Length);
+ stream.Write(body, 0, body.Length);
+ }
+
+ public void Dispose() => listener.Stop();
+ }
+
+ /// <summary>Waits up to 60 s for a fetch. A batch-mode editor runs the player loop (which resumes
+ /// Awaitable.NextFrameAsync) only now and then while idle: a retry's 0.5 s backoff measured 57 s over 2 frames. Each
+ /// tick queues a player-loop update, as a player runs one every frame.</summary>
+ static IEnumerator Await(Awaitable<GameInputs>.Awaiter fetch)
+ {
+ var start = Time.realtimeSinceStartup;
+ while (!fetch.IsCompleted && Time.realtimeSinceStartup - start < 60f)
+ {
+ UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
+ yield return null;
+ }
+ Assert.IsTrue(fetch.IsCompleted, "fetch did not finish within 60 seconds");
+ }
+
+ /// <summary>Fetches the staged site through a FlakySite with these faults and checks the result is the disk's
+ /// content (same hash) with nothing left open; returns the server for its hit counts.</summary>
+ static IEnumerator FetchesTheDiskContentDespite(Dictionary<string, (string, int)> faults, Action<FlakySite> check)
+ {
+ var site = StagedSite();
+ try
+ {
+ using (var server = new FlakySite(site, faults))
+ {
+ var fetch = GameInputs.FetchAsync(server.BaseUrl).GetAwaiter();
+ yield return Await(fetch);
+ var fetched = fetch.GetResult();
+ var disk = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+ Assert.AreEqual(disk.Content.Hash, fetched.Content.Hash);
+ Assert.AreEqual(Simulation.NewGame(disk.Content, 7, Mode.Historical).Hash(), Simulation.NewGame(fetched.Content, 7, Mode.Historical).Hash());
+ CollectionAssert.AreEqual(disk.Map.HeightmapR16, fetched.Map.HeightmapR16);
+ Assert.AreEqual(0, GameInputs.OpenRequests);
+ check(server);
+ }
+ }
+ finally { Directory.Delete(site, true); }
+ }
+
+ [UnityTest]
+ public IEnumerator DroppedConnectionsAreRetried() =>
+ FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/events/israel_bonds.yaml"] = ("drop", 2) },
+ server => Assert.AreEqual(3, server.Hits("content/events/israel_bonds.yaml")));
+
+ [UnityTest]
+ public IEnumerator AServerErrorIsRetried() =>
+ FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/people.yaml"] = ("503", 1), ["map/heightmap.r16"] = ("500", 2) },
+ server =>
+ {
+ Assert.AreEqual(2, server.Hits("content/people.yaml"));
+ Assert.AreEqual(3, server.Hits("map/heightmap.r16"));
+ });
+
+ [UnityTest]
+ public IEnumerator AConnectionThatKeepsDroppingFailsNamingTheFileWithNothingLeftOpen()
+ {
+ var site = StagedSite();
+ try
+ {
+ var faults = new Dictionary<string, (string, int)> { ["content/events/israel_bonds.yaml"] = ("drop", int.MaxValue) };
+ using (var server = new FlakySite(site, faults))
+ {
+ var fetch = GameInputs.FetchAsync(server.BaseUrl).GetAwaiter();
+ yield return Await(fetch);
+ var ex = Assert.Throws<IOException>(() => fetch.GetResult());
+ StringAssert.StartsWith("events/israel_bonds.yaml: ", ex.Message);
+ StringAssert.EndsWith($"after {GameInputs.MaxAttempts} attempts", ex.Message);
+ Assert.AreEqual(GameInputs.MaxAttempts, server.Hits("content/events/israel_bonds.yaml"));
+ Assert.AreEqual(0, GameInputs.OpenRequests, "requests still in flight after a failed fetch were not disposed");
+ }
+ }
+ finally { Directory.Delete(site, true); }
+ }
+
+ [Test]
+ public void OnlyNoResponseAndServerSideStatusesAreRetried()
+ {
+ Assert.IsTrue(GameInputs.Transient(UnityWebRequest.Result.ConnectionError, 0));
+ foreach (var status in new long[] { 500, 502, 503, 504, 408, 429 })
+ Assert.IsTrue(GameInputs.Transient(UnityWebRequest.Result.ProtocolError, status), status.ToString());
+ foreach (var status in new long[] { 400, 403, 404, 410 })
+ Assert.IsFalse(GameInputs.Transient(UnityWebRequest.Result.ProtocolError, status), status.ToString());
+ Assert.IsFalse(GameInputs.Transient(UnityWebRequest.Result.DataProcessingError, 200));
+ Assert.AreEqual(4, GameInputs.MaxAttempts);
+ CollectionAssert.AreEqual(new[] { 0.5f, 1f, 2f }, new[] { GameInputs.Backoff(1), GameInputs.Backoff(2), GameInputs.Backoff(3) });
+ }
+
+ [UnityTest]
+ public IEnumerator ANotFoundFileIsNotRetried()
+ {
+ var site = StagedSite();
+ File.Delete(Path.Combine(site, "content", "people.yaml"));
+ using (var server = new FlakySite(site, new Dictionary<string, (string, int)>()))
+ {
+ var fetch = GameInputs.FetchAsync(server.BaseUrl).GetAwaiter();
+ yield return Await(fetch);
+ StringAssert.StartsWith("people.yaml: ", Assert.Throws<IOException>(() => fetch.GetResult()).Message);
+ Assert.AreEqual(1, server.Hits("content/people.yaml"));
+ Assert.AreEqual(0, GameInputs.OpenRequests);
+ }
+ Directory.Delete(site, true);
+ }
+
[Test]
public void VerifyAcceptsACopyAndRejectsAMissingFileOrManifestMismatch()
{