perf(saves): workers iterate entity dictionaries directly; main thread joins the drain
Removes the per-entity handoff from the freeze entirely. GenericEntityPersistence publishes 4096-slot ranges over its dictionary's backing entries array, and workers serialize occupied slots (value != null) directly via a ShadowEntry<TValue> struct that mirrors the runtime's private Dictionary Entry layout. Safe because the dictionary is frozen during Saving (mutations divert to the pending safety queues). The layout is proven at startup before any code reads through it: validation measures the true Entry stride via precise allocation accounting (so all shadow reads are guaranteed in-bounds), then compares every key and value of a churned, resized, freelist-exercised dictionary reading value slots as raw pointer bits only - never materializing a managed reference until the layout is proven. If a future runtime changes Dictionary internals, validation fails and saves fall back to the enumerate-and-push path with a logged warning. The main thread now joins the drain through an inline (threadless) worker after publishing work, instead of idling while the thread workers finish - worth a full worker share on the freeze and proportionally more on low-core hosts. Measured through the real pipeline classes (24 cores, 10M entities, 1.7GB, dense 2-byte write profile): publish cost drops from ~55ms to ~0.1ms, the freeze is now bound by pure serialize throughput at ~99ms steady state (vs ~740ms before this branch, ~7.5x), and the first save after boot drops from ~468ms to ~139ms because fine-grained ranges self-balance without needing size estimates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
230c39851f
commit
9acd701aaa
6 changed files with 509 additions and 34 deletions
|
|
@ -31,10 +31,20 @@ public interface IGenericEntityPersistence
|
|||
public void DeserializeIndexes(string savePath, Dictionary<ulong, string> typesDb);
|
||||
}
|
||||
|
||||
public class GenericEntityPersistence<T> : GenericPersistence, IGenericEntityPersistence where T : class, ISerializable
|
||||
public class GenericEntityPersistence<T> : GenericPersistence, IGenericEntityPersistence, ISlotRangeSource
|
||||
where T : class, ISerializable
|
||||
{
|
||||
private static readonly ILogger logger = LogFactory.GetLogger(typeof(GenericEntityPersistence<T>));
|
||||
|
||||
// Layout-validated direct access to EntitiesBySerial's entries array, letting workers
|
||||
// iterate the dictionary in parallel during saves. Null when unsupported on this runtime.
|
||||
private static readonly FieldInfo _entriesField =
|
||||
ShadowDictionaryEntries.Supported ? ShadowDictionaryEntries.GetEntriesField<T>() : null;
|
||||
|
||||
// The entries array captured at freeze time. The dictionary cannot mutate while saving
|
||||
// (adds/removes divert to the pending queues), so the array is stable until released.
|
||||
private object _entriesSnapshot;
|
||||
|
||||
// Support legacy split file serialization
|
||||
private static Dictionary<int, List<EntitySpan<T>>> _entities;
|
||||
|
||||
|
|
@ -155,6 +165,15 @@ public class GenericEntityPersistence<T> : GenericPersistence, IGenericEntityPer
|
|||
// Self-payload first so a large one overlaps the entity stream instead of ending it.
|
||||
World.PushSingleToCache(this);
|
||||
|
||||
// Fast path: publish slot ranges of the dictionary's entries array so the workers
|
||||
// iterate it directly in parallel — the main thread never touches the entities.
|
||||
if (TrySnapshotEntries(out var slotCount))
|
||||
{
|
||||
World.PushSlotRangesToCache(this, slotCount);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback: enumerate and hand off every entity from the main thread.
|
||||
foreach (var entity in EntitiesBySerial.Values)
|
||||
{
|
||||
// Previous save's length is the cost estimate; 0 (new entity or first save) takes
|
||||
|
|
@ -171,6 +190,44 @@ public class GenericEntityPersistence<T> : GenericPersistence, IGenericEntityPer
|
|||
}
|
||||
}
|
||||
|
||||
internal bool TrySnapshotEntries(out int slotCount)
|
||||
{
|
||||
if (_entriesField != null && EntitiesBySerial.Count > 0 &&
|
||||
_entriesField.GetValue(EntitiesBySerial) is Array entries)
|
||||
{
|
||||
_entriesSnapshot = entries;
|
||||
slotCount = entries.Length;
|
||||
return true;
|
||||
}
|
||||
|
||||
slotCount = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
int ISlotRangeSource.SerializeRange(BufferWriter writer, byte threadIndex, int offset, int count)
|
||||
{
|
||||
// Layout proven at startup by ShadowDictionaryEntries.Supported; ranges are produced
|
||||
// from the same array's length, so every read is in-bounds.
|
||||
var entries = Unsafe.As<ShadowEntry<T>[]>(_entriesSnapshot);
|
||||
var serialized = 0;
|
||||
|
||||
ref var entry = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(entries), offset);
|
||||
|
||||
for (var i = 0; i < count; i++, entry = ref Unsafe.Add(ref entry, 1))
|
||||
{
|
||||
// Occupied slots are exactly the non-null values: Dictionary clears reference
|
||||
// values on remove, and never-used capacity is zero-initialized.
|
||||
var entity = entry.Value;
|
||||
if (entity != null)
|
||||
{
|
||||
SerializationThreadWorker.Serialize(entity, writer, threadIndex);
|
||||
serialized++;
|
||||
}
|
||||
}
|
||||
|
||||
return serialized;
|
||||
}
|
||||
|
||||
private static ConstructorInfo GetConstructorFor(string typeName, Type t, Type[] constructorTypes)
|
||||
{
|
||||
if (t?.IsAbstract != false)
|
||||
|
|
@ -495,6 +552,8 @@ public class GenericEntityPersistence<T> : GenericPersistence, IGenericEntityPer
|
|||
|
||||
public override void PostWorldSave()
|
||||
{
|
||||
// Release the snapshot so a between-saves resize doesn't pin the old array.
|
||||
_entriesSnapshot = null;
|
||||
ProcessSafetyQueues();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20,6 +20,21 @@ using System.Runtime.InteropServices;
|
|||
|
||||
namespace Server;
|
||||
|
||||
/// <summary>
|
||||
/// A range of backing-store slots that a serialization worker can serialize directly,
|
||||
/// letting workers iterate a persistence's storage in parallel instead of the main thread
|
||||
/// enumerating and handing off every entity. Implemented by
|
||||
/// <see cref="GenericEntityPersistence{T}"/> over its dictionary's entries array.
|
||||
/// </summary>
|
||||
public interface ISlotRangeSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Serializes every occupied slot in [offset, offset + count) into the writer,
|
||||
/// stamping each entity's thread/position/length. Returns the number serialized.
|
||||
/// </summary>
|
||||
int SerializeRange(BufferWriter writer, byte threadIndex, int offset, int count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Single-producer/multi-consumer handoff between the game loop and the serialization
|
||||
/// thread workers during a world save. The producer batches entities into pooled chunks
|
||||
|
|
@ -29,6 +44,8 @@ namespace Server;
|
|||
/// Entities whose previous serialized size exceeds <see cref="HeavyEntityThreshold"/> are
|
||||
/// published as dedicated single-entity chunks so multi-megabyte payloads spread across
|
||||
/// workers instead of riding inside one chunk.
|
||||
/// Persistences that support direct parallel iteration publish slot ranges instead of
|
||||
/// filled chunks, removing the per-entity handoff from the freeze entirely.
|
||||
/// </summary>
|
||||
public sealed class SerializationChunkSource
|
||||
{
|
||||
|
|
@ -47,21 +64,28 @@ public sealed class SerializationChunkSource
|
|||
{
|
||||
public readonly IGenericSerializable Single;
|
||||
public readonly IGenericSerializable[] Buffer;
|
||||
public readonly ISlotRangeSource Source;
|
||||
public readonly int Offset;
|
||||
public readonly int Count;
|
||||
|
||||
public Chunk(IGenericSerializable single)
|
||||
{
|
||||
Single = single;
|
||||
Buffer = null;
|
||||
Count = 1;
|
||||
}
|
||||
|
||||
public Chunk(IGenericSerializable[] buffer, int count)
|
||||
{
|
||||
Single = null;
|
||||
Buffer = buffer;
|
||||
Count = count;
|
||||
}
|
||||
|
||||
public Chunk(ISlotRangeSource source, int offset, int count)
|
||||
{
|
||||
Source = source;
|
||||
Offset = offset;
|
||||
Count = count;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly ConcurrentQueue<Chunk> _chunks = new();
|
||||
|
|
@ -96,6 +120,19 @@ public sealed class SerializationChunkSource
|
|||
/// </summary>
|
||||
public void PushSingle(IGenericSerializable entity) => _chunks.Enqueue(new Chunk(entity));
|
||||
|
||||
/// <summary>
|
||||
/// Publishes slot ranges covering [0, slotCount) of a directly-iterable persistence.
|
||||
/// Workers claim ranges like any other chunk, so the per-entity handoff cost disappears
|
||||
/// and load balancing is unchanged.
|
||||
/// </summary>
|
||||
public void PushSlotRanges(ISlotRangeSource source, int slotCount)
|
||||
{
|
||||
for (var offset = 0; offset < slotCount; offset += ChunkCapacity)
|
||||
{
|
||||
_chunks.Enqueue(new Chunk(source, offset, Math.Min(ChunkCapacity, slotCount - offset)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes the partial chunk, if any. Must be called on the producer thread before
|
||||
/// the workers are told to finish draining, or the tail of the stream is not serialized.
|
||||
|
|
|
|||
|
|
@ -36,16 +36,33 @@ public class SerializationThreadWorker
|
|||
private long _bytesSerialized;
|
||||
|
||||
public SerializationThreadWorker(int index, SerializationChunkSource chunkSource, int heapSizeHint = 0)
|
||||
: this(index, chunkSource, heapSizeHint, inline: false)
|
||||
{
|
||||
}
|
||||
|
||||
private SerializationThreadWorker(int index, SerializationChunkSource chunkSource, int heapSizeHint, bool inline)
|
||||
{
|
||||
_index = index;
|
||||
_chunkSource = chunkSource;
|
||||
_heapSizeHint = heapSizeHint;
|
||||
_startEvent = new AutoResetEvent(false);
|
||||
_stopEvent = new AutoResetEvent(false);
|
||||
_thread = new Thread(Execute);
|
||||
_thread.Start(this);
|
||||
|
||||
if (!inline)
|
||||
{
|
||||
_startEvent = new AutoResetEvent(false);
|
||||
_stopEvent = new AutoResetEvent(false);
|
||||
_thread = new Thread(Execute);
|
||||
_thread.Start(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a worker with no thread of its own. The owner drains chunks inline via
|
||||
/// <see cref="DrainInline"/> — used by the main thread to join the drain instead of
|
||||
/// idling while the thread workers finish.
|
||||
/// </summary>
|
||||
public static SerializationThreadWorker CreateInline(int index, SerializationChunkSource chunkSource, int heapSizeHint = 0) =>
|
||||
new(index, chunkSource, heapSizeHint, inline: true);
|
||||
|
||||
// Stats from the most recent save, for diagnosing load balance.
|
||||
public long EntitiesSerialized => _entitiesSerialized;
|
||||
public long BytesSerialized => _bytesSerialized;
|
||||
|
|
@ -82,7 +99,7 @@ public class SerializationThreadWorker
|
|||
public ReadOnlySpan<byte> GetHeap(int start, int length) => _heap.AsSpan(start, length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void Serialize(IGenericSerializable e, BufferWriter writer, byte threadIndex)
|
||||
internal static void Serialize(IGenericSerializable e, BufferWriter writer, byte threadIndex)
|
||||
{
|
||||
e.SerializedThread = threadIndex;
|
||||
var start = e.SerializedPosition = (int)writer.Position;
|
||||
|
|
@ -90,6 +107,56 @@ public class SerializationThreadWorker
|
|||
e.SerializedLength = (int)(writer.Position - start);
|
||||
}
|
||||
|
||||
private static long ProcessChunk(
|
||||
in SerializationChunkSource.Chunk chunk, SerializationChunkSource chunkSource,
|
||||
BufferWriter writer, byte threadIndex
|
||||
)
|
||||
{
|
||||
if (chunk.Single != null)
|
||||
{
|
||||
Serialize(chunk.Single, writer, threadIndex);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (chunk.Source != null)
|
||||
{
|
||||
return chunk.Source.SerializeRange(writer, threadIndex, chunk.Offset, chunk.Count);
|
||||
}
|
||||
|
||||
var buffer = chunk.Buffer;
|
||||
var count = chunk.Count;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
Serialize(buffer[i], writer, threadIndex);
|
||||
}
|
||||
|
||||
chunkSource.Return(buffer, count);
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drains chunks on the calling thread until the queue is empty, then returns.
|
||||
/// Only valid on inline workers; the main thread calls this after publishing all work
|
||||
/// so it contributes drain throughput instead of idling.
|
||||
/// </summary>
|
||||
public void DrainInline()
|
||||
{
|
||||
var writer = new BufferWriter(_heap, true, World.SerializedTypes);
|
||||
var threadIndex = (byte)_index;
|
||||
var entities = 0L;
|
||||
|
||||
while (_chunkSource.TryTake(out var chunk))
|
||||
{
|
||||
entities += ProcessChunk(in chunk, _chunkSource, writer, threadIndex);
|
||||
}
|
||||
|
||||
_heap = writer.Buffer;
|
||||
_entitiesSerialized = entities;
|
||||
_bytesSerialized = writer.Position;
|
||||
|
||||
writer.Close();
|
||||
}
|
||||
|
||||
private static void Execute(object obj)
|
||||
{
|
||||
var worker = (SerializationThreadWorker)obj;
|
||||
|
|
@ -110,24 +177,7 @@ public class SerializationThreadWorker
|
|||
if (chunkSource.TryTake(out var chunk))
|
||||
{
|
||||
spinner.Reset();
|
||||
|
||||
if (chunk.Single != null)
|
||||
{
|
||||
Serialize(chunk.Single, writer, threadIndex);
|
||||
entities++;
|
||||
}
|
||||
else
|
||||
{
|
||||
var buffer = chunk.Buffer;
|
||||
var count = chunk.Count;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
Serialize(buffer[i], writer, threadIndex);
|
||||
}
|
||||
|
||||
entities += count;
|
||||
chunkSource.Return(buffer, count);
|
||||
}
|
||||
entities += ProcessChunk(in chunk, chunkSource, writer, threadIndex);
|
||||
}
|
||||
else if (pauseRequested) // Break when finished
|
||||
{
|
||||
|
|
|
|||
197
Projects/Server/Serialization/ShadowDictionaryEntries.cs
Normal file
197
Projects/Server/Serialization/ShadowDictionaryEntries.cs
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2026 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: ShadowDictionaryEntries.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using Server.Logging;
|
||||
|
||||
namespace Server;
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors the field layout of <c>Dictionary<Serial, TValue>.Entry</c> so serialization
|
||||
/// workers can scan a dictionary's backing entries array directly, in parallel, without the
|
||||
/// main thread enumerating and handing off every entity.
|
||||
/// The CLR's auto-layout algorithm is deterministic for identical field sequences, so this
|
||||
/// struct lays out identically to the runtime's private Entry struct — and
|
||||
/// <see cref="ShadowDictionaryEntries.Supported"/> proves that empirically at startup before
|
||||
/// any code reads through it. If validation fails on a future runtime, callers fall back to
|
||||
/// the enumerate-and-push path.
|
||||
/// A free or never-used slot always has a null value (Dictionary clears values of
|
||||
/// reference-type TValue on remove to release references), so occupancy is exactly
|
||||
/// <c>Value != null</c>.
|
||||
/// </summary>
|
||||
internal struct ShadowEntry<TValue>
|
||||
{
|
||||
// Field order must mirror S.P.CoreLib Dictionary<TKey,TValue>.Entry: hashCode, next, key, value
|
||||
public uint HashCode;
|
||||
public int Next;
|
||||
public Serial Key;
|
||||
public TValue Value;
|
||||
}
|
||||
|
||||
internal static class ShadowDictionaryEntries
|
||||
{
|
||||
private static readonly ILogger logger = LogFactory.GetLogger(typeof(ShadowDictionaryEntries));
|
||||
|
||||
/// <summary>
|
||||
/// True when this runtime's Dictionary entry layout matches <see cref="ShadowEntry{TValue}"/>,
|
||||
/// proven by validation at startup. All reference-type TValue instantiations share one
|
||||
/// canonical layout, so a single validation covers every entity dictionary.
|
||||
/// </summary>
|
||||
internal static readonly bool Supported = Validate();
|
||||
|
||||
internal static FieldInfo GetEntriesField<TValue>() where TValue : class =>
|
||||
typeof(Dictionary<Serial, TValue>).GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
|
||||
private sealed class ValidationValue
|
||||
{
|
||||
public int Id;
|
||||
}
|
||||
|
||||
private static bool Validate()
|
||||
{
|
||||
try
|
||||
{
|
||||
var field = GetEntriesField<ValidationValue>();
|
||||
if (field == null)
|
||||
{
|
||||
logger.Warning("Dictionary._entries not found; parallel save iteration disabled.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// A compacting GC between snapshotting reference bits and scanning them can only
|
||||
// produce a false negative, so retry a few times before falling back.
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
if (RunValidationPass(field))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
logger.Warning("Dictionary entry layout mismatch; parallel save iteration disabled.");
|
||||
return false;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Warning(e, "Dictionary entry layout validation failed; parallel save iteration disabled.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Measures the true element stride of the runtime's Entry struct by allocating a large
|
||||
/// array of it and reading the precise allocated byte count. Verifying the stride first
|
||||
/// guarantees every subsequent shadow read is in-bounds of the entries array even if the
|
||||
/// field layout were wrong.
|
||||
/// </summary>
|
||||
private static bool StrideMatches(Type entryType)
|
||||
{
|
||||
const int probeLength = 64 * 1024;
|
||||
const int arrayHeaderSize = 24; // 64-bit: sync block + method table + length + padding
|
||||
|
||||
// Warm the reflection/allocation path so the measured delta contains only the probe.
|
||||
Array.CreateInstance(entryType, 1);
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
var probe = Array.CreateInstance(entryType, probeLength);
|
||||
var delta = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
GC.KeepAlive(probe);
|
||||
|
||||
// Alignment slack is < 8 bytes on a 512KB+ allocation, so integer division is exact.
|
||||
var actualStride = (delta - arrayHeaderSize) / probeLength;
|
||||
|
||||
return actualStride == Unsafe.SizeOf<ShadowEntry<ValidationValue>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Proves the layout without ever materializing a managed reference through the shadow
|
||||
/// view: value slots are compared as raw pointer bits (nint). Only after the stride and
|
||||
/// every key and value-pointer of a churned, resized, freelist-exercised dictionary match
|
||||
/// is the layout trusted for typed reads.
|
||||
/// </summary>
|
||||
private static bool RunValidationPass(FieldInfo field)
|
||||
{
|
||||
const int count = 1000;
|
||||
|
||||
var dict = new Dictionary<Serial, ValidationValue>();
|
||||
var rng = new System.Random(0x5EED);
|
||||
var inserted = new List<Serial>(count);
|
||||
|
||||
// Adds with interleaved removes and re-adds: exercises resizes and freelist reuse so
|
||||
// freed slots (which production skips via null values) are present in the array.
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var serial = (Serial)(uint)rng.Next(1, int.MaxValue);
|
||||
if (dict.TryAdd(serial, new ValidationValue { Id = i }))
|
||||
{
|
||||
inserted.Add(serial);
|
||||
}
|
||||
|
||||
if (i % 3 == 2)
|
||||
{
|
||||
var victim = inserted[rng.Next(inserted.Count)];
|
||||
if (dict.Remove(victim))
|
||||
{
|
||||
inserted.Remove(victim);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (field.GetValue(dict) is not Array entriesObj || !StrideMatches(entriesObj.GetType().GetElementType()!))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Snapshot expected key -> value-pointer-bits pairs before scanning, so no allocation
|
||||
// happens between reading the real references and reading the shadow view.
|
||||
var expected = new Dictionary<Serial, nint>(dict.Count);
|
||||
foreach (var (key, value) in dict)
|
||||
{
|
||||
var v = value;
|
||||
expected[key] = Unsafe.As<ValidationValue, nint>(ref v);
|
||||
}
|
||||
|
||||
var entries = Unsafe.As<ShadowEntry<ValidationValue>[]>(entriesObj);
|
||||
var length = entriesObj.Length;
|
||||
var matched = 0;
|
||||
|
||||
ref var entry = ref MemoryMarshal.GetArrayDataReference(entries);
|
||||
|
||||
for (var i = 0; i < length; i++, entry = ref Unsafe.Add(ref entry, 1))
|
||||
{
|
||||
// Read the value slot as pointer bits only — never as a reference — so a wrong
|
||||
// field offset cannot fabricate a managed reference for the GC to trip over.
|
||||
var bits = Unsafe.As<ValidationValue, nint>(ref entry.Value);
|
||||
|
||||
if (bits == 0)
|
||||
{
|
||||
continue; // free or never-used slot
|
||||
}
|
||||
|
||||
if (!expected.TryGetValue(entry.Key, out var expectedBits) || bits != expectedBits)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
matched++;
|
||||
}
|
||||
|
||||
return matched == dict.Count;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue