acdream/src/AcDream.Content/BoundedDatObjectCache.cs
Erik 7b456b49d6 perf(diag): per-frame history export + checkpoint LOH/cache counters + soak capped mode (2026-07-24 audit review)
An adversarial performance review found our own instruments cannot
measure the project's own performance gates:

- FrameProfiler aggregated CPU/GPU/alloc/stage samples into ~5-second
  windows and reset the ring buffers after each report, so route-wide
  p50/p95/p99 distributions across a whole soak could not be
  reconstructed after the fact. ACDREAM_FRAME_HISTORY=<path> now opts
  into a separate per-frame history (one record per frame, ~72
  bytes/record, accumulated in memory with zero frame-thread I/O) that
  a shutdown-only Dispose() writes as CSV. The aggregated [frame-prof]
  report format and its existing metrics are unchanged.

- The canonical checkpoint JSON tracked cache residency (entry/byte
  counts) but never LOH size/fragmentation, process-wide allocated
  bytes, or cache hit/miss/eviction traffic — a committed audit JSON
  showed 65% LOH fragmentation that no tracked instrument recorded,
  and "does a revisit portal hit or miss the caches" was unanswerable
  from an artifact alone. WorldLifecycleResourceSnapshot now carries
  loh_size_bytes/loh_fragmentation_bytes (GCMemoryInfo.GenerationInfo
  index 3), process_total_allocated_bytes (GC.GetTotalAllocatedBytes),
  and Interlocked hit/miss/eviction counters for the CPU mesh cache,
  decoded-texture cache, and the four bounded DAT-object caches
  (portal/cell/highRes/language, aggregated).

