diff --git a/internal/gateway/session_commands.go b/internal/gateway/session_commands.go index c0310a4dd..586bb7981 100644 --- a/internal/gateway/session_commands.go +++ b/internal/gateway/session_commands.go @@ -52,10 +52,25 @@ func (t *sessionTracker) resolve(ctx context.Context, platform, botUser, channel } // Find the most recent session matching this thread and bot. - for _, s := range sessions { - if s.Source.BotUser == botUser && s.Source.ThreadID == threadID { - return t.cacheActive(key, s.SessionID), nil + // + // Pick by LastActiveAt rather than trusting the store's order. This used + // to take the first match, which on the NellDB store is document order -- + // i.e. by session ID, effectively arbitrary -- so a restart, which always + // re-resolves because the cache is in-memory, could drop the operator + // back into a session they had left with /new. The two backends also + // order GetByChannel differently, and this makes the caller independent + // of that. + var best *SessionContext + for i, s := range sessions { + if s.Source.BotUser != botUser || s.Source.ThreadID != threadID { + continue } + if best == nil || sessionRecency(s).After(sessionRecency(*best)) { + best = &sessions[i] + } + } + if best != nil { + return t.cacheActive(key, best.SessionID), nil } // Create a new session with a deterministic key so it matches the diff --git a/internal/gateway/session_resolve_test.go b/internal/gateway/session_resolve_test.go new file mode 100644 index 000000000..9d61bf9ad --- /dev/null +++ b/internal/gateway/session_resolve_test.go @@ -0,0 +1,195 @@ +package gateway + +import ( + "context" + "testing" + "time" +) + +// resolve claims to find "the most recent session matching this thread and +// bot" but took whichever session the store happened to return first. The +// tracker cache is in-memory, so every daemon restart re-resolves from the +// store -- and dropped the operator back into an arbitrary older session, +// answering against pre-/new history. LastActiveAt was populated on every +// record and never consulted. +func TestResolvePicksTheMostRecentSession(t *testing.T) { + // Session IDs are chosen so that ordering by ID disagrees with ordering + // by recency: a store that returns document order hands back "aaa" or + // "zzz" first depending on direction, and neither is the answer. + tests := []struct { + name string + sessions []struct { + id string + active time.Duration + } + want string + }{ + { + name: "newest sorts last by id", + sessions: []struct { + id string + active time.Duration + }{ + {"aaa-old", 0}, + {"zzz-new", time.Hour}, + }, + want: "zzz-new", + }, + { + name: "newest sorts first by id", + sessions: []struct { + id string + active time.Duration + }{ + {"zzz-old", 0}, + {"aaa-new", time.Hour}, + }, + want: "aaa-new", + }, + { + name: "newest is in the middle", + sessions: []struct { + id string + active time.Duration + }{ + {"aaa", 0}, + {"mmm", 2 * time.Hour}, + {"zzz", time.Hour}, + }, + want: "mmm", + }, + } + + for name, newStore := range compressBackends() { + t.Run(name, func(t *testing.T) { + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + store := newStore(t) + + for _, s := range tc.sessions { + if err := store.Save(ctx, SessionContext{ + SessionID: s.id, + Source: SessionSource{ + Platform: "telegram", + BotUser: "archie", + ChannelID: "chat-1", + }, + CreatedAt: base.Add(s.active), + LastActiveAt: base.Add(s.active), + }); err != nil { + t.Fatalf("Save %s: %v", s.id, err) + } + } + + // A cold tracker, as after a restart. + tr := newSessionTracker(store) + got, err := tr.resolve(ctx, "telegram", "archie", "chat-1", "") + if err != nil { + t.Fatalf("resolve: %v", err) + } + if got != tc.want { + t.Errorf("resolve = %q, want the most recently active %q", got, tc.want) + } + }) + } + }) + } +} + +// Matching is still scoped to the bot and thread: a more recent session +// belonging to another identity or another thread must not be picked up. +func TestResolveIgnoresOtherBotsAndThreads(t *testing.T) { + for name, newStore := range compressBackends() { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + store := newStore(t) + + save := func(id, botUser, threadID string, offset time.Duration) { + t.Helper() + if err := store.Save(ctx, SessionContext{ + SessionID: id, + Source: SessionSource{ + Platform: "telegram", + BotUser: botUser, + ChannelID: "chat-1", + ThreadID: threadID, + }, + CreatedAt: base.Add(offset), + LastActiveAt: base.Add(offset), + }); err != nil { + t.Fatalf("Save %s: %v", id, err) + } + } + + save("ours", "archie", "", 0) + save("other-bot", "winter", "", 5*time.Hour) + save("other-thread", "archie", "t-9", 9*time.Hour) + + tr := newSessionTracker(store) + got, err := tr.resolve(ctx, "telegram", "archie", "chat-1", "") + if err != nil { + t.Fatalf("resolve: %v", err) + } + if got != "ours" { + t.Errorf("resolve = %q, want %q: a newer session for another bot or "+ + "thread must not be adopted", got, "ours") + } + }) + } +} + +// List promises newest-first in its interface doc. It reversed document +// order, which is by session ID, so the dashboard and /sessions listed an +// arbitrary order that looked like recency. +func TestListIsNewestFirst(t *testing.T) { + for name, newStore := range compressBackends() { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + store := newStore(t) + + // Creation order deliberately disagrees with ID order. + order := []struct { + id string + offset time.Duration + }{ + {"zzz-oldest", 0}, + {"aaa-middle", time.Hour}, + {"mmm-newest", 2 * time.Hour}, + } + for _, o := range order { + if err := store.Save(ctx, SessionContext{ + SessionID: o.id, + Source: SessionSource{Platform: "telegram", ChannelID: "chat-1"}, + CreatedAt: base.Add(o.offset), + LastActiveAt: base.Add(o.offset), + }); err != nil { + t.Fatalf("Save: %v", err) + } + } + + got, err := store.List(ctx) + if err != nil { + t.Fatalf("List: %v", err) + } + want := []string{"mmm-newest", "aaa-middle", "zzz-oldest"} + if len(got) != len(want) { + t.Fatalf("List returned %d sessions, want %d", len(got), len(want)) + } + for i, w := range want { + if got[i].SessionID != w { + t.Errorf("List[%d] = %q, want %q (full order %v)", + i, got[i].SessionID, w, sessionIDs(got)) + } + } + }) + } +} + +func sessionIDs(ss []SessionContext) []string { + out := make([]string, 0, len(ss)) + for _, s := range ss { + out = append(out, s.SessionID) + } + return out +} diff --git a/internal/gateway/session_store.go b/internal/gateway/session_store.go index 2e5cf0bbb..92a3249d7 100644 --- a/internal/gateway/session_store.go +++ b/internal/gateway/session_store.go @@ -283,13 +283,25 @@ func (s *nellSessionStore) listAllLocked(ctx context.Context) ([]SessionContext, } out = append(out, docToSession(row.Doc)) } - // Newest first. - for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 { - out[i], out[j] = out[j], out[i] - } + // Newest first. AllDocs sorts by document ID, which for sessions is the + // session ID -- reversing that produced reverse-lexicographic order and + // passed it off as recency, so a restart resolved into an arbitrary old + // session. Sort on the field that actually means recency, falling back + // to creation for records never touched. + slices.SortStableFunc(out, func(a, b SessionContext) int { + return sessionRecency(b).Compare(sessionRecency(a)) + }) return out, nil } +// sessionRecency is the instant a session was last meaningfully used. +func sessionRecency(sc SessionContext) time.Time { + if !sc.LastActiveAt.IsZero() { + return sc.LastActiveAt + } + return sc.CreatedAt +} + func sessionToDoc(sc SessionContext) sdk.Doc { doc := sdk.Doc{ sdk.FieldID: sc.SessionID,