fix(gateway): stop /compress destroying a message that arrives midway

applyCompress reads the history, computes a summary, then replaces it.
ReplaceMessages removed everything outside the replacement set, so a
chat turn saved in that window was deleted without ever having been
read, let alone summarised. Confirmed on both backends. It is
unrecoverable loss, and it sits outside the write-then-delete guarantee
because the window is in the caller, not the store.

ReplaceMessages now takes the messages the caller is superseding instead
of inferring them from the complement of the replacement. A caller
computes a replacement from a history it read; anything that arrives
afterwards is not part of that, and is now left alone. IDs in both lists
are still kept, so read-modify-write callers are unaffected.

The test fake's ReplaceMessages was a slice assignment, which could not
observe ordering or identity at all -- it now mirrors the real stores.

Refs archie-core-6e0
This commit is contained in:
sam committed 2026-08-04 22:21:15 +10:00
1 parent 44d43ef286
commit 0fd3398cf8
7 files changed
+211 -50

No files matched your search

@@ -0,0 +1,83 @@
package gateway
import (
"context"
"testing"
)
// A chat turn that lands while a compression is being computed is not part of
// what the caller summarised, and must survive it.
//
// applyCompress reads the history, computes a summary, then replaces. The
// replacement used to mean "delete everything that is not in this list", so a
// message saved in that window was deleted without ever being read, let alone
// summarised. That is unrecoverable loss, and it is outside the guarantee the
// failure-safe write-then-delete ordering provides -- the window is in the
// caller, not the store.
func TestCompressKeepsAMessageThatArrivesMidway(t *testing.T) {
for name, newStore := range compressBackends() {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
inner := newStore(t)
store := &midCompressStore{SessionStore: inner}
r := NewRouter(nil, nil, "telegram")
r.InitSessions(store)
r.Identity = "archie"
sessionID, err := r.sessionTracker.resolve(ctx, "telegram", "archie", "chat-1", "")
if err != nil {
t.Fatalf("resolve: %v", err)
}
seedForCompress(t, store, sessionID, 40)
// The inbound turn lands after applyCompress has read the
// history and before it writes the replacement.
const lateText = "sent while the summary was being computed"
store.afterRecent = func() {
if err := inner.SaveMessage(ctx, sessionID, Message{
From: "alice",
Text: lateText,
SourceID: "tg-late",
At: at(dur(9000)),
}); err != nil {
t.Errorf("late SaveMessage: %v", err)
}
}
if _, err := r.applyCompress(ctx, sessionID, DefaultCompressionConfig()); err != nil {
t.Fatalf("applyCompress: %v", err)
}
after, err := inner.RecentMessages(ctx, sessionID, 1000)
if err != nil {
t.Fatalf("RecentMessages: %v", err)
}
for _, m := range after {
if m.Text == lateText {
return
}
}
t.Fatalf("the message that arrived mid-compress was destroyed; history is %d messages",
len(after))
})
}
}
// midCompressStore fires a callback after RecentMessages returns, which is
// the window inside applyCompress between reading the history and replacing
// it.
type midCompressStore struct {
SessionStore
afterRecent func()
}
func (m *midCompressStore) RecentMessages(ctx context.Context, sessionID string, n int) ([]Message, error) {
out, err := m.SessionStore.RecentMessages(ctx, sessionID, n)
if m.afterRecent != nil {
fn := m.afterRecent
m.afterRecent = nil
fn()
}
return out, err
}
+16 -6
View File
@@ -691,12 +691,22 @@ func (r *Router) applyCompress(ctx context.Context, sessionID string, cfg Compre
compressedMsgs := compressedHistory(msgs, view, r.Identity)
// Replace the history with the compressed view in one store-level
// operation. ReplaceMessages writes the replacement before removing
// the originals, so a failure leaves recoverable duplicates instead of
// wiping the session -- the previous delete-then-save order lost the
// entire history if anything went wrong in between.
if err := r.sessionTracker.sessions.ReplaceMessages(ctx, sessionID, compressedMsgs); err != nil {
// Name exactly the messages this compression consumed. A turn that
// arrives between the read above and the write below was never read and
// never summarised, so it must not be swept away with the ones that
// were -- that was unrecoverable loss of a message nobody had seen.
superseded := make([]string, 0, len(msgs))
for _, m := range msgs {
if m.MessageID != "" {
superseded = append(superseded, m.MessageID)
}
}
// ReplaceMessages writes the replacement before removing the originals,
// so a failure leaves recoverable duplicates instead of wiping the
// session -- the previous delete-then-save order lost the entire history
// if anything went wrong in between.
if err := r.sessionTracker.sessions.ReplaceMessages(ctx, sessionID, compressedMsgs, superseded); err != nil {
return "", fmt.Errorf("replace with compressed messages: %w", err)
}
+31 -3
View File
@@ -3,11 +3,12 @@ package gateway
import (
"context"
"fmt"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
)
// fakeSessionStore implements SessionStore for tests. Messages are
@@ -135,10 +136,37 @@ func (f *fakeSessionStore) SaveMessages(_ context.Context, sessionID string, msg
return nil
}
func (f *fakeSessionStore) ReplaceMessages(_ context.Context, sessionID string, msgs []Message) error {
// ReplaceMessages mirrors the real stores: it appends the replacement and
// removes only what the caller named. A plain slice assignment could not
// observe either, which is why the /compress contract went untested here.
func (f *fakeSessionStore) ReplaceMessages(
_ context.Context,
sessionID string,
msgs []Message,
superseded []string,
) error {
f.mu.Lock()
defer f.mu.Unlock()
f.messages[sessionID] = slices.Clone(msgs)
doomed := make(map[string]struct{}, len(superseded))
for _, id := range superseded {
doomed[id] = struct{}{}
}
kept := make([]Message, 0, len(f.messages[sessionID])+len(msgs))
for _, m := range f.messages[sessionID] {
if _, gone := doomed[m.MessageID]; gone {
continue
}
kept = append(kept, m)
}
for _, m := range msgs {
if m.MessageID == "" {
m.MessageID = uuid.NewString()
}
kept = append(kept, m)
}
f.messages[sessionID] = kept
return nil
}
+26 -16
View File
@@ -68,11 +68,20 @@ type MessageHistory interface {
// SaveMessages bulk-saves messages for branch inheritance.
SaveMessages(ctx context.Context, sessionID string, msgs []Message) error
// ReplaceMessages makes msgs the session's entire history. It is the
// /compress primitive. The replacement is written before the previous
// history is removed, so an interrupted call leaves both sets
// present -- recoverable duplicates -- rather than an empty session.
ReplaceMessages(ctx context.Context, sessionID string, msgs []Message) error
// ReplaceMessages writes msgs and removes exactly the messages named by
// superseded. It is the /compress primitive.
//
// The caller names what it is replacing rather than the store inferring
// it from the complement of msgs. A caller computes a replacement from a
// history it read, and a message that arrives in between is not part of
// that: inferring the delete set destroyed such a message without ever
// having read it, which is unrecoverable. Anything in neither list is
// left alone.
//
// The replacement is written before the removal, so an interrupted call
// leaves both sets present -- recoverable duplicates -- rather than an
// empty session. IDs appearing in both msgs and superseded are kept.
ReplaceMessages(ctx context.Context, sessionID string, msgs []Message, superseded []string) error
// SearchMessages returns one page of messages matching the query,
// searching the session's entire history rather than a recent window.
@@ -679,21 +688,22 @@ func (s *nellSessionStore) SaveMessages(ctx context.Context, sessionID string, m
return nil
}
func (s *nellSessionStore) ReplaceMessages(ctx context.Context, sessionID string, msgs []Message) error {
func (s *nellSessionStore) ReplaceMessages(
ctx context.Context,
sessionID string,
msgs []Message,
superseded []string,
) error {
s.mu.Lock()
defer s.mu.Unlock()
db := s.messagesFor(sessionID)
// Snapshot the current history first, so the delete below removes
// exactly what was there when the call started and never touches the
// replacement written after it.
existing, err := db.AllDocs(ctx, sdk.DocRange{IncludeDocs: false})
if err != nil {
return fmt.Errorf("sessionstore: replace messages: list existing: %w", err)
}
doomed := make(map[string]struct{}, len(existing.Rows))
for _, row := range existing.Rows {
doomed[row.ID] = struct{}{}
// Only what the caller named is removed. Deriving this from the store's
// current contents would sweep up messages saved since the caller read
// the history -- messages it never saw and never summarised.
doomed := make(map[string]struct{}, len(superseded))
for _, id := range superseded {
doomed[id] = struct{}{}
}
// Write the replacement before removing anything: an interruption here
+29 -19
View File
@@ -361,16 +361,23 @@ func (s *sqliteSessionStore) SaveMessages(ctx context.Context, sessionID string,
return nil
}
// ReplaceMessages makes msgs the session's entire history, atomically: the
// replacement is written and the previous history removed inside a single
// transaction, so a caller either sees the old history or the new one, never
// an in-between or empty state.
// ReplaceMessages writes msgs and removes exactly the messages named by
// superseded, atomically: both happen inside one transaction, so a caller
// either sees the old history or the new one, never an in-between state.
//
// Only the named messages are removed. Deleting the complement of msgs swept
// up anything saved since the caller read the history -- a chat turn arriving
// mid-compression was destroyed without ever being read.
//
// A replacement message that carries a canonical ID lands on the same row it
// already occupied (saveMessage's immutability no-op), so a read-modify-write
// caller -- ReplaceMessages(sess, history[:2]) -- keeps those rows rather than
// deleting them: they are excluded from the survivor-complement delete below.
func (s *sqliteSessionStore) ReplaceMessages(ctx context.Context, sessionID string, msgs []Message) error {
// already occupied (saveMessage's immutability no-op), so an ID in both lists
// is kept.
func (s *sqliteSessionStore) ReplaceMessages(
ctx context.Context,
sessionID string,
msgs []Message,
superseded []string,
) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -380,26 +387,29 @@ func (s *sqliteSessionStore) ReplaceMessages(ctx context.Context, sessionID stri
}
defer func() { _ = tx.Rollback() }()
survivors := make([]string, 0, len(msgs))
survivors := make(map[string]struct{}, len(msgs))
for _, msg := range msgs {
id, err := saveMessage(ctx, tx, sessionID, msg)
if err != nil {
return fmt.Errorf("sessionstore: replace messages: %w", err)
}
survivors = append(survivors, id)
survivors[id] = struct{}{}
}
query := `DELETE FROM messages WHERE session_id = ?`
args := []any{sessionID}
if len(survivors) > 0 {
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(survivors)), ",")
query += ` AND message_id NOT IN (` + placeholders + `)`
for _, id := range survivors {
args = append(args, id)
doomed := make([]any, 0, len(superseded))
for _, id := range superseded {
if _, kept := survivors[id]; kept {
continue
}
doomed = append(doomed, id)
}
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
return fmt.Errorf("sessionstore: replace messages: delete old: %w", err)
if len(doomed) > 0 {
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(doomed)), ",")
query := `DELETE FROM messages WHERE session_id = ? AND message_id IN (` + placeholders + `)`
args := append([]any{sessionID}, doomed...)
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
return fmt.Errorf("sessionstore: replace messages: delete old: %w", err)
}
}
if err := tx.Commit(); err != nil {
@@ -141,7 +141,7 @@ func TestSQLiteSessionStore_ErrorPaths(t *testing.T) {
}
})
t.Run("ReplaceMessages after close", func(t *testing.T) {
if err := st.ReplaceMessages(ctx, "sess", nil); err == nil {
if err := st.ReplaceMessages(ctx, "sess", nil, nil); err == nil {
t.Error("expected error replacing messages on a closed store")
}
})
@@ -399,7 +399,7 @@ func TestSQLiteSessionStore_ReplaceMessagesAbortRollsBack(t *testing.T) {
installAbortTrigger(t, st, `BEFORE DELETE ON messages WHEN old.message_id = 'm-1'`)
replacement := []Message{{From: "summarizer", Text: "merged summary", At: sqliteBase().Add(time.Hour)}}
if err := st.ReplaceMessages(ctx, "sess-replace-abort", replacement); err == nil {
if err := st.ReplaceMessages(ctx, "sess-replace-abort", replacement, supersededIDs(ctx, t, st, "sess-replace-abort")); err == nil {
t.Fatal("expected ReplaceMessages to fail from the forced abort trigger")
}
@@ -526,7 +526,7 @@ func TestSQLiteSessionStore_FTSStaysCorrectThroughMutations(t *testing.T) {
mutate: func(ctx context.Context, t *testing.T, st SessionStore) error {
return st.ReplaceMessages(ctx, "a", []Message{{
From: "summarizer", Text: "merged needle summary", At: sqliteBase().Add(time.Hour),
}})
}}, supersededIDs(ctx, t, st, "a"))
},
wantA: []string{"merged needle summary"},
wantANeedle: []string{"merged needle summary"},
@@ -42,6 +42,26 @@ func equal(a, b []string) bool {
// runSessionStoreSuite runs every SessionStore behavioural contract against
// a store implementation. newStore must return a fresh, empty store.
// supersededIDs returns the canonical IDs of a session's whole history, for
// tests that mean "replace everything". Production callers name only what
// they actually read; a test that wants a clean sweep has to say so.
func supersededIDs(ctx context.Context, t *testing.T, s SessionStore, sessionID string) []string {
t.Helper()
count, err := s.MessageCount(ctx, sessionID)
if err != nil {
t.Fatalf("MessageCount: %v", err)
}
msgs, err := s.RecentMessages(ctx, sessionID, count)
if err != nil {
t.Fatalf("RecentMessages: %v", err)
}
ids := make([]string, 0, len(msgs))
for _, m := range msgs {
ids = append(ids, m.MessageID)
}
return ids
}
func runSessionStoreSuite(t *testing.T, newStore func(t *testing.T) SessionStore) {
t.Helper()
@@ -797,7 +817,7 @@ func testReplaceMessagesIsFailureSafe(t *testing.T, newStore func(t *testing.T)
for i, text := range tc.replacement {
replacement = append(replacement, msg(text, dur(len(tc.existing)+i)))
}
if err := s.ReplaceMessages(ctx, "sess", replacement); err != nil {
if err := s.ReplaceMessages(ctx, "sess", replacement, supersededIDs(ctx, t, s, "sess")); err != nil {
t.Fatalf("ReplaceMessages: %v", err)
}
@@ -832,7 +852,7 @@ func testReplaceMessagesBeyondScanPageLimit(t *testing.T, newStore func(t *testi
t.Fatalf("SaveMessage: %v", err)
}
}
if err := s.ReplaceMessages(ctx, "sess", []Message{msg("summary", dur(total))}); err != nil {
if err := s.ReplaceMessages(ctx, "sess", []Message{msg("summary", dur(total))}, supersededIDs(ctx, t, s, "sess")); err != nil {
t.Fatalf("ReplaceMessages: %v", err)
}
got, err := s.RecentMessages(ctx, "sess", 100)
@@ -863,7 +883,7 @@ func testReplaceMessagesKeepsSurvivors(t *testing.T, newStore func(t *testing.T)
if err != nil {
t.Fatalf("RecentMessages: %v", err)
}
if err := s.ReplaceMessages(ctx, "sess", history[:2]); err != nil {
if err := s.ReplaceMessages(ctx, "sess", history[:2], supersededIDs(ctx, t, s, "sess")); err != nil {
t.Fatalf("ReplaceMessages: %v", err)
}