diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 0c3974cd5..657137169 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -472,10 +472,11 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { // aimed at had already finished. func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, router *gateway.Router) { gm := gateway.Message{ - // Telegram's message ID makes persistence idempotent, so a - // redelivered update updates the stored turn instead of appending - // a duplicate. Date is the sender's clock reading for the message - // and is what history should be ordered by. + // Telegram's message ID makes persistence idempotent: the store + // derives a canonical ID from it, so a redelivered update is a + // no-op rather than appending a duplicate or overwriting the + // stored record, which must stay immutable. Date is the sender's + // clock reading and is what history should be ordered by. SourceID: fmt.Sprintf("%d", msg.ID), ChannelID: fmt.Sprintf("%d", msg.Chat.ID), ThreadID: threadIDString(msg.MessageThreadID), diff --git a/internal/gateway/branch_identity_test.go b/internal/gateway/branch_identity_test.go new file mode 100644 index 000000000..6168c6681 --- /dev/null +++ b/internal/gateway/branch_identity_test.go @@ -0,0 +1,101 @@ +package gateway + +import ( + "context" + "strings" + "testing" +) + +// A branch copies the parent's history into a new session. Those copies used +// to keep the parent's canonical MessageIDs, because saveMessageLocked +// honours an incoming ID and handleBranch fed it messages read straight back +// from the parent. newMessageID's own doc claims the opposite -- "the same +// upstream message copied into a branch gets its own identity" -- and the +// architecture requires exact branch-point correlation on stable MessageIDs, +// which is ambiguous when three sessions hold the same ID. +// +// It also defeats dedup in the child: redelivering an upstream message that +// was inherited appends, because the inherited copy carries an ID derived +// from the parent's session rather than the child's. +func TestBranchGivesInheritedMessagesTheirOwnIdentity(t *testing.T) { + for name, newStore := range compressBackends() { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + store := newStore(t) + + r := NewRouter(nil, nil, "telegram") + r.InitSessions(store) + r.Identity = "archie" + + parentID, err := r.sessionTracker.resolve(ctx, "telegram", "archie", "chat-1", "") + if err != nil { + t.Fatalf("resolve: %v", err) + } + + for i, text := range []string{"one", "two", "three"} { + if err := store.SaveMessage(ctx, parentID, Message{ + From: "alice", Text: text, SourceID: "tg-" + text, At: at(dur(i)), + }); err != nil { + t.Fatalf("SaveMessage: %v", err) + } + } + parentMsgs, err := store.RecentMessages(ctx, parentID, 100) + if err != nil { + t.Fatalf("RecentMessages(parent): %v", err) + } + + reply, err := r.Route(ctx, Message{Text: "/branch side-quest", ChannelID: "chat-1"}) + if err != nil { + t.Fatalf("Route(/branch): %v", err) + } + if !strings.Contains(reply, "Branched") { + t.Fatalf("reply = %q, want a branch confirmation", reply) + } + childID := r.sessionTracker.getActive("chat-1", "") + if childID == parentID { + t.Fatal("branch did not switch the active session") + } + + childMsgs, err := store.RecentMessages(ctx, childID, 100) + if err != nil { + t.Fatalf("RecentMessages(child): %v", err) + } + if len(childMsgs) != len(parentMsgs) { + t.Fatalf("child has %d messages, want the parent's %d", len(childMsgs), len(parentMsgs)) + } + + parentIDs := make(map[string]struct{}, len(parentMsgs)) + for _, m := range parentMsgs { + parentIDs[m.MessageID] = struct{}{} + } + for _, m := range childMsgs { + if _, shared := parentIDs[m.MessageID]; shared { + t.Errorf("inherited %q kept the parent's MessageID %q: two sessions "+ + "now claim one canonical identity", m.Text, m.MessageID) + } + if m.SourceID == "" { + t.Errorf("inherited %q lost its SourceID; upstream correlation is gone", m.Text) + } + if want := CanonicalMessageID(childID, m.SourceID); m.MessageID != want { + t.Errorf("inherited %q: MessageID = %q, want the child-scoped %q", + m.Text, m.MessageID, want) + } + } + + // Dedup must work in the child on its own terms. + if err := store.SaveMessage(ctx, childID, Message{ + From: "alice", Text: "two", SourceID: "tg-two", At: at(dur(1)), + }); err != nil { + t.Fatalf("redeliver into child: %v", err) + } + after, err := store.MessageCount(ctx, childID) + if err != nil { + t.Fatalf("MessageCount: %v", err) + } + if after != len(childMsgs) { + t.Errorf("redelivery into the branch appended: count = %d, want %d", + after, len(childMsgs)) + } + }) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b4c1be962..80776b954 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -22,8 +22,17 @@ import ( type Message struct { // MessageID is the canonical, application-generated identifier for // this message. It is assigned by the message store, stable, and the - // handle branch points and related records correlate on. Populated on - // read; ignored on write. + // handle branch points and related records correlate on. + // + // Populated on read, and HONOURED on write: saving a message that + // already carries one keeps that identity, which is what lets a + // read-modify-write of a history preserve identities rather than + // minting new ones. A caller copying messages into a different session + // must therefore clear it, or two sessions end up claiming one + // identity -- see handleBranch. + // + // Leave it empty for a newly received message: the store derives one, + // from SourceID when there is one. MessageID string // SourceID is the channel-native identifier (e.g. a Telegram // message_id). It is external correlation metadata, never the diff --git a/internal/gateway/session_commands.go b/internal/gateway/session_commands.go index 18f10d938..6f7a34b23 100644 --- a/internal/gateway/session_commands.go +++ b/internal/gateway/session_commands.go @@ -515,7 +515,19 @@ func (r *Router) handleBranch(ctx context.Context, msg Message, rest string) (st return "", fmt.Errorf("inherit history: %w", err) } if len(msgs) > 0 { - if err := r.sessionTracker.sessions.SaveMessages(ctx, id, msgs); err != nil { + // Clear the canonical ID so the child derives its own. The store + // honours an incoming MessageID -- which is what lets a + // read-modify-write keep identities -- so copying the parent's + // messages verbatim made two sessions claim one identity, leaving + // branch-point correlation ambiguous. It also broke dedup in the + // child: an inherited message carried an ID derived from the + // parent's session, so redelivering it appended. + inherited := make([]Message, 0, len(msgs)) + for _, m := range msgs { + m.MessageID = "" + inherited = append(inherited, m) + } + if err := r.sessionTracker.sessions.SaveMessages(ctx, id, inherited); err != nil { return "", fmt.Errorf("copy history: %w", err) } } diff --git a/internal/gateway/session_store.go b/internal/gateway/session_store.go index 169303bbf..26cebfe71 100644 --- a/internal/gateway/session_store.go +++ b/internal/gateway/session_store.go @@ -423,11 +423,6 @@ func (s *nellSessionStore) dropMsgDB(sessionID string) { } } -// msgID builds a time-ordered, collision-free document ID. Ordering is -// driven by the _ts field, but a matching ID order keeps equal-timestamp -// ties stable across scans and cursors. The counter disambiguates messages -// that land within the same nanosecond; it resets on restart, so uniqueness -// across restarts rests on the nanosecond timestamp. // messageIDNamespace scopes the deterministic derivation below. It is a // fixed, arbitrary UUID: only its stability matters. var messageIDNamespace = uuid.MustParse("6f8d2b1e-9c4a-4f37-8a56-1d0e7b3c9a42")