perf(session): persist entry after releasing the session lock (P5)

This commit is contained in:
sausheong committed 2026-06-13 10:06:43 +08:00
1 parent c710ea5a94
commit 25b2e9163f
2 files changed
+36 -4

No files matched your search

+9 -4
View File
@@ -100,7 +100,6 @@ func NewSession(agentID, key string) *Session {
// Append adds an entry to the session.
func (s *Session) Append(entry SessionEntry) {
s.mu.Lock()
defer s.mu.Unlock()
if entry.ID == "" {
entry.ID = generateID("e")
}
@@ -115,9 +114,15 @@ func (s *Session) Append(entry SessionEntry) {
s.entryMap[entry.ID] = &s.entries[len(s.entries)-1]
s.leafID = entry.ID
// Persist if store is set
if s.store != nil {
s.store.AppendEntry(s, entry)
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)
if store != nil {
store.AppendEntry(s, finalized)
}
}
+27
View File
@@ -350,3 +350,30 @@ func TestSession_ViewReturnsCopy(t *testing.T) {
require.Len(t, v2, 1)
require.Equal(t, "e_1", v2[0].ID, "internal state must not be mutated by caller's slice modification")
}
func TestConcurrentAppendAndViewNoRace(t *testing.T) {
dir := t.TempDir()
store := NewStore(dir)
require.NoError(t, store.Create("a", "k"))
sess := NewSession("a", "k")
sess.SetStore(store)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
sess.Append(SessionEntry{Type: EntryTypeMessage, Role: "user", Data: []byte(`{"text":"x"}`)})
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
_ = sess.View()
}
}()
wg.Wait()
require.Len(t, sess.Entries(), 500)
}