Publish each hold's own changes to its own caller

The cache-wide unpublished list let any thread drain and deliver another
thread's changes: a throwing observer dropped the rest of the queue and threw
into an unrelated writer, writes returned before their change was published,
and a third-party load could wait indefinitely.

Every admission now runs in a hold (Held). The outermost hold on a thread
collects exactly the changes it admits and publishes them after it leaves the
gate, before it returns, on its caller's thread; nested holds append to it.
Every change is delivered even when an observer throws; the first exception
(AggregateException for several) is then rethrown, and a failing body's own
exception wins over observer exceptions.

Stores take the hold instead of locking a shared Gate object, so a direct
PullAll on an attached store publishes its own load and the empty follow-up
Loaded hand-over is gone. Gate is replaced by protected Held.

Tests: OwnChangeIsPublishedBeforeWriteReturns and
ThrowingObserverDoesNotLoseOtherChanges fail on 4eacd87 and pass here. The
repull tests now record a write that reaches the gate while the pull is paused
instead of inferring readiness from thread state; both fail when the pull does
not hold the gate.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-13 19:46:18 +02:00
commit 544c087cf1
4 changed files with 284 additions and 209 deletions

View file

@ -38,13 +38,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
public override string ToString() => _manifestFile.FullName;
public override void PullAll()
{
lock (Gate)
PullAllCore();
// Outside the gate, an empty hand-over lets the cache publish what this pull admitted.
Loaded?.Invoke(Array.Empty<CultStoredDocument>(), Array.Empty<CultStoredDocument>());
}
public override void PullAll() => Held(PullAllCore);
private void PullAllCore()
{
@ -110,31 +104,31 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
public override void Push(CultStoredDocument entry)
{
ThrowIfReadOnly();
lock (Gate)
Held(() =>
{
Entries[entry.Key.Value] = entry;
_dirtyKeys[entry.Key.Value] = true;
_deletedKeys.TryRemove(entry.Key.Value, out _);
IsDirty = true;
}
});
}
public override void Delete(CultStoredDocument entry)
{
ThrowIfReadOnly();
lock (Gate)
Held(() =>
{
Entries.TryRemove(entry.Key.Value, out _);
_dirtyKeys.TryRemove(entry.Key.Value, out _);
_deletedKeys[entry.Key.Value] = true;
IsDirty = true;
}
});
}
public override CultCommitOutcome CommitBatch(CultCommitRequest request, bool wait)
{
ThrowIfReadOnly();
lock (Gate)
return Held(() =>
{
Directory.CreateDirectory(_manifestFile.DirectoryName!);
using var commitLease = AcquireCommitLease(wait);
@ -180,13 +174,13 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
IsDirty = wasDirty;
throw;
}
}
});
}
public override void PushAll()
{
ThrowIfReadOnly();
lock (Gate)
Held(() =>
{
if (!IsDirty)
return;
@ -194,7 +188,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
Directory.CreateDirectory(_manifestFile.DirectoryName!);
using var commitLease = AcquireCommitLease(wait: true);
WriteGeneration(ReadManifest());
}
});
}
// Runs under the commit lease: pages first, then the manifest that names them.

View file

@ -45,9 +45,15 @@ which route wrote it.
- A load publishes changes to `Watch` subscribers and fires `OnUpdate`. A local
write or commit publishes to `Watch` only; `OnUpdate` fires for loads alone.
- Observers and `OnUpdate` run after the cache releases its gate, never under
it: an observer may read or write the cache from any thread. A throwing
observer cannot undo the store's adoption of a load; the store and cache
already agree when publication starts.
it: an observer may read or write the cache from any thread. A change is
published after the cache releases its gate and before the call that made it
returns, on that caller's thread; no call publishes another call's changes. A
direct `PullAll` on an attached store is such a call.
- An observer exception is rethrown to that caller after all of that call's
changes are delivered (an `AggregateException` if several threw). If the call
itself failed, its own exception is rethrown and observer exceptions are
dropped. A throwing observer cannot undo the store's adoption of a load; the
store and cache already agree when publication starts.
- Hydration failure on open is loud: a corrupt store file, or a record whose
schema the registry cannot resolve, makes the open throw and leaves the file
byte-identical. Consumers never delete and rewrite a store they failed to