- run-connected-r6-soak.ps1 unconditionally forced
  ACDREAM_UNCAPPED_RENDER=1 with no capped mode, while its sibling
  lifecycle-gate script correctly gated it behind a switch. Added
  -Uncapped (default capped, matching the sibling script's pattern),
  fixed the stationary dwell (12s -> 26s, past the 25s
  LiveEntityLivenessController deadline the adjacent comment already
  cited), and now write an env-disclosure.json into the automation
  artifact directory before every launch listing every ACDREAM_* var
  the script sets plus -Uncapped, since the prior audit could only see
  ACDREAM_DUMP_MOVE_TRUTH and nothing else was ever recorded anywhere.

Cache counters are wired via the existing composition path
(ObjectMeshManager already owns the CPU mesh cache and the mesh
extractor directly; content.Dats is threaded into
WorldLifecycleResourceSnapshotSource the same way every other
composition consumer receives it). The DAT-object cache lives behind
IDatReaderWriter, a third-party interface from the DatReaderWriter
package that cannot be extended; RuntimeDatCollection (the one
production implementation) exposes the aggregate stats directly and a
pattern match reads them, degrading to zero for any test double —
no new static registry was introduced (GpuMemoryTracker remains the
one precedented process-wide static).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(cherry picked from commit 1da2c33c875b41fa383dd79694ee2765f0e21896)
2026-07-24 12:00:30 +02:00

178 lines
6 KiB
C#

using DatReaderWriter.DBObjs;
using DatReaderWriter.Lib.IO;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace AcDream.Content;
/// <summary>
/// Thread-safe LRU for unpacked DAT objects retained by
/// <see cref="DatDatabaseWrapper"/>.
/// </summary>
/// <remarks>
/// The underlying <see cref="DatReaderWriter.DatCollection"/> remains the sole
/// reader and owner of the DAT databases. Entries here are managed object
/// references only; eviction therefore releases the adapter's reference and
/// never disposes or mutates an object.
///
/// DatReaderWriter objects do not expose an exact retained-size contract. The
/// byte budget is consequently conservative accounting rather than a hard
/// managed-heap limit: known raw texture payloads are charged exactly, while
/// other object graphs receive a fixed floor. The independent entry ceiling
/// provides the hard bound even when a generated DAT type grows an unmeasured
/// child graph.
/// </remarks>
internal sealed class BoundedDatObjectCache
{
internal const int DefaultEntryLimit = 256;
internal const long DefaultEstimatedByteLimit = 64L * 1024L * 1024L;
private const long UnknownObjectEstimate = 128L * 1024L;
private readonly record struct CacheKey(Type ObjectType, uint FileId);
private sealed record CacheEntry(
CacheKey Key,
IDBObj Value,
long EstimatedBytes);
private readonly int _entryLimit;
private readonly long _estimatedByteLimit;
private readonly Func<IDBObj, long> _estimateRetainedBytes;
private readonly Dictionary<CacheKey, LinkedListNode<CacheEntry>> _byKey = new();
private readonly LinkedList<CacheEntry> _leastRecentlyUsed = new();
private readonly object _gate = new();
private long _estimatedBytes;
// Hit/miss/eviction traffic counters (2026-07-24 measurement-tooling
// review). Read via Stats without the _gate lock, so plain fields with
// Interlocked increments rather than lock-protected longs.
private long _hits;
private long _misses;
private long _evictions;
/// <summary>Cumulative hit/miss/eviction counts since construction.</summary>
internal CacheStats Stats => new(
Interlocked.Read(ref _hits),
Interlocked.Read(ref _misses),
Interlocked.Read(ref _evictions));
internal BoundedDatObjectCache(
int entryLimit = DefaultEntryLimit,
long estimatedByteLimit = DefaultEstimatedByteLimit,
Func<IDBObj, long>? estimateRetainedBytes = null)
{
ArgumentOutOfRangeException.ThrowIfLessThan(entryLimit, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(estimatedByteLimit, 1);
_entryLimit = entryLimit;
_estimatedByteLimit = estimatedByteLimit;
_estimateRetainedBytes = estimateRetainedBytes ?? EstimateRetainedBytes;
}
internal int Count
{
get
{
lock (_gate)
return _byKey.Count;
}
}
internal long EstimatedBytes
{
get
{
lock (_gate)
return _estimatedBytes;
}
}
internal bool TryGet<T>(uint fileId, [MaybeNullWhen(false)] out T value)
where T : IDBObj
{
lock (_gate)
{
if (!_byKey.TryGetValue(new CacheKey(typeof(T), fileId), out var node))
{
Interlocked.Increment(ref _misses);
value = default;
return false;
}
Interlocked.Increment(ref _hits);
MarkMostRecentlyUsed(node);
value = (T)node.Value.Value;
return true;
}
}
/// <summary>
/// Returns the existing canonical object for a key, or admits
/// <paramref name="candidate"/> and returns it. An object larger than the
/// complete byte budget is served to the caller but is not retained.
/// </summary>
internal T GetOrAdd<T>(uint fileId, T candidate)
where T : IDBObj
{
ArgumentNullException.ThrowIfNull(candidate);
var key = new CacheKey(typeof(T), fileId);
long estimatedBytes = Math.Max(1L, _estimateRetainedBytes(candidate));
lock (_gate)
{
if (_byKey.TryGetValue(key, out var existing))
{
MarkMostRecentlyUsed(existing);
return (T)existing.Value.Value;
}
if (estimatedBytes > _estimatedByteLimit)
return candidate;
while (_byKey.Count >= _entryLimit
|| _estimatedBytes > _estimatedByteLimit - estimatedBytes)
{
EvictLeastRecentlyUsed();
}
var entry = new CacheEntry(key, candidate, estimatedBytes);
var node = _leastRecentlyUsed.AddLast(entry);
_byKey.Add(key, node);
_estimatedBytes += estimatedBytes;
return candidate;
}
}
private void MarkMostRecentlyUsed(LinkedListNode<CacheEntry> node)
{
if (!ReferenceEquals(node, _leastRecentlyUsed.Last))
{
_leastRecentlyUsed.Remove(node);
_leastRecentlyUsed.AddLast(node);
}
}
private void EvictLeastRecentlyUsed()
{
LinkedListNode<CacheEntry>? node = _leastRecentlyUsed.First;
if (node is null)
throw new InvalidOperationException("DAT object cache accounting is inconsistent.");
_leastRecentlyUsed.RemoveFirst();
_byKey.Remove(node.Value.Key);
_estimatedBytes -= node.Value.EstimatedBytes;
Interlocked.Increment(ref _evictions);
}
private static long EstimateRetainedBytes(IDBObj value)
{
// RenderSurface is the dominant byte-bearing object on the mesh path.
// Charge its unpacked source payload exactly, plus the conservative
// floor for the generated object and array overhead.
if (value is RenderSurface renderSurface)
return Math.Max(UnknownObjectEstimate, renderSurface.SourceData.LongLength + 256L);
return UnknownObjectEstimate;
}
}