Skip to content

Commit 309299b

Browse files
authored
fix(chat): prevent stale attachment metadata writes (#1259)
Version attachment cache mutations and reject stale snapshots before the atomic write.
1 parent 4c078f9 commit 309299b

2 files changed

Lines changed: 92 additions & 42 deletions

File tree

‎src/OpenClaw.Tray.WinUI/Chat/ChatMetadataStore.cs‎

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,22 +118,29 @@ internal sealed class CachedAttachmentItem
118118
private readonly object _attachmentSaveGate = new();
119119
private readonly string _toolCacheFilePath;
120120
private readonly string _attachmentCacheFilePath;
121+
private readonly Action<long>? _attachmentSnapshotCaptured;
121122
private Dictionary<string, List<CachedToolMeta>> _toolCache;
122123
private Dictionary<string, List<CachedAttachmentMeta>> _attachmentCache;
123124
private readonly Dictionary<string, long> _evictedResetGenerations = new(StringComparer.Ordinal);
124125
private Timer? _toolSaveTimer;
125126
private long _toolSaveVersion;
127+
private long _attachmentSaveVersion;
126128
private bool _toolCacheDirty;
129+
private bool _attachmentCacheDirty;
127130
private bool _disposed;
128131

129-
internal ChatMetadataStore(string toolCacheFilePath, string? attachmentCacheFilePath = null)
132+
internal ChatMetadataStore(
133+
string toolCacheFilePath,
134+
string? attachmentCacheFilePath = null,
135+
Action<long>? attachmentSnapshotCaptured = null)
130136
{
131137
_toolCacheFilePath = !string.IsNullOrWhiteSpace(toolCacheFilePath)
132138
? toolCacheFilePath
133139
: throw new ArgumentException("Tool metadata cache path is required.", nameof(toolCacheFilePath));
134140
_attachmentCacheFilePath = !string.IsNullOrWhiteSpace(attachmentCacheFilePath)
135141
? attachmentCacheFilePath
136142
: DefaultAttachmentMetaCacheFilePath(_toolCacheFilePath);
143+
_attachmentSnapshotCaptured = attachmentSnapshotCaptured;
137144
_toolCache = LoadToolMetaCache(_toolCacheFilePath);
138145
_attachmentCache = LoadAttachmentMetaCache(_attachmentCacheFilePath);
139146
}
@@ -308,6 +315,7 @@ internal void CacheAttachments(
308315
if (items.Count == 0)
309316
return;
310317

318+
long saveVersion;
311319
lock (_gate)
312320
{
313321
if (_disposed || IsStaleResetGenerationLocked(threadId, resetGeneration))
@@ -332,9 +340,11 @@ internal void CacheAttachments(
332340
});
333341
if (list.Count > MaxAttachmentEntriesPerSession)
334342
list.RemoveRange(0, list.Count - MaxAttachmentEntriesPerSession);
343+
_attachmentCacheDirty = true;
344+
saveVersion = ++_attachmentSaveVersion;
335345
}
336346

337-
SaveAttachmentCache();
347+
SaveAttachmentCache(saveVersion);
338348
}
339349