View file

@ -7,6 +7,7 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
@ -1179,7 +1180,8 @@ namespace GameCult.Caching
private readonly ConditionalWeakTable<object, KeyBox> _handles = new();
private readonly Subject<Change> _changes = new();
private readonly object _gate = new();
private List<(Change Change, bool Loaded)> _unpublished = new();
// The changes admitted by this thread's outermost hold, published by that hold when it exits.
[ThreadStatic] private static List<(CultCache Cache, Change Change, bool Loaded)>? _held;
private bool _dirtyInMemory;
public CultCache(CultDocumentRegistry? registry = null)
@ -1253,76 +1255,59 @@ namespace GameCult.Caching
{
if (store == null) throw new ArgumentNullException(nameof(store));
homes ??= Array.Empty<Type>();
try
Held(() =>
{
lock (_gate)
if (store.Loaded != null)
throw new InvalidOperationException($"Backing store {store} is already attached to a cache.");
if (store.IsDirty)
throw new InvalidOperationException($"Backing store {store} has staged writes; attach it clean.");
if (homes.Length == 0 && _stores.Any(entry => entry.Homes.Length == 0))
throw new InvalidOperationException(
$"Backing store {store} would be a second untyped store; name the types it is home to.");
foreach (var home in homes)
{
if (store.Loaded != null)
throw new InvalidOperationException($"Backing store {store} is already attached to a cache.");
if (store.IsDirty)
throw new InvalidOperationException($"Backing store {store} has staged writes; attach it clean.");
if (homes.Length == 0 && _stores.Any(entry => entry.Homes.Length == 0))
throw new InvalidOperationException(
$"Backing store {store} would be a second untyped store; name the types it is home to.");
foreach (var home in homes)
{
var owner = _stores.FirstOrDefault(entry => entry.Homes.Contains(home)).Store;
if (owner != null)
throw new InvalidOperationException($"{home.FullName} is already routed to {owner}; it cannot also route to {store}.");
}
var candidate = (store, homes);
foreach (var type in _entries.Values.Select(entry => entry.Descriptor).Distinct())
{
var before = Home(type.DocumentType);
_stores.Add(candidate);
var after = Home(type.DocumentType);
_stores.RemoveAt(_stores.Count - 1);
if (before != after)
throw new InvalidOperationException(
$"Attaching {store} would move {type.SchemaName} from {before?.ToString() ?? "memory"} to {after}; " +
"attach routed stores before the untyped store.");
}
store.AttachRegistry(_registry);
store.Gate = _gate;
store.Loaded = (loaded, dropped) => Admit(loaded, dropped, store, _ => CultCommitOutcome.Committed);
_stores.Add(candidate);
try
{
store.PullAll();
}
catch
{
_stores.Remove(candidate);
store.Loaded = null;
store.Gate = new object();
throw;
}
var owner = _stores.FirstOrDefault(entry => entry.Homes.Contains(home)).Store;
if (owner != null)
throw new InvalidOperationException($"{home.FullName} is already routed to {owner}; it cannot also route to {store}.");
}
}
finally
{
Publish();
}
var candidate = (store, homes);
foreach (var type in _entries.Values.Select(entry => entry.Descriptor).Distinct())
{
var before = Home(type.DocumentType);
_stores.Add(candidate);
var after = Home(type.DocumentType);
_stores.RemoveAt(_stores.Count - 1);
if (before != after)
throw new InvalidOperationException(
$"Attaching {store} would move {type.SchemaName} from {before?.ToString() ?? "memory"} to {after}; " +
"attach routed stores before the untyped store.");
}
store.AttachRegistry(_registry);
store.Cache = this;
store.Loaded = (loaded, dropped) => Admit(loaded, dropped, store, _ => CultCommitOutcome.Committed);
_stores.Add(candidate);
try
{
store.PullAll();
}
catch
{
_stores.Remove(candidate);
store.Loaded = null;
store.Cache = null;
throw;
}
return true;
});
}
public Task PullAllBackingStoresAsync()
{
// Our stores take the gate themselves; a third-party store might not, so the cache takes it here.
foreach (var store in BackingStores)
{
try
{
// Our stores take the gate themselves; a third-party store might not, so the cache takes it here.
lock (_gate)
store.PullAll();
}
finally
{
Publish();
}
}
Held(() => { store.PullAll(); return true; });
return Task.CompletedTask;
}
@ -1362,27 +1347,17 @@ namespace GameCult.Caching
return Task.FromResult(Write(document, key));
}
public bool Remove(CultRecordKey key)
public bool Remove(CultRecordKey key) => Held(() =>
{
try
if (!_entries.TryGetValue(key.Value, out var existing))
return false;
Admit(Array.Empty<CultStoredDocument>(), new[] { existing }, null, home =>
{
lock (_gate)
{
if (!_entries.TryGetValue(key.Value, out var existing))
return false;
Admit(Array.Empty<CultStoredDocument>(), new[] { existing }, null, home =>
{
home?.Delete(existing);
return CultCommitOutcome.Committed;
});
return true;
}
}
finally
{
Publish();
}
}
home?.Delete(existing);
return CultCommitOutcome.Committed;
});
return true;
});
public void Remove<T>(CultRecordHandle<T> handle)
{
@ -1514,26 +1489,16 @@ namespace GameCult.Caching
return now.ToString("O", CultureInfo.InvariantCulture);
}
private CultRecordKey Write(object document, CultRecordKey? key)
private CultRecordKey Write(object document, CultRecordKey? key) => Held(() =>
{
try
var stored = CreateStoredDocument(document, key);
Admit(new[] { stored }, Array.Empty<CultStoredDocument>(), null, home =>
{
lock (_gate)
{
var stored = CreateStoredDocument(document, key);
Admit(new[] { stored }, Array.Empty<CultStoredDocument>(), null, home =>
{
home?.Push(stored);
return CultCommitOutcome.Committed;
});
return stored.Key;
}
}
finally
{
Publish();
}
}
home?.Push(stored);
return CultCommitOutcome.Committed;
});
return stored.Key;
});
private CultCommitOutcome Land(Action<CultCacheBatch> stage, bool wait)
{
@ -1549,42 +1514,35 @@ namespace GameCult.Caching
}
// The in-process gate is always entered; only the store lock attempt honors wait, so Contended means another writer holds the store.
try
return Held(() =>
{
lock (_gate)
// Staging stamped outside this gate; a pull since then may hold a later storedAt, so stamp again.
var upserts = batch.Operations.Values
.Where(op => op.Stored != null)
.Select(op => Stamp(op.Key, op.Stored!.Descriptor, op.Stored.Document))
.ToArray();
var deletes = batch.Operations.Values
.Where(op => op.Stored == null && _entries.ContainsKey(op.Key.Value))
.Select(op => _entries[op.Key.Value])
.ToArray();
var request = new CultCommitRequest(upserts, deletes, batch.Expected.ToArray(), batch.ExpectsUnchanged);
return Admit(upserts, deletes, null, home =>
{
// Staging stamped outside this gate; a pull since then may hold a later storedAt, so stamp again.
var upserts = batch.Operations.Values
.Where(op => op.Stored != null)
.Select(op => Stamp(op.Key, op.Stored!.Descriptor, op.Stored.Document))
.ToArray();
var deletes = batch.Operations.Values
.Where(op => op.Stored == null && _entries.ContainsKey(op.Key.Value))
.Select(op => _entries[op.Key.Value])
.ToArray();
var request = new CultCommitRequest(upserts, deletes, batch.Expected.ToArray(), batch.ExpectsUnchanged);
return Admit(upserts, deletes, null, home =>
if (home != null)
{
if (home != null)
{
if (request.HasConditions && home.IsDirty)
throw new InvalidOperationException($"Backing store {home} has staged writes; flush before a conditional commit.");
return home.CommitBatch(request, wait);
}
if (request.HasConditions && home.IsDirty)
throw new InvalidOperationException($"Backing store {home} has staged writes; flush before a conditional commit.");
return home.CommitBatch(request, wait);
}
if (request.HasConditions && _stores.Count > 0)
throw new InvalidOperationException("A conditional batch names its home store through a record it upserts or removes.");
var inMemory = _entries.Values
.Select(entry => new CultPersistedRecord { Key = entry.Key.Value, SchemaId = entry.Descriptor.SchemaId, StoredAt = entry.StoredAt })
.ToArray();
return request.ConditionsHold(inMemory, _entries.Values) ? CultCommitOutcome.Committed : CultCommitOutcome.Mismatch;
});
}
}
finally
{
Publish();
}
if (request.HasConditions && _stores.Count > 0)
throw new InvalidOperationException("A conditional batch names its home store through a record it upserts or removes.");
var inMemory = _entries.Values
.Select(entry => new CultPersistedRecord { Key = entry.Key.Value, SchemaId = entry.Descriptor.SchemaId, StoredAt = entry.StoredAt })
.ToArray();
return request.ConditionsHold(inMemory, _entries.Values) ? CultCommitOutcome.Committed : CultCommitOutcome.Mismatch;
});
});
}
// Every add and remove passes here: single writes, committed batches, and loads (source set).
@ -1593,46 +1551,65 @@ namespace GameCult.Caching
IReadOnlyList<CultStoredDocument> admitted,
IReadOnlyList<CultStoredDocument> evicted,
CacheBackingStore? source,
Func<CacheBackingStore?, CultCommitOutcome> land)
Func<CacheBackingStore?, CultCommitOutcome> land) => Held(() =>
{
var outcome = land(Validate(admitted, evicted, source));
if (outcome != CultCommitOutcome.Committed)
return outcome;
foreach (var change in Apply(admitted, evicted, source))
_held!.Add((this, change, source != null));
return CultCommitOutcome.Committed;
});
// Every admission runs in a hold. A nested hold adds to the outermost one, which publishes exactly its own changes
// after it leaves the gate, before it returns, on its caller's thread: observers never run under the gate.
// Every change is delivered even if an observer throws; then the first observer exception (an AggregateException
// for several) is rethrown. If the body itself threw, its exception wins and observer exceptions are dropped.
internal T Held<T>(Func<T> body)
{
if (Monitor.IsEntered(_gate))
return body();
var outer = _held;
var mine = _held = new List<(CultCache Cache, Change Change, bool Loaded)>();
T result;
try
{
lock (_gate)
{
var outcome = land(Validate(admitted, evicted, source));
if (outcome != CultCommitOutcome.Committed)
return outcome;
foreach (var change in Apply(admitted, evicted, source))
_unpublished.Add((change, source != null));
return CultCommitOutcome.Committed;
}
result = body();
}
finally
catch
{
Publish();
_held = outer;
Deliver(mine);
throw;
}
_held = outer;
var failures = Deliver(mine);
if (failures.Count == 1)
ExceptionDispatchInfo.Capture(failures[0]).Throw();
if (failures.Count > 1)
throw new AggregateException(failures);
return result;
}
// Observers never run under the gate: admitted changes wait until this thread has left its outermost hold.
private void Publish()
private static List<Exception> Deliver(List<(CultCache Cache, Change Change, bool Loaded)> changes)
{
if (Monitor.IsEntered(_gate))
return;
List<(Change Change, bool Loaded)> pending;
lock (_gate)
var failures = new List<Exception>();
void Try(Action observe)
{
if (_unpublished.Count == 0)
return;
pending = _unpublished;
_unpublished = new();
try { observe(); }
catch (Exception exception) { failures.Add(exception); }
}
foreach (var (change, loaded) in pending)
foreach (var (cache, change, loaded) in changes)
{
_changes.OnNext(change);
Try(() => cache._changes.OnNext(change));
if (loaded)
OnUpdate?.Invoke(change.Previous, change.Document);
Try(() => cache.OnUpdate?.Invoke(change.Previous, change.Document));
}
return failures;
}
private CacheBackingStore? Validate(
@ -1875,9 +1852,21 @@ namespace GameCult.Caching
// any of it; if the cache refuses a record the call throws and the store keeps its previous view.
protected internal Action<IReadOnlyList<CultStoredDocument>, IReadOnlyList<CultStoredDocument>>? Loaded;
// Once attached, the cache's gate: the store and its cache share one lock, so a load calling back into the cache
// can never take the gate after the store lock. File locks are always taken inside it.
protected internal object Gate { get; internal set; } = new();
private readonly object _detachedGate = new();
internal CultCache? Cache;
// Once attached, a hold on the cache's gate: the store and its cache share one lock, so a load calling back into
// the cache can never take the gate after the store lock, and a direct call publishes what it loaded when it
// returns. File locks are always taken inside it.
protected T Held<T>(Func<T> body)
{
if (Cache is { } cache)
return cache.Held(body);
lock (_detachedGate)
return body();
}
protected void Held(Action body) => Held(() => { body(); return true; });
internal void AttachRegistry(CultDocumentRegistry registry)
{
@ -1959,13 +1948,7 @@ namespace GameCult.Caching
public override string ToString() => FileInfo.FullName;
public override void PullAll()
{
lock (Gate)
PullAllCore();
// Outside the gate, an empty hand-over lets the cache publish what this pull admitted.
Loaded?.Invoke(Array.Empty<CultStoredDocument>(), Array.Empty<CultStoredDocument>());
}
public override void PullAll() => Held(PullAllCore);
private void PullAllCore()
{
@ -2009,21 +1992,21 @@ namespace GameCult.Caching
public override void Push(CultStoredDocument entry)
{
ThrowIfReadOnly();
lock (Gate)
Held(() =>
{
Entries[entry.Key.Value] = entry;
IsDirty = true;
}
});
}
public override void Delete(CultStoredDocument entry)
{
ThrowIfReadOnly();
lock (Gate)
Held(() =>
{
Entries.TryRemove(entry.Key.Value, out _);
IsDirty = true;
}
});
}
// A plain flush writes this store's whole view under the lock: two writers never interleave bytes, but the last
@ -2031,7 +2014,7 @@ namespace GameCult.Caching
public override void PushAll()
{
ThrowIfReadOnly();
lock (Gate)
Held(() =>
{
using (AcquireLock(wait: true))
{
@ -2041,14 +2024,13 @@ namespace GameCult.Caching
}
MarkFlushSucceeded();
}
});
}
public override CultCommitOutcome CommitBatch(CultCommitRequest request, bool wait)
{
ThrowIfReadOnly();
lock (Gate)
return CommitBatchCore(request, wait);
return Held(() => CommitBatchCore(request, wait));
}
private CultCommitOutcome CommitBatchCore(CultCommitRequest request, bool wait)

