Files
EmilandClaude Sonnet 5 cd8f221ddd Fix real bugs from independent review (docs/review-handoff.md)
A second AI session read the whole codebase in parallel (read-only, no
code changes) and left a handoff doc. Addressed the correctness findings:

- PhysicsWorld.Sync's early return compared _bodies.Count to live.Count,
  not their contents — same size, different membership (destroy one
  tracked GameObject, gain one untracked-because-no-collider one; or any
  Restore where the scene has both a Rigidbody+collider object and a
  Rigidbody-without-one) skipped cleanup entirely, leaking the native
  Box3D body forever. Fixed by checking the actual stale set. Two new
  regression tests reproduce the review's own two scenarios via a new
  Lingua_GetBodyCount native export, asserting on the native table's own
  count rather than PhysicsWorld's C#-side bookkeeping.
- TryCreateBody stored handle -1 (native shim refused: invalid world, or
  its 8192-slot body table full) as if it were real — every later
  GetBodyTransform on it silently teleported the GameObject to the
  origin with a degenerate rotation, no error anywhere. Now checked and
  warned once, same as the missing-collider case.
- PluginHost.Load didn't roll back anything when Configure threw partway
  through: Schedule.Add/Events.Subscribe registrations it already made
  stayed forever, and its ALC was never unloaded — neither loaded (no
  _loaded entry) nor cleanly unloadable. Fixed with try/catch: best-effort
  Shutdown (the only thing that knows which services this plugin
  provided), RemoveAllFrom on both Schedule and EventBus, best-effort ALC
  unload, rethrow. New fixture plugin (sandbox.failing-configure, mirrors
  sandbox.echo's own real-load pattern) registers a system against a
  shared Ping component then throws, so FailedConfigureRollbackTests can
  assert the dangling system actually stops firing — an earlier version
  tried to prove this via AssemblyLoadContext.All instead, which passed
  even against the deliberately-reverted buggy code (the ALC turned out
  to get collected either way once its only references went out of
  scope); watching the dangling system is what actually distinguishes
  rolled-back from not, confirmed by deliberately reverting the fix and
  watching this specific test fail before restoring it.
- Engine.Host's "r <id>" left a plugin unloaded on a failed reload with
  no honest indication of that, and retrying threw "not loaded" instead
  of ever reaching Load again. Added PluginHost.IsLoaded so the handler
  only calls Unload when there's something to unload, and the failure
  message now says the plugin is unloaded, not just "failed."
- AssetService.ReloadWithRetry's `when (attempt < 4)` guard meant the
  5th and final IOException fell out of the loop and propagated from a
  discarded fire-and-forget Task — no log, no event, nothing. Now logged.
- EditorState.Selected kept pointing at a GameObject Restore had already
  destroyed after ExitPlay, so Inspector/gizmo would silently keep
  editing something no longer in the world. EditorPlugin.DrawUi now
  compares IsPlaying against its own previous frame (not just reacting to
  the Stop button) so this is caught whether Play was exited via the
  button or the "stop" stdin command — the same stdin-vs-real-control gap
  already hit once earlier this session — and re-resolves the selection
  by name.
- README.md and kernel-contract.md's Event Bus/Time rows had fallen a
  milestone behind (still said "no asset system yet" and "no fixed-step
  accumulator yet" after both shipped).

Full suite: 98 tests.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N1qPfzq8TDCUMFMV3UwV5N
2026-09-02 20:57:08 +03:00

117 lines
4.0 KiB
C#

using System.Collections.Concurrent;
using Engine.Assets.Contracts;
using Engine.Kernel.Diagnostics;
using Engine.Kernel.Events;
namespace Engine.Assets;
internal sealed class AssetService(IEventBus events, ILogger log) : IAssetService, IDisposable
{
private readonly List<FileSystemWatcher> _watchers = [];
private readonly ConcurrentQueue<TextureReloaded> _pendingEvents = new();
private readonly Dictionary<string, DateTime> _lastTriggered = [];
private readonly Lock _debounceLock = new();
public TextureData LoadTexture(string path)
{
var fullPath = Path.GetFullPath(path);
var data = Decode(fullPath);
Watch(fullPath);
return data;
}
/// <summary>
/// Drains reloads decoded on background threads and publishes them on
/// whichever thread calls this — meant to run once per Update stage,
/// which always runs on the frame loop's own thread. A subscriber that
/// reacts to TextureReloaded by touching a GL texture needs that: GL
/// contexts are thread-affine, and FileSystemWatcher.Changed fires on
/// a ThreadPool thread that was never made current for any of them.
/// </summary>
public void PumpReloads()
{
while (_pendingEvents.TryDequeue(out var evt))
{
events.Publish(evt);
log.Info($"reloaded texture '{evt.Path}'");
}
}
private void Watch(string fullPath)
{
var directory = Path.GetDirectoryName(fullPath)!;
var fileName = Path.GetFileName(fullPath);
var watcher = new FileSystemWatcher(directory, fileName)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
};
watcher.Changed += (_, _) => OnChanged(fullPath);
watcher.EnableRaisingEvents = true;
_watchers.Add(watcher);
}
private void OnChanged(string path)
{
// Editors/tools often fire several Changed events for one save
// (truncate + write, or multiple flushes) — a quiet window per
// path collapses those into a single reload instead of several.
lock (_debounceLock)
{
var now = DateTime.UtcNow;
if (_lastTriggered.TryGetValue(path, out var last) && now - last < TimeSpan.FromMilliseconds(200))
return;
_lastTriggered[path] = now;
}
_ = Task.Run(() => ReloadWithRetry(path));
}
private async Task ReloadWithRetry(string path)
{
// The writer may still be flushing when Changed fires — a short
// retry window absorbs that instead of surfacing a transient
// IOException as a real failure.
for (var attempt = 0; attempt < 5; attempt++)
{
try
{
_pendingEvents.Enqueue(new TextureReloaded(path, Decode(path)));
return;
}
catch (IOException) when (attempt < 4)
{
await Task.Delay(50);
}
catch (IOException ex)
{
// The 5th and final attempt — the `when` guard above only
// covers attempts 0-3, so this is the one case that used
// to fall out of the loop and propagate from a
// fire-and-forget Task (`_ = Task.Run(...)`) as an
// unobserved exception: no log, no event, nothing to show
// the reload silently never happened.
log.Warn($"Giving up reloading '{path}' after 5 attempts: {ex.Message}");
}
}
}
private static TextureData Decode(string path)
{
var (width, height, rgba) = PngReader.Read(path);
return new TextureData(width, height, rgba);
}
public void Dispose()
{
// Undisposed FileSystemWatchers would pin this plugin's ALC the
// same way a forgotten Schedule/EventBus registration would —
// each one's Changed handler is a delegate into this assembly.
foreach (var watcher in _watchers)
watcher.Dispose();
_watchers.Clear();
}
}