package server import ( "context" "testing" "git.a-wan.net/alan/pipelines/internal/protocol" ) func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing.T) { h := newChatHub() room := newChatRoom(context.Background(), "ses_usage") defer room.cancel() room.running = true room.nativeTurnID = "turn_keep" room.turnDone = make(chan struct{}) h.rooms[room.sessionID] = room sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})} room.subs[sub.clientID] = sub h.apply(protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running"}}) for _, n := range []int64{123, 123, 0, 5} { total := n u := &protocol.ChatUsage{Scope: "session", TotalTokens: &total} h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: u}) live := (<-sub.ch).ChatEvent if live.MessageID != "" || *live.Usage.TotalTokens != n { t.Fatalf("live=%+v", live) } total = 999 // producer-owned data must not mutate retained state h.replayUsage(sub) frame := (<-sub.ch).ChatEvent if frame == nil || frame.Kind != protocol.ChatEventUsage || frame.MessageID != "" || frame.Usage.TotalTokens == nil || *frame.Usage.TotalTokens != n { t.Fatalf("replay=%+v", frame) } *frame.Usage.TotalTokens = 888 // neither may a consumer if !room.running || room.nativeTurnID != "turn_keep" || h.turns[room.sessionID].step != nil || h.turns[room.sessionID].compaction == nil { t.Fatal("usage changed turn/admission/compaction") } select { case <-room.turnDone: t.Fatal("usage settled turn") default: } } if got := h.snapshot(room.sessionID); len(got) != 0 { t.Fatalf("usage created transcript messages %+v", got) } // A full snapshot may legitimately reset every unknown field to nil. h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Scope: "session"}}) <-sub.ch h.replayUsage(sub) if f := (<-sub.ch).ChatEvent; f.Usage.TotalTokens != nil { t.Fatal("unknown snapshot accumulated old counter") } other := newChatRoom(context.Background(), "ses_other") defer other.cancel() h.rooms[other.sessionID] = other otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})} other.subs[otherSub.clientID] = otherSub h.replayUsage(otherSub) if len(otherSub.ch) != 0 { t.Fatal("foreign usage replayed") } }