diff --git a/Docs/ModChannel.md b/Docs/ModChannel.md index e09879b..74cbcfb 100644 --- a/Docs/ModChannel.md +++ b/Docs/ModChannel.md @@ -138,6 +138,14 @@ and exactly once per operation; a node that restarts begins a new order. Every d `POST /cluster/mod-deliver` and owner lookups to `GET /cluster/mod-locate?entity=` (both channel N9, Docs/Gateway/NodeAPI.md). +## Measuring entity reads and events + +`Test/mod_channel_latency.py RESULTS` starts a World Authority and two regular servers using the configured test host. Run it in an exclusive benchmark slot. Its mod creates eight named battery blocks on one server. It times local property reads, reads from a saved snapshot, and request/reply reads from the other server. The requester exercises `to-owner`, a previously resolved owner with `to-node`, and eight values carried in one reply. It checks every returned name and the unique grid owner. + +For the event measurement the mod subscribes to `IMyFunctionalBlock.EnabledChanged` on the owning server, toggles the first battery and sends the observed value to the second server through `to-node`. The run checks that all 16 local callbacks occur inside the setter and the remote node receives every alternating value in sequence. This relay is fixture code. A mod that wants other nodes to observe an entity event has to arrange delivery and renew its native subscription when the entity moves. + +The report retains individual timestamps plus median, nearest-rank p95 and maximum. One-way intervals use the shared host clock and include game-thread scheduling, transport and serialization. Getter times amortize 16,384 reads per sample. A cached snapshot trades freshness for a local read. + ## Not built From Plan/Modding.md (clustering-plan) v1: the delegate vtable handshake (the object[] protocol above came first diff --git a/Test/ModChannelLatencyFixture/Data/Scripts/ChannelProbe/Probe.cs b/Test/ModChannelLatencyFixture/Data/Scripts/ChannelProbe/Probe.cs new file mode 100644 index 0000000..e56ffd1 --- /dev/null +++ b/Test/ModChannelLatencyFixture/Data/Scripts/ChannelProbe/Probe.cs @@ -0,0 +1,244 @@ +using System; +using Sandbox.Common.ObjectBuilders; +using Sandbox.ModAPI; +using VRage.Game; +using VRage.Game.Components; +using VRage.Game.ModAPI; +using VRage.ObjectBuilders; +using VRage.Utils; +using VRageMath; + +namespace ModChannelLatency +{ + [MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)] + public class Probe : MySessionComponentBase + { + private const long Send = 0x434C55534D4F4453; + private const long Receive = 0x434C55534D4F4452; + private const string Channel = "cluster-latency-fixture"; + private const int Samples = 16; + private readonly IMyFunctionalBlock[] blocks = new IMyFunctionalBlock[8]; + private readonly string[] snapshot = new string[8]; + private int frame, + command, + seq, + events; + private long grid, + started, + setter; + private string mode, + cachedOwner; + private bool toggling, + inSetter; + + public override void LoadData() + { + MyAPIGateway.Utilities.RegisterMessageHandler(Receive, OnMessage); + } + + public override void UpdateAfterSimulation() + { + ++frame; + if (toggling && frame % 11 == 0) + { + inSetter = true; + setter = DateTime.UtcNow.Ticks; + blocks[0].Enabled = !blocks[0].Enabled; + inSetter = false; + if (++events == Samples) + toggling = false; + } + if (frame % 15 != 0) + return; + string file = "step" + command + ".txt"; + if (!MyAPIGateway.Utilities.FileExistsInModLocation(file, ModContext.ModItem)) + return; + string[] step; + using (var r = MyAPIGateway.Utilities.ReadFileInModLocation(file, ModContext.ModItem)) + step = r.ReadToEnd().Trim().Split('|'); + command++; + if (step[0] == "spawn") + Spawn(); + else if (step[0] == "local") + Local(); + else if (step[0] == "events") + toggling = true; + else + { + mode = step[0]; + grid = long.Parse(step[1]); + seq = 0; + if (mode == "resolve") + { + started = DateTime.UtcNow.Ticks; + MyAPIGateway.Utilities.SendModMessage( + Send, + new object[] { "owner-of", Channel, grid, 1L } + ); + } + else + Request(); + } + } + + private void Spawn() + { + var builder = new MyObjectBuilder_CubeGrid + { + GridSizeEnum = MyCubeSize.Large, + IsStatic = true, + DisplayName = "Mod channel latency", + PersistentFlags = MyPersistentEntityFlags2.InScene, + PositionAndOrientation = new MyPositionAndOrientation( + new Vector3D(110, 140, 100), + Vector3.Forward, + Vector3.Up + ), + }; + for (int i = 0; i < 8; i++) + builder.CubeBlocks.Add( + new MyObjectBuilder_BatteryBlock + { + SubtypeName = "LargeBlockBatteryBlock", + Min = new Vector3I(i, 0, 0), + CustomName = new string('x', i + 1), + Enabled = true, + } + ); + var live = (IMyCubeGrid)MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(builder); + for (int i = 0; i < 8; i++) + { + blocks[i] = (IMyFunctionalBlock)live.GetCubeBlock(new Vector3I(i, 0, 0)).FatBlock; + snapshot[i] = blocks[i].CustomName; + } + grid = live.EntityId; + blocks[0].EnabledChanged += EnabledChanged; + Log("spawn|" + grid); + } + + private void Local() + { + for (int s = 0; s < Samples; s++) + { + int sum = 0; + long begin = DateTime.UtcNow.Ticks; + for (int i = 0; i < 16384; i++) + sum += blocks[i % 8].CustomName.Length; + long finish = DateTime.UtcNow.Ticks; + Log("local|" + s + "|" + begin + "|" + finish + "|" + sum); + sum = 0; + begin = DateTime.UtcNow.Ticks; + for (int i = 0; i < 16384; i++) + sum += snapshot[i % 8].Length; + finish = DateTime.UtcNow.Ticks; + Log("snapshot|" + s + "|" + begin + "|" + finish + "|" + sum); + } + } + + private void Request() + { + string payload = "get|" + mode + "|" + seq; + started = DateTime.UtcNow.Ticks; + if (mode == "owner") + MyAPIGateway.Utilities.SendModMessage( + Send, + new object[] { "to-owner", Channel, payload, grid, (long)seq + 1 } + ); + else + ToNode(cachedOwner, payload); + } + + private static void ToNode(string node, string payload) + { + MyAPIGateway.Utilities.SendModMessage( + Send, + new object[] { "to-node", Channel, payload, node } + ); + } + + private void OnMessage(object message) + { + long received = DateTime.UtcNow.Ticks; + var parts = message as object[]; + if (parts == null || parts.Length < 3 || (string)parts[1] != Channel) + return; + string kind = (string)parts[0]; + if (kind == "owner") + { + cachedOwner = (string)parts[3]; + Log("resolved|" + cachedOwner + "|" + started + "|" + received); + return; + } + if (kind == "fault") + Log("fault|" + parts[2]); + if (kind != "to-owner" && kind != "to-node") + return; + string origin = (string)parts[2]; + string[] p = ((string)parts[3]).Split('|'); + if (p[0] == "get") + { + int s = int.Parse(p[2]); + int count = p[1] == "batch" ? 8 : 1; + string[] values = new string[count]; + for (int i = 0; i < count; i++) + values[i] = blocks[(s + i) % 8].CustomName; + string reply = + "reply|" + p[1] + "|" + s + "|" + string.Join(",", values) + "|" + received; + ToNode(origin, reply + "|" + DateTime.UtcNow.Ticks); + } + else if (p[0] == "reply" && p[1] == mode && int.Parse(p[2]) == seq) + { + Log( + mode + + "|" + + seq + + "|" + + started + + "|" + + p[4] + + "|" + + p[5] + + "|" + + received + + "|" + + origin + + "|" + + p[3] + ); + if (++seq < Samples) + Request(); + } + else if (p[0] == "event") + Log((string)parts[3] + "|" + received + "|" + origin); + } + + private void EnabledChanged(IMyTerminalBlock block) + { + long entered = DateTime.UtcNow.Ticks; + if (!toggling) + return; + string payload = + "event|" + + events + + "|" + + ((IMyFunctionalBlock)block).Enabled + + "|" + + setter + + "|" + + entered; + ToNode("node-2", payload + "|" + DateTime.UtcNow.Ticks + "|" + inSetter); + } + + private static void Log(string line) + { + MyLog.Default.WriteLineAndConsole("channel_latency " + line); + } + + protected override void UnloadData() + { + MyAPIGateway.Utilities.UnregisterMessageHandler(Receive, OnMessage); + if (blocks[0] != null) + blocks[0].EnabledChanged -= EnabledChanged; + } + } +} diff --git a/Test/ModChannelLatencyFixture/cluster-mod-compat.txt b/Test/ModChannelLatencyFixture/cluster-mod-compat.txt new file mode 100644 index 0000000..d4999c4 --- /dev/null +++ b/Test/ModChannelLatencyFixture/cluster-mod-compat.txt @@ -0,0 +1 @@ +D everywhere diff --git a/Test/mod_channel_latency.py b/Test/mod_channel_latency.py new file mode 100644 index 0000000..44ceb21 --- /dev/null +++ b/Test/mod_channel_latency.py @@ -0,0 +1,177 @@ +"""Measure a native entity event and explicit mod-channel notifications and reads.""" + +import argparse +import json +import math +import os +import re +import shutil +import statistics +import tempfile +import time +from pathlib import Path + +from bench import Bench, HOST +from cluster import wait_until +from mod_definition_differential import world_with_mods + +PROBE = "9991845011" +SAMPLES = 16 +READS = 16384 +OWNER = "node-1" +SUBSCRIBER = "node-2" + + +def summary(values): + return { + "count": len(values), + "p50_us": statistics.median(values), + "p95_us": sorted(values)[math.ceil(0.95 * len(values)) - 1], + "max_us": max(values), + } + + +def summarize(raw): + metrics = {} + for phase in ("local", "snapshot", "owner", "cached", "batch", "event"): + rows = raw[phase] + if [int(r[1]) for r in rows] != list(range(SAMPLES)): + raise ValueError(f"Missing, duplicate or out-of-order sample in {phase}") + if phase in ("local", "snapshot"): + if any(int(r[4]) != 36 * (READS // 8) for r in rows): + raise ValueError(f"Unexpected sampled property values in {phase}") + metrics[phase] = summary( + [(int(r[3]) - int(r[2])) / (10 * READS) for r in rows] + ) + continue + if phase == "event": + if any( + r[2] != ("True" if i % 2 else "False") + or r[8] != OWNER + or r[6] != "True" + for i, r in enumerate(rows) + ): + raise ValueError("Unexpected event value or sending node") + names = ( + "setter_to_callback", + "callback_to_send", + "send_to_receiver", + "setter_to_receiver", + ) + stamps = [list(map(int, (r[3], r[4], r[5], r[7]))) for r in rows] + else: + for i, r in enumerate(rows): + values = [ + "x" * ((i + j) % 8 + 1) for j in range(8 if phase == "batch" else 1) + ] + if r[6] != OWNER or r[7].split(",") != values: + raise ValueError( + f"{phase} returned the wrong owner or grid properties" + ) + names = ( + "request_to_owner", + "owner_service", + "reply_to_requester", + "round_trip", + ) + stamps = [list(map(int, r[2:6])) for r in rows] + if any(t != sorted(t) for t in stamps): + raise ValueError( + f"{phase} timestamps went backwards; cannot compare host clocks" + ) + metrics[phase] = { + n: summary([(t[b] - t[a]) / 10 for t in stamps]) + for n, (a, b) in zip(names, ((0, 1), (1, 2), (2, 3), (0, 3))) + } + return metrics + + +def run(results): + os.environ["CLUSTER_TEST_PLUGIN"] = "0" + bench = Bench("MOD-CHANNEL-LATENCY", "Mod entity reads and events", "2", results) + cluster = bench.cluster + root = cluster.config.root + report = { + "result": "INCONCLUSIVE", + "package": json.loads((HOST.package / "manifest.json").read_text()), + "clock": "UTC ticks on one host", + "raw": {}, + } + commands = {OWNER: 0, SUBSCRIBER: 0} + + def stage(node): + return root / f"{node}-data/Mods/{PROBE}.sbm" + + def command(node, value): + file = stage(node) / f"step{commands[node]}.txt" + temp = file.with_suffix(".new") + temp.write_text(value) + temp.replace(file) + commands[node] += 1 + + def samples(node, phase): + cluster.wait_node_log(node, rf"channel_latency {phase}\|15\|", 45) + log = max( + (root / f"{node}-data").glob("SpaceEngineersDedicated_*.log"), + key=lambda p: p.stat().st_mtime, + ) + return [ + m.group(1).split("|") + for line in log.read_text(errors="replace").splitlines() + if (m := re.search(rf"channel_latency ({phase}\|.*)$", line)) + ] + + try: + with tempfile.TemporaryDirectory(dir=results) as tmp: + world = Path(tmp) / "world" + world_with_mods(HOST.package / "examples/Cluster-Simple", world, [PROBE]) + cluster.config.world_template = world + cluster.prepare(wipe=True) + for node in ("wa-1", OWNER, SUBSCRIBER): + shutil.copytree( + Path(__file__).parent / "ModChannelLatencyFixture", stage(node) + ) + cluster.start() + cluster.wait_ready(timeout=230, serving=True) + cluster.post("/automatic/pause") + command(OWNER, "spawn") + match = r"channel_latency spawn\|(\d+)" + grid = int(re.search(match, cluster.wait_node_log(OWNER, match, 35))[1]) + + def owned(): + places = bench.entity_owner(bench.diag("entities"), grid) + return places if len(places) == 1 and places[0][0] == OWNER else None + + report["grid"] = grid + report["ownership"] = wait_until(owned, 45, "fixture owned by node-1") + command(OWNER, "local") + for phase in ("local", "snapshot"): + report["raw"][phase] = samples(OWNER, phase) + command(SUBSCRIBER, f"resolve|{grid}") + match = r"channel_latency resolved\|node-1\|(\d+)\|(\d+)" + resolved = re.search(match, cluster.wait_node_log(SUBSCRIBER, match, 30)) + report["owner_lookup_us"] = (int(resolved[2]) - int(resolved[1])) / 10 + for phase in ("owner", "cached", "batch", "event"): + if phase == "event": + command(OWNER, "events") + else: + command(SUBSCRIBER, f"{phase}|{grid}") + report["raw"][phase] = samples(SUBSCRIBER, phase) + if phase != "event": + # Let the real 30-sends/10s channel quota clear between workloads. + time.sleep(10.2) + report["metrics"] = summarize(report["raw"]) + report["result"] = "PASS" + except Exception as error: + report["error"] = str(error) + raise + finally: + bench.record("observations", report) + bench.close() + print(json.dumps({k: v for k, v in report.items() if k != "raw"}, indent=2)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("results", type=Path) + run(parser.parse_args().results)