feat(pathfinding): JSONL recorder + public bake helpers (#2449)

## Summary

Adds two pieces of pathfinding tooling on top of PR #2448's lazy `.swb` infrastructure:

- **`PathfindRecorder`** — admin-toggled JSONL telemetry capture; one record per `BitmapAStarAlgorithm.Find` call. Output format matches the BDN harness corpus, so production traffic can be captured and replayed in benchmarks without an adapter.
- **Public bake helpers on `StepCache`** — `ComputeLiveTileDataHash`, `TryReadTileDataHashFromFile`, `BakeMap`, `ClearResidentChunks`. Lets the benchmark project (and any future bake utility) drive cache fill + persist without exposing internal types.

The companion BDN harness update lives in [ModernUO-Benchmarks#kb/pathfinding-pr4-bench](https://github.com/modernuo/ModernUO-Benchmarks/tree/kb/pathfinding-pr4-bench): porting `Benchmarks/PathfindInGame/` from the `kb/ai_pathfinding` branch to the API shipped in #2446–#2448.

## What's in this PR

### `PathfindRecorder` (`PathfindRecorder.cs`)
- Holds a single `StreamWriter` open while recording; its internal buffer absorbs per-record writes without per-call `File.AppendAllText`.
- Single `bool` check on the hot path; cheap when disabled.
- Disabling flushes + disposes; an IO failure during write also disables the recorder.
- Server config:
  - `pathfinding.recorder.enable` — bool, default `false`. Read on boot via `GetOrUpdateSetting`.
  - `pathfinding.recorder.path` — default `<basedir>/Data/Pathfinding/recordings/pathfinds.jsonl`.
- Hooked into `BitmapAStarAlgorithm.Find` — runs once per call, does nothing when disabled.
- Admin command: `[PathRecord [on|off|flush|status]` (default `status`).

### Public cache helpers
- `static ulong StepCache.ComputeLiveTileDataHash()` — wraps the file module's hash function for staleness checks.
- `static bool StepCache.TryReadTileDataHashFromFile(string, out ulong)` — peeks at a `.swb` file's hash field (20 bytes).
- `int StepCache.BakeMap(int, string)` — walks every chunk in the map, populates resident set, saves. Offline / fixture use; blocks for many seconds on a full-map walk.
- `void StepCache.ClearResidentChunks()` — drops chunks + zeros counters but keeps lazy readers open. Lets benchmark loops measure "first query after boot" cost across iterations without the lazy-reader reopen overhead.
This commit is contained in:
Kamron Batman 2026-05-06 13:06:28 -07:00 committed by GitHub
parent 7c9215d97c
commit a8ca82738d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 587 additions and 27 deletions

View file

@ -0,0 +1,163 @@
using System.IO;
using Server.Engines.Pathing;
using Xunit;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class PathfindRecorderTests
{
private static string NewTempPath() =>
Path.Combine(Path.GetTempPath(), $"pathfind-recorder-{System.Guid.NewGuid():N}.jsonl");
/// <summary>
/// Reflection-set the static _outputPath without going through Configure (which
/// reads from server.cfg) so tests don't poison the project's server.cfg.
/// </summary>
private static void OverrideOutputPath(string path)
{
typeof(PathfindRecorder).GetField("_outputPath",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!
.SetValue(null, path);
}
[Fact]
public void Disabled_RecordIfEnabled_DoesNothing()
{
var path = NewTempPath();
OverrideOutputPath(path);
PathfindRecorder.SetEnabled(false);
try
{
var stub = new RecorderStub(World.NewMobile);
stub.DefaultMobileInit();
stub.MoveToWorld(new Point3D(1500, 1600, 0), Map.Maps[1]);
PathfindRecorder.RecordIfEnabled(
stub, Map.Maps[1],
new Point3D(1500, 1600, 0), new Point3D(1498, 1598, 0)
);
stub.Delete();
Assert.False(File.Exists(path), "disabled recorder must not create the output file");
}
finally
{
if (File.Exists(path)) { File.Delete(path); }
}
}
[Fact]
public void Enabled_RecordIfEnabled_WritesValidJsonlLine()
{
var path = NewTempPath();
OverrideOutputPath(path);
PathfindRecorder.SetEnabled(true);
try
{
Assert.True(PathfindRecorder.Enabled);
var stub = new RecorderStub(World.NewMobile);
stub.DefaultMobileInit();
stub.MoveToWorld(new Point3D(1500, 1600, 0), Map.Maps[1]);
PathfindRecorder.RecordIfEnabled(
stub, Map.Maps[1],
new Point3D(1500, 1600, 5), new Point3D(1498, 1598, 5)
);
// Disable to flush + close before reading.
PathfindRecorder.SetEnabled(false);
stub.Delete();
Assert.True(File.Exists(path));
var content = File.ReadAllText(path).TrimEnd();
Assert.Single(content.Split('\n'));
Assert.StartsWith("{\"Name\":\"recorded\"", content);
Assert.Contains("\"MapId\":1", content);
Assert.Contains("\"StartX\":1500", content);
Assert.Contains("\"StartY\":1600", content);
Assert.Contains("\"GoalX\":1498", content);
Assert.Contains("\"GoalY\":1598", content);
Assert.Contains("\"CanSwim\":false", content);
Assert.EndsWith("}", content);
}
finally
{
PathfindRecorder.SetEnabled(false);
if (File.Exists(path)) { File.Delete(path); }
}
}
[Fact]
public void Enabled_RecordsCapabilityFlagsFromBaseCreature()
{
var path = NewTempPath();
OverrideOutputPath(path);
PathfindRecorder.SetEnabled(true);
try
{
var stub = new RecorderStub(World.NewMobile);
stub.DefaultMobileInit();
stub.MoveToWorld(new Point3D(1500, 1600, 0), Map.Maps[1]);
stub.CanSwim = true;
PathfindRecorder.RecordIfEnabled(
stub, Map.Maps[1],
new Point3D(1500, 1600, 0), new Point3D(1498, 1598, 0)
);
PathfindRecorder.SetEnabled(false);
stub.Delete();
var content = File.ReadAllText(path);
Assert.Contains("\"CanSwim\":true", content);
Assert.Contains("\"CanFly\":false", content);
Assert.Contains("\"CanOpenDoors\":", content); // value depends on BaseCreature defaults
Assert.Contains("\"CanMoveOverObstacles\":", content); // — same.
}
finally
{
PathfindRecorder.SetEnabled(false);
if (File.Exists(path)) { File.Delete(path); }
}
}
[Fact]
public void SetEnabled_TogglingTwice_IsIdempotent()
{
var path = NewTempPath();
OverrideOutputPath(path);
try
{
PathfindRecorder.SetEnabled(true);
Assert.True(PathfindRecorder.Enabled);
PathfindRecorder.SetEnabled(true); // second on: no-op, no error
Assert.True(PathfindRecorder.Enabled);
PathfindRecorder.SetEnabled(false);
Assert.False(PathfindRecorder.Enabled);
PathfindRecorder.SetEnabled(false); // second off: no-op
Assert.False(PathfindRecorder.Enabled);
}
finally
{
PathfindRecorder.SetEnabled(false);
if (File.Exists(path)) { File.Delete(path); }
}
}
private sealed class RecorderStub : Server.Mobiles.BaseCreature
{
public RecorderStub(Serial serial) : base(serial)
{
Body = 0xC9;
}
}
}

View file

@ -126,7 +126,7 @@ public class StepCacheFileTests
}
[Fact]
public void TryOpenLazyReader_TileDataHashMismatch_ReturnsFalse()
public void TryOpenLazyReader_FingerprintMismatch_ReturnsFalse()
{
var cache = StepCache.Instance;
cache.Clear();
@ -139,7 +139,7 @@ public class StepCacheFileTests
{
cache.SaveToFile(path, map.MapID);
// Corrupt the TileDataHash field at byte offset 12 (Magic[4] + Version[4] + MapId[4]).
// Corrupt the Fingerprint field at byte offset 12 (Magic[4] + Version[4] + MapId[4]).
var bytes = File.ReadAllBytes(path);
for (var i = 12; i < 20; i++)
{