Carry order as data: per-cache change Sequence, no delivery scheduler

bcae483 made the cache a delivery scheduler (tickets, _deliveryGate turn
waits, per-thread delivery queues). It deadlocked inside CultLib: a load's
delivery reaching a CultNetDatabaseSubscriptionServer observer that needs
_lifecycleGate, while a subscribe's demand handler holding that gate writes
the cache and waits for the delivery's turn.

The cache now owns order as data. Every admitted change takes the next value
of a per-cache in-memory sequence under the gate, published as
CultCacheDocumentChange<T>.Sequence. Delivery is the 544c087/b653f68 rule:
each call publishes its own changes on its own thread after releasing the
gate; nothing waits on another call's delivery. Cross-thread delivery order is
not guaranteed.

Deleted: ticket counter, _delivered, _deliveryGate, Monitor.Wait turns,
per-thread delivery queues, per-ticket catch-all, and the save-order contract
text with its observer-must-not-block rule.

Consumer: a cache-backed CultMesh document handle hands its observed and
reactive mirrors each snapshot's Sequence; ApplyCanonicalSnapshot drops one
not newer than the last applied.

Tests: SequenceIncreasesInAdmissionOrder,
ObserverWritingTheSameCacheDoesNotWaitOnOtherDeliveries,
SubscriptionDemandHandlerWritingCacheDuringDeliveryDoesNotDeadlock,
WatchRecordIgnoresStaleSequence. The last three time out on bcae483.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-13 20:43:11 +02:00
commit 456234018f
8 changed files with 233 additions and 166 deletions

View file

@ -1520,19 +1520,18 @@ namespace GameCult.Mesh
var sourceList = sources?.ToArray()
?? new[] { ProjectionSource(key.Value, descriptor.SchemaId, "CultCache record") };
var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.InProcess, "CultCache document");
return Document<TDocument>(
var feed = LiveFeed<CultMeshDocumentQueryParameters, TDocument>(
ResolveDocumentId(documentId, key),
context,
_ => Task.FromResult(ReadRequired<TDocument>(cache, key)),
_ => cache.WatchRecord<TDocument>(key)
(_parameters, _context) => Task.FromResult(ReadRequired<TDocument>(cache, key)),
(_parameters, _context) => cache.WatchRecord<TDocument>(key)
.Where(change => change.Document != null)
.Select(change => change.Document!),
async value =>
{
await cache.UpsertAsync(value, new CultRecordHandle<TDocument>(key)).ConfigureAwait(false);
},
sourceList,
route);
return new CultMeshDocumentHandle<TDocument>(
BindLiveFeed(context, feed),
async value => await cache.UpsertAsync(value, new CultRecordHandle<TDocument>(key)).ConfigureAwait(false),
() => cache.WatchRecord<TDocument>(key));
}
/// <summary>

View file

@ -927,6 +927,8 @@ namespace GameCult.Mesh
private readonly CultMeshBoundLiveFeed<CultMeshDocumentQueryParameters, TDocument> _feed;
private readonly Func<TDocument, Task>? _replace;
private readonly Func<TDocument, Task>? _submitPrediction;
// Set only over a CultCache record, whose changes carry the cache's Sequence.
private readonly Func<Observable<CultCacheDocumentChange<TDocument>>>? _recordChanges;
/// <summary>Creates a document handle from a Verse-bound live feed.</summary>
public CultMeshDocumentHandle(
@ -939,6 +941,15 @@ namespace GameCult.Mesh
_submitPrediction = submitPrediction;
}
internal CultMeshDocumentHandle(
CultMeshBoundLiveFeed<CultMeshDocumentQueryParameters, TDocument> feed,
Func<TDocument, Task> replace,
Func<Observable<CultCacheDocumentChange<TDocument>>> recordChanges)
: this(feed, replace)
{
_recordChanges = recordChanges;
}
/// <summary>Gets the semantic document id.</summary>
public string DocumentId => _feed.FeedId;
@ -997,6 +1008,13 @@ namespace GameCult.Mesh
return Watch().Subscribe(onNext);
}
// Latest-value mirrors: a cache-backed handle passes each snapshot's Sequence; other sources pass null.
internal IDisposable WatchSequenced(Action<TDocument, long?> onNext) => _recordChanges == null
? Watch(document => onNext(document, null))
: _recordChanges()
.Where(change => change.Document != null)
.Subscribe(change => onNext(change.Document!, change.Sequence));
/// <summary>
/// Projects one typed document field into a stable reactive state pointer. The expression is
/// structural metadata: only member access and constant collection indices are accepted.
@ -1203,6 +1221,7 @@ namespace GameCult.Mesh
private readonly object _gate = new();
private IDisposable? _subscription;
private TDocument _current;
private long _appliedSequence;
private bool _disposed;
internal CultMeshObservedDocument(
@ -1234,7 +1253,7 @@ namespace GameCult.Mesh
internal void Start()
{
_subscription = Document.Watch(ApplyCanonicalSnapshot);
_subscription = Document.WatchSequenced(ApplyCanonicalSnapshot);
}
/// <summary>Reads and adopts a fresh canonical snapshot.</summary>
@ -1264,15 +1283,17 @@ namespace GameCult.Mesh
_subscription?.Dispose();
}
private void ApplyCanonicalSnapshot(TDocument canonical)
private void ApplyCanonicalSnapshot(TDocument canonical, long? sequence)
{
if (canonical == null)
return;
var next = CultMeshDocumentHandle<TDocument>.CloneDocument(canonical);
lock (_gate)
{
if (!_disposed)
_current = next;
if (_disposed || sequence <= _appliedSequence)
return;
_appliedSequence = sequence ?? _appliedSequence;
_current = next;
}
}
@ -1439,6 +1460,7 @@ namespace GameCult.Mesh
private bool _flushQueued;
private bool _flushing;
private bool _disposed;
private long _appliedSequence;
private int _reconciliationVersion;
internal CultMeshReactiveDocument(
@ -1489,7 +1511,7 @@ namespace GameCult.Mesh
internal void Start()
{
_subscription = _document.Watch(ApplyCanonicalSnapshot);
_subscription = _document.WatchSequenced(ApplyCanonicalSnapshot);
}
/// <summary>Mutates the current value and schedules a coalesced prediction or replacement.</summary>
@ -1596,15 +1618,16 @@ namespace GameCult.Mesh
_subscription?.Dispose();
}
private void ApplyCanonicalSnapshot(TDocument canonical)
private void ApplyCanonicalSnapshot(TDocument canonical, long? sequence)
{
if (canonical == null)
return;
lock (_gate)
{
if (_disposed)
if (_disposed || sequence <= _appliedSequence)
return;
_appliedSequence = sequence ?? _appliedSequence;
TDocument? replacement = null;
if (_dirty || _flushing)