fix(session): lock-couple writeMu to preserve disk order under concurrent Append (P5)

The earlier P5 change released s.mu before the store write, which let
concurrent appends on one Session reach the disk writer out of in-memory
order. Acquire a dedicated writeMu while still holding s.mu, then release
s.mu before the disk write — disk latency stays off s.mu while on-disk
order still matches append order. Adds a disk-order regression test.
This commit is contained in:
sausheong committed 2026-06-13 10:29:07 +08:00
1 parent e1fd4dc689
commit 34ebfc5e95
2 files changed
+44 -4

No files matched your search

+14 -4
View File
@@ -85,6 +85,12 @@ type Session struct {
entryMap map[string]*SessionEntry
leafID string // current leaf for history traversal
store *Store
// writeMu serializes store writes and preserves their order. Acquired in
// Append while s.mu is still held (lock-coupling), then s.mu is released
// before the disk write — so disk latency stays off s.mu while on-disk
// order still matches in-memory append order under concurrent callers. (P5)
writeMu sync.Mutex
}
// NewSession creates a new empty session.
@@ -116,13 +122,17 @@ func (s *Session) Append(entry SessionEntry) {
finalized := entry // value copy with all fields set
store := s.store
s.mu.Unlock()
// Persist after releasing s.mu so disk latency doesn't block concurrent
// View()/append callers. Store.mu still serializes the file write and
// preserves append ordering (callers reach this point in lock order). (P5)
// Lock-coupling: take writeMu BEFORE releasing s.mu so the disk-write
// order matches the in-memory append order even under concurrent callers,
// then release s.mu so disk latency doesn't block concurrent View()/append.
if store != nil {
s.writeMu.Lock()
s.mu.Unlock()
store.AppendEntry(s, finalized)
s.writeMu.Unlock()
} else {
s.mu.Unlock()
}
}
+30
View File
@@ -377,3 +377,33 @@ func TestConcurrentAppendAndViewNoRace(t *testing.T) {
require.Len(t, sess.Entries(), 500)
}
// TestAppendPreservesDiskOrder verifies that the P5 lock-coupling keeps the
// on-disk JSONL order identical to the in-memory append order: sequential
// appends must persist in order, and reloading from disk must round-trip them
// in the same sequence.
func TestAppendPreservesDiskOrder(t *testing.T) {
dir := t.TempDir()
store := NewStore(dir)
require.NoError(t, store.Create("a", "k"))
sess := NewSession("a", "k")
sess.SetStore(store)
const n = 200
for i := 0; i < n; i++ {
sess.Append(SessionEntry{
Type: EntryTypeMessage,
Role: "user",
Data: json.RawMessage(fmt.Sprintf(`{"text":"%d"}`, i)),
})
}
reloaded, err := store.Load("a", "k")
require.NoError(t, err)
got := reloaded.Entries()
require.Len(t, got, n)
for i := 0; i < n; i++ {
require.JSONEq(t, fmt.Sprintf(`{"text":"%d"}`, i), string(got[i].Data),
"on-disk entry %d out of order", i)
}
}