340350
internal Queue<CachedToolMeta>? GetToolMetadata(
@@ -429,6 +439,7 @@ internal void EvictReset(string threadId, string? oldSessionId, long resetGenera
429439
{
430440
var saveTool = false;
431441
var saveAttachments = false;
442+
long attachmentSaveVersion = 0;
432443
lock (_gate)
433444
{
434445
if (_evictedResetGenerations.TryGetValue(threadId, out var current) &&
@@ -463,12 +474,17 @@ internal void EvictReset(string threadId, string? oldSessionId, long resetGenera
463474
_toolCacheDirty = true;
464475
_toolSaveVersion++;
465476
}
477+
if (saveAttachments)
478+
{
479+
_attachmentCacheDirty = true;
480+
attachmentSaveVersion = ++_attachmentSaveVersion;
481+
}
466482
}
467483

468484
if (saveTool)
469485
SaveToolCache();
470486
if (saveAttachments)
471-
SaveAttachmentCache();
487+
SaveAttachmentCache(attachmentSaveVersion);
472488
}
473489

474490
private bool RemoveOlderToolEntries(
@@ -524,16 +540,18 @@ private bool RemoveOlderAttachmentEntries(
524540
internal void Flush()
525541
{
526542
Timer? timer;
543+
long attachmentSaveVersion;
527544
lock (_gate)
528545
{
529546
timer = _toolSaveTimer;
530547
_toolSaveTimer = null;
531548
_toolSaveVersion++;
549+
attachmentSaveVersion = _attachmentSaveVersion;
532550
}
533551

534552
timer?.Dispose();
535553
SaveToolCache();
536-
SaveAttachmentCache();
554+
SaveAttachmentCache(attachmentSaveVersion);
537555
}
538556

539557
public void Dispose()
@@ -605,24 +623,42 @@ private void SaveToolCache(long? expectedVersion = null)
605623
}
606624
}
607625

608-
private void SaveAttachmentCache()
626+
private void SaveAttachmentCache(long expectedVersion)
609627
{
610628
try
611629
{
612630
Dictionary<string, List<CachedAttachmentMeta>> snapshot;
613631
lock (_gate)
614632
{
633+
if (expectedVersion != _attachmentSaveVersion ||
634+
!_attachmentCacheDirty)
635+
{
636+
return;
637+
}
638+
615639
snapshot = _attachmentCache.ToDictionary(
616640
pair => pair.Key,
617641
pair => pair.Value.Select(Clone).ToList(),
618642
StringComparer.Ordinal);
619643
}
620644

645+
_attachmentSnapshotCaptured?.Invoke(expectedVersion);
621646
EvictOldestSessions(snapshot);
622647
var json = JsonSerializer.Serialize(snapshot, CacheJsonOptions);
623648
lock (_attachmentSaveGate)
624649
{
650+
lock (_gate)
651+
{
652+
if (expectedVersion != _attachmentSaveVersion)
653+
return;
654+
}
655+
625656
AtomicWrite(_attachmentCacheFilePath, json, "attachment metadata");
657+
lock (_gate)
658+
{
659+
if (expectedVersion == _attachmentSaveVersion)
660+
_attachmentCacheDirty = false;
661+
}
626662
}
627663
}
628664
catch (Exception ex)

‎tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs‎

Lines changed: 51 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -11668,50 +11668,64 @@ await provider1.SendMessageAsync("main", "Check this", default,
1166811668
[Fact]
1166911669
public async Task AttachmentMetadata_ConcurrentSavesPreserveEveryCompletedSend()
1167011670
{
11671-
const int sendCount = 16;
1167211671
using var tempDir = new TempDirectory();
11672+
var toolPath = Path.Combine(tempDir.DirectoryPath, "tool-metadata.json");
1167311673
var attachmentPath = Path.Combine(tempDir.DirectoryPath, "attachment-metadata.json");
11674-
var sessions = Enumerable.Range(0, sendCount)
11675-
.Select(index => new SessionInfo
11674+
var firstSnapshotCaptured = new TaskCompletionSource(
11675+
TaskCreationOptions.RunContinuationsAsynchronously);
11676+
using var releaseFirstSnapshot = new ManualResetEventSlim();
11677+
using var store = new ChatMetadataStore(
11678+
toolPath,
11679+
attachmentPath,
11680+
version =>
1167611681
{
11677-
Key = $"thread-{index}",
11678-
DisplayName = $"Thread {index}",
11679-
Status = "active",
11680-
IsMain = index == 0,
11681-
})
11682-
.ToArray();
11683-
var (bridge, provider, _, _) = CreateProvider(
11684-
sessions,
11685-
attachmentMetaCachePath: attachmentPath);
11686-
await provider.LoadAsync();
11682+
if (version != 1)
11683+
return;
1168711684

11688-
var allStarted = new CountdownEvent(sendCount);
11689-
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
11690-
bridge.SendBehavior = async (_, _, _) =>
11685+
firstSnapshotCaptured.SetResult();
11686+
releaseFirstSnapshot.Wait();
11687+
});
11688+
11689+
static ChatAttachment Attachment(string fileName) => new()
1169111690
{
11692-
allStarted.Signal();
11693-
await release.Task;
11691+
Type = "image",
11692+
MimeType = "image/png",
11693+
FileName = fileName,
11694+
Content = Convert.ToBase64String([1]),
11695+
SizeBytes = 1,
1169411696
};
1169511697

11696-
var sends = sessions.Select((session, index) =>
11697-
provider.SendMessageAsync(session.Key, $"caption-{index}", default,
11698-
[
11699-
new ChatAttachment
11700-
{
11701-
Type = "image",
11702-
MimeType = "image/png",
11703-
FileName = $"file-{index}.png",
11704-
Content = Convert.ToBase64String([(byte)index]),
11705-
SizeBytes = 1,
11706-
},
11707-
])).ToArray();
11708-
Assert.True(allStarted.Wait(TimeSpan.FromSeconds(5)));
11709-
release.SetResult();
11710-
await Task.WhenAll(sends);
11711-
11712-
var persisted = await File.ReadAllTextAsync(attachmentPath);
11713-
for (var index = 0; index < sendCount; index++)
11714-
Assert.Contains($"file-{index}.png", persisted, StringComparison.Ordinal);
11698+
var firstSave = Task.Run(() =>
11699+
store.CacheAttachments(
11700+
"thread-1",
11701+
"session-1",
11702+
0,
11703+
"first",
11704+
[Attachment("first.png")],
11705+
1_000));
11706+
try
11707+
{
11708+
await firstSnapshotCaptured.Task.WaitAsync(TimeSpan.FromSeconds(5));
11709+
store.CacheAttachments(
11710+
"thread-2",
11711+
"session-2",
11712+
0,
11713+
"second",
11714+
[Attachment("second.png")],
11715+
2_000);
11716+
}
11717+
finally
11718+
{
11719+
releaseFirstSnapshot.Set();
11720+
}
11721+
11722+
await firstSave;
11723+
11724+
var cache = JsonSerializer.Deserialize<
11725+
Dictionary<string, List<ChatMetadataStore.CachedAttachmentMeta>>>(
11726+
await File.ReadAllTextAsync(attachmentPath));
11727+
Assert.Equal("first.png", Assert.Single(cache!["session-1"]).Attachments[0].FileName);
11728+
Assert.Equal("second.png", Assert.Single(cache["session-2"]).Attachments[0].FileName);
1171511729
}
1171611730

1171711731
[Fact]

0 commit comments

Comments
 (0)