Decode an edit's Record from the bytes its Document came from

BeginEdit cloned Document eagerly but Record lazily from record.Document,
so a cache change in place before Record's first read made the two copies
come from different states. BeginEdit now serializes the document once and
deserializes Document from those bytes; Record deserializes the same bytes
on first read. Record is the state the edit began from, and costs one
deserialize only when a drawer reads it, with no second serialize.

Each commit still spends the edit, so a slider drag begins an edit per
frame; that serialize was already paid for Document, and Record adds a
deserialize only in frames where a drawer reads it.

The new test mutates the cached document between BeginEdit and the first
Record read; it fails on the lazy clone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-14 21:34:23 +02:00
commit 29bec57021
2 changed files with 16 additions and 2 deletions

View file

@ -252,7 +252,8 @@ namespace GameCult.Caching
public object Document { get; }
// The record being drawn, as stored when this edit began, for drawers that read the document they sit in. It is a
// second copy, made on first read: not the cached object, and not Document, which a lowering commits. Nothing
// second copy, decoded on first read from the bytes Document came from, so a cache change in between cannot split
// them: not the cached object, and not Document, which a lowering commits. Nothing
// reads it back, so writing to it saves nothing and changes neither the edit nor the cache.
public object Record => _record ??= _snapshot();
@ -353,7 +354,8 @@ namespace GameCult.Caching
{
if (record == null) throw new ArgumentNullException(nameof(record));
var type = record.Descriptor.DocumentType;
return new CultInspectorEdit(record, Clone(record.Document, type), () => Clone(record.Document, type));
var snapshot = _serialize(record.Document, type, type);
return new CultInspectorEdit(record, _deserialize(type, snapshot), () => _deserialize(type, snapshot));
}
// Whether CreateDefault makes a value: a string, struct, list or dictionary, or a concrete class with a parameterless constructor.

View file

@ -199,6 +199,18 @@ namespace GameCult.Caching.Tests
Assert.That(none, Does.Contain("cannot serialize"));
}
[Test]
public async Task RecordIsTheStateTheEditBeganFrom()
{
using var cache = new CultCache(Registry);
await cache.UpsertAsync(typeof(InspectItem), new InspectItem { Name = "original" });
var record = cache.AllStoredDocuments.Single();
var edit = Model().BeginEdit(record);
((InspectItem)record.Document).Name = "changed in place before Record was read";
Assert.That(((InspectItem)edit.Record).Name, Is.EqualTo(((InspectItem)edit.Document).Name).And.EqualTo("original"));
}
[Test]
public async Task RefusedCommitLeavesTheCachedDocumentUnchanged()
{