View file

@ -1,5 +1,6 @@
#nullable enable
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Threading;
@ -352,10 +353,12 @@ namespace GameCult.Caching.Tests
{
var pulling = Task.Run(() => cache.PullAllBackingStoresAsync());
Assert.That(store.Entered.Wait(TimeSpan.FromSeconds(10)), Is.True, "the pull never read the file");
var writer = StartWriter(() => cache.UpsertAsync(new Counter { Name = "staged" }, new CultRecordHandle<Counter>(staged)), () => store.Pushed.IsSet);
var writing = Task.Run(() => cache.UpsertAsync(new Counter { Name = "staged" }, new CultRecordHandle<Counter>(staged)));
writing.Wait(200);
Assert.That(store.PushedWhilePaused, Is.False, "a write reached the store while the pull held the gate");
store.Pause = null;
release.Set();
Assert.That(pulling.Wait(TimeSpan.FromSeconds(10)) && writer(), Is.True);
Assert.That(Task.WaitAll(new Task[] { pulling, writing }, TimeSpan.FromSeconds(10)), Is.True);
}
finally
{
@ -383,15 +386,19 @@ namespace GameCult.Caching.Tests
using (var release = new ManualResetEventSlim())
{
Slow.Entered.Reset();
Slow.ReadWhilePaused = false;
Slow.Pause = release;
try
{
var pulling = Task.Run(() => cache.PullAllBackingStoresAsync());
Assert.That(Slow.Entered.Wait(TimeSpan.FromSeconds(10)), Is.True, "the pull never loaded a page");
var writer = StartWriter(() => cache.UpsertAsync(new Counter { Name = "staged" }, new CultRecordHandle<Counter>(staged)), () => false);
// Admitting the write indexes its name under the gate, so a write that gets past the gate reads it while paused.
var writing = Task.Run(() => cache.UpsertAsync(new Slow { Name = "staged" }, new CultRecordHandle<Slow>(staged)));
writing.Wait(200);
Assert.That(Slow.ReadWhilePaused, Is.False, "a write was admitted while the pull held the gate");
Slow.Pause = null;
release.Set();
Assert.That(pulling.Wait(TimeSpan.FromSeconds(10)) && writer(), Is.True);
Assert.That(Task.WaitAll(new Task[] { pulling, writing }, TimeSpan.FromSeconds(10)), Is.True);
}
finally
{
@ -496,24 +503,92 @@ namespace GameCult.Caching.Tests
Assert.That(reader.Get(doomed), Is.Null, "a throwing observer left the store holding a record the cache dropped");
}
// Runs write on its own thread and returns once it has reached the store or is blocked waiting; the result joins it.
private static Func<bool> StartWriter(Action write, Func<bool> reachedStore)
[Test]
public void OwnChangeIsPublishedBeforeWriteReturns()
{
Exception? failure = null;
var thread = new Thread(() =>
using var cache = SingleFile(PathOf("own.cc")).Open();
var published = new ConcurrentDictionary<string, int>();
using var subscription = cache.Watch<Counter>().Subscribe(change => published[change.Key.Value] = Environment.CurrentManagedThreadId);
var late = 0;
var writers = Enumerable.Range(0, 4).Select(t => Task.Run(() =>
{
try { write(); }
catch (Exception exception) { failure = exception; }
for (var i = 0; i < 3000; i++)
{
var key = $"{t}:{i}";
cache.UpsertAsync(new Counter { Name = key }, new CultRecordHandle<Counter>(new CultRecordKey(key)));
if (!published.TryGetValue(key, out var thread) || thread != Environment.CurrentManagedThreadId)
Interlocked.Increment(ref late);
}
})).ToArray();
Assert.That(Task.WaitAll(writers, TimeSpan.FromSeconds(60)), Is.True);
Assert.That(late, Is.Zero, "a write returned before its own change was published on its thread");
Assert.That(published.Count, Is.EqualTo(12000));
}
[Test]
public void ThrowingObserverDoesNotLoseOtherChanges()
{
var store = DirectoryStore(PathOf("throwing.cc"));
using var a = store.Open();
using var other = store.Open();
var loads = 0;
var armed = 0;
a.OnUpdate += (_, _) =>
{
Interlocked.Increment(ref loads);
if (Interlocked.Exchange(ref armed, 0) == 1)
throw new InvalidOperationException("observer failed");
};
var published = new ConcurrentDictionary<string, int>();
using var subscription = a.Watch<Counter>().Subscribe(change => published[change.Key.Value] = Environment.CurrentManagedThreadId);
var failed = 0;
var late = 0;
using var stop = new CancellationTokenSource();
var writing = Task.Run(() =>
{
for (var i = 0; !stop.IsCancellationRequested; i++)
{
var key = $"w:{i}";
try
{
a.UpsertAsync(new Counter { Name = key }, new CultRecordHandle<Counter>(new CultRecordKey(key)));
if (!published.TryGetValue(key, out var thread) || thread != Environment.CurrentManagedThreadId)
Interlocked.Increment(ref late);
}
catch (Exception)
{
Interlocked.Increment(ref failed);
}
}
});
thread.Start();
var waited = System.Diagnostics.Stopwatch.StartNew();
while (!reachedStore() && thread.IsAlive && (thread.ThreadState & ThreadState.WaitSleepJoin) == 0)
try
{
Assert.That(waited.Elapsed, Is.LessThan(TimeSpan.FromSeconds(10)), "the write neither reached the store nor blocked");
Thread.Yield();
for (var pull = 0; pull < 50; pull++)
{
var first = new CultRecordKey($"first:{pull}");
var second = new CultRecordKey($"second:{pull}");
Assert.That(other.Commit(batch =>
{
batch.Upsert(new Counter { Name = first.Value }, new CultRecordHandle<Counter>(first));
batch.Upsert(new Counter { Name = second.Value }, new CultRecordHandle<Counter>(second));
}), Is.True);
Interlocked.Exchange(ref armed, 1);
Assert.That(() => a.PullAllBackingStoresAsync(), Throws.InvalidOperationException.With.Message.EqualTo("observer failed"), $"pull {pull}");
Assert.That(loads, Is.EqualTo(2 * (pull + 1)), $"pull {pull} lost a change after its observer threw");
Assert.That(published.ContainsKey(second.Value), Is.True, $"pull {pull} never published its second record");
}
}
finally
{
stop.Cancel();
Assert.That(writing.Wait(TimeSpan.FromSeconds(10)), Is.True);
}
return () => thread.Join(TimeSpan.FromSeconds(10)) && failure == null;
Assert.That(failed, Is.Zero, "an unrelated write threw another call's observer exception");
Assert.That(late, Is.Zero, "an unrelated write returned before its change was published");
}
[Test]
@ -687,12 +762,14 @@ namespace GameCult.Caching.Tests
public ManualResetEventSlim? Pause;
public readonly ManualResetEventSlim Entered = new();
public readonly ManualResetEventSlim Pushed = new();
public volatile bool Paused;
public volatile bool PushedWhilePaused;
public override void Push(CultStoredDocument entry)
{
if (Paused)
PushedWhilePaused = true;
base.Push(entry);
Pushed.Set();
}
protected override CultPersistedStoreSnapshot DeserializeSnapshot(byte[] data)
@ -700,8 +777,10 @@ namespace GameCult.Caching.Tests
var snapshot = base.DeserializeSnapshot(data);
if (Pause is { } pause)
{
Paused = true;
Entered.Set();
pause.Wait();
Paused = false;
}
return snapshot;
@ -753,11 +832,23 @@ namespace GameCult.Caching.Tests
{
internal static volatile ManualResetEventSlim? Pause;
internal static readonly ManualResetEventSlim Entered = new();
internal static volatile bool Paused;
internal static volatile bool ReadWhilePaused;
private bool _blocks;
private string _name = string.Empty;
[Key(0)]
[CultName]
public string Name = string.Empty;
public string Name
{
get
{
if (Paused)
ReadWhilePaused = true;
return _name;
}
set => _name = value;
}
[Key(1)]
public bool Blocks
@ -768,8 +859,10 @@ namespace GameCult.Caching.Tests
_blocks = value;
if (value && Pause is { } pause)
{
Paused = true;
Entered.Set();
pause.Wait();
Paused = false;
}
}
}