feat(gateway): coalesce rapid-fire text events into one turn
This commit is contained in:
1 parent
8d48a08b13
commit
d06be5ca32
5 files changed
+888
-7
No files matched your search
@@ -141,17 +141,54 @@ func (a *LocalChatAdapter) Stream(ctx context.Context, in Inbound) (<-chan ChatE
|
||||
return nil, err
|
||||
}
|
||||
events := make(chan ChatEvent, 32)
|
||||
events <- ChatEvent{Kind: "started", SessionID: id}
|
||||
go a.stream(ctx, in, id, events)
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) stream(ctx context.Context, in Inbound, id string, events chan ChatEvent) {
|
||||
defer close(events)
|
||||
|
||||
// The per-message gates run here, per fragment, on this call's own
|
||||
// goroutine -- before the batch and before the session lane. A
|
||||
// redelivered fragment is a declined delivery to the gate it always
|
||||
// reached and never joins the batch it repeats; the rate budget is
|
||||
// charged per fragment the way it always was; and since the reply a
|
||||
// gate returns renders today, the prose is the done event of this very
|
||||
// stream rather than a turn output.
|
||||
if a.Router.duplicateDelivery(in) {
|
||||
events <- ChatEvent{Kind: "done", Text: dedupReply, SessionID: id}
|
||||
return
|
||||
}
|
||||
if a.Router.checkRateLimit(in) {
|
||||
events <- ChatEvent{Kind: "done", Text: rateLimitReply, SessionID: id}
|
||||
return
|
||||
}
|
||||
|
||||
// Rapid-fire text fragments of one thought coalesce here, before the
|
||||
// session lane exists: waiting inside a lane would make every fragment
|
||||
// queue behind the first fragment's batch window instead of joining it.
|
||||
ready, mine, err := a.Router.CollectTurn(ctx, in)
|
||||
if err != nil {
|
||||
events <- ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}
|
||||
return
|
||||
}
|
||||
if !mine {
|
||||
// A covered fragment: the batch's turn runs on the call that
|
||||
// dispatched it. This caller contributes its text to that turn and
|
||||
// renders nothing of its own -- not even the started event, which
|
||||
// announces a turn that does not exist here.
|
||||
return
|
||||
}
|
||||
in = ready
|
||||
|
||||
// started announces the turn that runs; it comes now, after the gates and
|
||||
// the batch, and always before the first delta or the terminal event.
|
||||
events <- ChatEvent{Kind: "started", SessionID: id}
|
||||
|
||||
pending := make(chan ChatEvent, 32)
|
||||
stream := localChatStream{done: ctx.Done(), events: pending, sessionID: id}
|
||||
run := func(turnCtx context.Context) ChatEvent {
|
||||
reply, err := a.Router.RouteStream(turnCtx, in, stream)
|
||||
reply, err := a.Router.StreamTurn(turnCtx, in, stream)
|
||||
if err != nil {
|
||||
return ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}
|
||||
}
|
||||
|
||||
@@ -216,7 +216,16 @@ type Router struct {
|
||||
// The window is deliberately not a config knob here: the durable
|
||||
// prior-reply replay in turn.go is the backstop for duplicates that
|
||||
// outlive it, and no composition choice between them needs exposing.
|
||||
Dedup *MessageDeduplicator
|
||||
Dedup *MessageDeduplicator
|
||||
// Batches coalesces rapid-fire plain-text fragments from one sender into
|
||||
// a single turn (internal/gateway/text_batch.go), so a chat client that
|
||||
// splits one thought across several messages costs one agent turn, not
|
||||
// one per fragment. It sits after the per-message gates (dedup, rate
|
||||
// limit) and before the responder: each fragment passes the gates as
|
||||
// the message it is, and the batch's single turn is the only dispatch.
|
||||
// NewRouter wires the package default, so a production router batches;
|
||||
// nil disables coalescing (test setups).
|
||||
Batches *TextBatchAggregator
|
||||
sessionTracker *sessionTracker
|
||||
gatewayName string
|
||||
// titlingMu guards titling, the set of sessions with a title proposal
|
||||
@@ -230,7 +239,8 @@ type Router struct {
|
||||
func NewRouter(store StatusReader, llm LLMResponder, gatewayName string) *Router {
|
||||
return &Router{
|
||||
Store: store, LLM: llm, gatewayName: gatewayName,
|
||||
Dedup: NewMessageDeduplicator(0, 0, nil),
|
||||
Dedup: NewMessageDeduplicator(0, 0, nil),
|
||||
Batches: NewTextBatchAggregator(0, 0, 0, nil, nil),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,7 +306,18 @@ func (r *Router) RouteResult(ctx context.Context, in Inbound) (reply string, rat
|
||||
if r.checkRateLimit(in) {
|
||||
return rateLimitReply, true, nil
|
||||
}
|
||||
reply, err = r.route(ctx, in)
|
||||
ready, mine, err := r.CollectTurn(ctx, in)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if !mine {
|
||||
// A covered fragment: the batch's one turn answers the batch through
|
||||
// the call that dispatched it. This caller renders nothing of its
|
||||
// own; where the reply leaves as text (email is the only such
|
||||
// channel today), nothing is sent rather than the join sent twice.
|
||||
return "", false, nil
|
||||
}
|
||||
reply, err = r.route(ctx, ready)
|
||||
return reply, false, err
|
||||
}
|
||||
|
||||
@@ -309,6 +330,20 @@ func (r *Router) duplicateDelivery(in Inbound) bool {
|
||||
return r.Dedup != nil && !r.Dedup.Admit(in)
|
||||
}
|
||||
|
||||
// CollectTurn hands a gated inbound to the text batcher and returns the
|
||||
// payload this call is responsible for dispatching. Every gate has already
|
||||
// run by the time it is called -- a gate reply like the dedup prose is
|
||||
// computed for the message it is and never waits on a batch window, and
|
||||
// then the batch's single turn dispatches without running the gates again
|
||||
// (their answer is already recorded). A nil Batches passes through, as do
|
||||
// messages that are no fragment (internal/gateway/text_batch.go).
|
||||
func (r *Router) CollectTurn(ctx context.Context, in Inbound) (Inbound, bool, error) {
|
||||
if r.Batches == nil {
|
||||
return in, true, nil
|
||||
}
|
||||
return r.Batches.Collect(ctx, in)
|
||||
}
|
||||
|
||||
// route is Route's continuation once the caller has already cleared the
|
||||
// rate-limit check (or is deliberately skipping it, as RouteStream's
|
||||
// local-command fallthrough does to avoid charging one message twice).
|
||||
@@ -488,13 +523,35 @@ func (r *Router) RouteStream(ctx context.Context, in Inbound, stream TurnStream)
|
||||
if r.checkRateLimit(in) {
|
||||
return rateLimitReply, nil
|
||||
}
|
||||
return r.StreamTurn(ctx, in, stream)
|
||||
}
|
||||
|
||||
// StreamTurn dispatches one streaming turn for an inbound whose per-message
|
||||
// gates have already run. RouteStream splits it off so the text batcher's
|
||||
// dispatcher can carry the joined payload for its whole batch through here
|
||||
// without the gates answering a second time for a message they already saw
|
||||
// -- in particular so the combined payload's first-fragment source ID, which
|
||||
// the dedup gate already recorded, does not read back as a redelivery.
|
||||
func (r *Router) StreamTurn(ctx context.Context, in Inbound, stream TurnStream) (string, error) {
|
||||
cmd, _ := parseCmd(strings.TrimSpace(in.Message.Text), r.gatewayName)
|
||||
if isLocalCommand(cmd) || strings.HasPrefix(cmd, "/") {
|
||||
return r.route(ctx, in)
|
||||
}
|
||||
reply, err := r.LLMStream(ctx, in, stream)
|
||||
ready, mine, err := r.CollectTurn(ctx, in)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !mine {
|
||||
// A covered fragment: the batch's one turn streams on the call that
|
||||
// dispatched it, so this caller's stream renders nothing. The empty
|
||||
// final reply is what every renderer drops (Telegram's finalizer has
|
||||
// no message and abandons; a dashboard client shows the turn that
|
||||
// actually ran).
|
||||
return "", nil
|
||||
}
|
||||
reply, err := r.LLMStream(ctx, ready, stream)
|
||||
if err == nil {
|
||||
r.maybeAutoTitle(ctx, in.Message)
|
||||
r.maybeAutoTitle(ctx, ready.Message)
|
||||
}
|
||||
return reply, err
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ func senderInbound(senderID, text string) Inbound {
|
||||
func TestRouteRateLimitBlocksOverBudget(t *testing.T) {
|
||||
r := NewRouter(nil, fakeLLM, "test")
|
||||
r.Limiter = ratelimit.New(time.Minute, 1)
|
||||
// The batcher is off: nothing here is about coalescing, and its window
|
||||
// must not sit between a dispatch and this test's assertions.
|
||||
r.Batches = nil
|
||||
|
||||
reply, err := r.Route(context.Background(), senderInbound("u1", "hello"))
|
||||
if err != nil {
|
||||
@@ -40,6 +43,9 @@ func TestRouteRateLimitBlocksOverBudget(t *testing.T) {
|
||||
func TestRouteRateLimitIsPerSender(t *testing.T) {
|
||||
r := NewRouter(nil, fakeLLM, "test")
|
||||
r.Limiter = ratelimit.New(time.Minute, 1)
|
||||
// The batcher is off: these dispatches must be immediate, and each new
|
||||
// sender would otherwise wait out its own quiet window.
|
||||
r.Batches = nil
|
||||
|
||||
if _, err := r.Route(context.Background(), senderInbound("u1", "hi")); err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
@@ -55,6 +61,8 @@ func TestRouteRateLimitIsPerSender(t *testing.T) {
|
||||
|
||||
func TestRouteNoLimiterConfiguredNeverBlocks(t *testing.T) {
|
||||
r := NewRouter(nil, fakeLLM, "test")
|
||||
// The batcher is off: each allowed dispatch must be immediate here.
|
||||
r.Batches = nil
|
||||
|
||||
for i := range 5 {
|
||||
reply, err := r.Route(context.Background(), senderInbound("u1", "hello"))
|
||||
@@ -139,6 +147,8 @@ func TestRouteBudgetKeyLimitsWithoutSenderID(t *testing.T) {
|
||||
func TestRouteStreamLocalCommandChargesExactlyOnce(t *testing.T) {
|
||||
r := NewRouter(&fakeStore{counts: map[string]int{}}, nil, "test")
|
||||
r.Limiter = ratelimit.New(time.Minute, 2)
|
||||
// The batcher is off: the charge being pinned is per message, not per batch.
|
||||
r.Batches = nil
|
||||
r.LLMStream = func(context.Context, Inbound, TurnStream) (string, error) {
|
||||
return "streamed", nil
|
||||
}
|
||||
@@ -169,6 +179,8 @@ func TestRouteStreamLocalCommandChargesExactlyOnce(t *testing.T) {
|
||||
func TestRouteStreamRateLimitBlocksStreamedReply(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test")
|
||||
r.Limiter = ratelimit.New(time.Minute, 1)
|
||||
// The batcher is off: the blocked call must not wait on a batch window.
|
||||
r.Batches = nil
|
||||
streamCalls := 0
|
||||
r.LLMStream = func(context.Context, Inbound, TurnStream) (string, error) {
|
||||
streamCalls++
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// fragment builds one rapid-fire text message carrying the per-person
|
||||
// identity the batch key and the dedup gate read: the channel that brought
|
||||
// it, its conversation, a stable sender, and the channel-native message ID.
|
||||
// Two fragments from the same sender differ only in source ID and text.
|
||||
func fragment(n int, sender, text string) Inbound {
|
||||
return Inbound{
|
||||
Platform: "telegram",
|
||||
Message: messaging.Message{
|
||||
SourceID: fmt.Sprintf("tg-%d", n),
|
||||
ConversationID: messaging.ConversationID{ChannelID: "chat:1"},
|
||||
Sender: sender,
|
||||
SenderID: sender,
|
||||
Role: messaging.RoleUser,
|
||||
Text: text,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// routeOutcome records one RouteStream caller's reply and how its own
|
||||
// stream rendered, so the dispatcher can be told apart from fragments whose
|
||||
// turn another call covered.
|
||||
type routeOutcome struct {
|
||||
reply string
|
||||
err error
|
||||
deltas int
|
||||
}
|
||||
|
||||
// batchOf reads the open batch for a key, if one is open. Test-only: it is
|
||||
// how tests see a join land without racing a blocking Collect call.
|
||||
func batchOf(ag *TextBatchAggregator, key batchKey) *textBatch {
|
||||
ag.mu.Lock()
|
||||
defer ag.mu.Unlock()
|
||||
return ag.batches[key]
|
||||
}
|
||||
|
||||
// fragmentCount reports how many fragments key's open batch holds, or -1
|
||||
// when no batch is open. The read is taken under the aggregate's lock.
|
||||
func fragmentCount(ag *TextBatchAggregator, key batchKey) int {
|
||||
ag.mu.Lock()
|
||||
defer ag.mu.Unlock()
|
||||
if bat := ag.batches[key]; bat != nil {
|
||||
return len(bat.fragments)
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// waitForFragments polls until key's batch holds want fragments.
|
||||
func waitForFragments(t *testing.T, ag *TextBatchAggregator, key batchKey, want int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if fragmentCount(ag, key) >= want {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatalf("the batch never registered %d fragments for %v", want, key)
|
||||
}
|
||||
|
||||
// waitForSettled polls until key's batch has settled and left the map.
|
||||
func waitForSettled(t *testing.T, ag *TextBatchAggregator, key batchKey) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
ag.mu.Lock()
|
||||
gone := ag.batches[key] == nil
|
||||
ag.mu.Unlock()
|
||||
if gone {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatalf("the batch for %v never settled", key)
|
||||
}
|
||||
|
||||
// fakeBatchClock is the batcher's injectable clock: Now plus close timers
|
||||
// that fire when Advance moves past their deadline. Batch close times are
|
||||
// tested with this, never wall-clock sleeps; the same shape the curator
|
||||
// runtime's tests use.
|
||||
type fakeBatchClock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
timers []*fakeBatchTimer
|
||||
}
|
||||
|
||||
type fakeBatchTimer struct {
|
||||
c chan time.Time
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func newBatchClock(at time.Time) *fakeBatchClock {
|
||||
return &fakeBatchClock{now: at}
|
||||
}
|
||||
|
||||
func (fc *fakeBatchClock) Now() time.Time {
|
||||
fc.mu.Lock()
|
||||
defer fc.mu.Unlock()
|
||||
return fc.now
|
||||
}
|
||||
|
||||
func (fc *fakeBatchClock) After(d time.Duration) <-chan time.Time {
|
||||
fc.mu.Lock()
|
||||
defer fc.mu.Unlock()
|
||||
t := &fakeBatchTimer{c: make(chan time.Time, 1), at: fc.now.Add(d)}
|
||||
fc.timers = append(fc.timers, t)
|
||||
return t.c
|
||||
}
|
||||
|
||||
// Advance moves the clock forward and fires every timer whose deadline has
|
||||
// passed.
|
||||
func (fc *fakeBatchClock) Advance(d time.Duration) {
|
||||
fc.mu.Lock()
|
||||
fc.now = fc.now.Add(d)
|
||||
var fired []*fakeBatchTimer
|
||||
remains := fc.timers[:0]
|
||||
for _, t := range fc.timers {
|
||||
if !t.at.After(fc.now) {
|
||||
fired = append(fired, t)
|
||||
} else {
|
||||
remains = append(remains, t)
|
||||
}
|
||||
}
|
||||
fc.timers = remains
|
||||
fc.mu.Unlock()
|
||||
for _, t := range fired {
|
||||
select {
|
||||
case t.c <- t.at:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRapidFireFragmentsTakeOneTurn pins the batcher's core contract:
|
||||
// fragments of one thought delivered back to back from one sender must
|
||||
// dispatch exactly one agent turn for the joined text, not one turn per
|
||||
// fragment. The fragments are registered one at a time -- the way a channel
|
||||
// delivers them -- and the batch closes when its quiet window passes.
|
||||
func TestRapidFireFragmentsTakeOneTurn(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "telegram")
|
||||
clock := newBatchClock(time.Now())
|
||||
r.Batches = NewTextBatchAggregator(time.Hour, 0, 0, clock.Now, clock.After)
|
||||
|
||||
var mu sync.Mutex
|
||||
turns := 0
|
||||
var dispatched []string
|
||||
r.LLMStream = func(_ context.Context, in Inbound, stream TurnStream) (string, error) {
|
||||
mu.Lock()
|
||||
turns++
|
||||
dispatched = append(dispatched, in.Message.Text)
|
||||
mu.Unlock()
|
||||
stream.Delta("…")
|
||||
return "the answer", nil
|
||||
}
|
||||
|
||||
key := batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: "sam"}
|
||||
texts := []string{"first think", "about it", "then act"}
|
||||
outcomes := make(chan routeOutcome, len(texts))
|
||||
for i, text := range texts {
|
||||
go func(i int, text string) {
|
||||
deltas := 0
|
||||
reply, err := r.RouteStream(context.Background(), fragment(i, "sam", text), DeltaFunc(func(string) {
|
||||
deltas++
|
||||
}))
|
||||
outcomes <- routeOutcome{reply: reply, err: err, deltas: deltas}
|
||||
}(i, text)
|
||||
waitForFragments(t, r.Batches, key, i+1)
|
||||
}
|
||||
clock.Advance(2 * time.Hour)
|
||||
|
||||
answerers := 0
|
||||
for range texts {
|
||||
outcome := <-outcomes
|
||||
if outcome.err != nil {
|
||||
t.Errorf("RouteStream: %v", outcome.err)
|
||||
continue
|
||||
}
|
||||
if outcome.reply == "the answer" {
|
||||
answerers++
|
||||
if outcome.deltas == 0 {
|
||||
t.Error("the fragment whose turn ran must see the reply stream through it, but no delta arrived")
|
||||
}
|
||||
} else if outcome.reply != "" {
|
||||
t.Errorf("a covered fragment answered %q, want an empty reply", outcome.reply)
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if turns != 1 {
|
||||
t.Errorf("rapid-fire fragments from one sender started %d agent turns, want 1 (dispatched %q)", turns, dispatched)
|
||||
}
|
||||
if answerers != 1 {
|
||||
t.Errorf("%d of %d fragments returned the turn's own reply, want exactly 1 dispatcher", answerers, len(texts))
|
||||
}
|
||||
if turns == 1 && dispatched[0] != strings.Join(texts, "\n") {
|
||||
t.Errorf("the turn dispatched %q, want the fragments joined in arrival order", dispatched[0])
|
||||
}
|
||||
}
|
||||
|
||||
// ---- component tests ---------------------------------------------------------
|
||||
|
||||
// TestTextBatchAggregatorJoinsThenReleasesOnQuietWindow walks the batcher
|
||||
// directly: fragments join in order, the batch stays open while fragments
|
||||
// keep arriving inside the window (each join re-arms the quiet deadline),
|
||||
// settling releases everyone, and the batch's dispatcher receives the
|
||||
// joined payload under the first fragment's identity. A fragment that
|
||||
// arrives after the batch settled starts a fresh batch.
|
||||
func TestTextBatchAggregatorJoinsThenReleasesOnQuietWindow(t *testing.T) {
|
||||
clock := newBatchClock(time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC))
|
||||
ag := NewTextBatchAggregator(time.Hour, 0, 0, clock.Now, clock.After)
|
||||
|
||||
key := batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: "sam"}
|
||||
texts := []string{"first think", "about it", "then act"}
|
||||
results := make(chan collectResult, len(texts))
|
||||
for i, text := range texts {
|
||||
go func(i int, text string) {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(i, "sam", text))
|
||||
results <- collectResult{payload: payload, mine: mine, err: err}
|
||||
}(i, text)
|
||||
waitForFragments(t, ag, key, i+1)
|
||||
}
|
||||
clock.Advance(2 * time.Hour)
|
||||
|
||||
got := 0
|
||||
for range len(texts) {
|
||||
out := <-results
|
||||
if out.err != nil {
|
||||
t.Errorf("Collect: %v", out.err)
|
||||
continue
|
||||
}
|
||||
got++
|
||||
if out.mine {
|
||||
first := fragment(0, "sam", "")
|
||||
if out.payload.Message.Text != strings.Join(texts, "\n") {
|
||||
t.Errorf("payload text = %q, want the fragments joined in arrival order", out.payload.Message.Text)
|
||||
}
|
||||
if out.payload.Message.SenderID != first.Message.SenderID ||
|
||||
out.payload.Message.SourceID != first.Message.SourceID ||
|
||||
out.payload.Message.ConversationID != first.Message.ConversationID {
|
||||
t.Errorf("payload identity = %v/%v, want the first fragment's", out.payload.Message.SenderID, out.payload.Message.SourceID)
|
||||
}
|
||||
} else if out.payload.Message.Text != "" {
|
||||
t.Error("a covered fragment received a payload, want none")
|
||||
}
|
||||
}
|
||||
if got != len(texts) {
|
||||
t.Errorf("%d of %d fragments were released, want all", got, len(texts))
|
||||
}
|
||||
|
||||
// A fragment that arrives after the batch settled starts a fresh batch
|
||||
// rather than joining a settled one, and its window is its own.
|
||||
next := fragment(10, "sam", "a later thought")
|
||||
fresh := make(chan collectResult, 1)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(context.Background(), next)
|
||||
fresh <- collectResult{payload: payload, mine: mine, err: err}
|
||||
}()
|
||||
waitForFragments(t, ag, key, 1)
|
||||
clock.Advance(2 * time.Hour)
|
||||
out := <-fresh
|
||||
if out.err != nil || !out.mine || out.payload.Message.Text != "a later thought" {
|
||||
t.Errorf("a fresh batch's single fragment = %q, mine %v, err %v; want itself dispatched alone", out.payload.Message.Text, out.mine, out.err)
|
||||
}
|
||||
}
|
||||
|
||||
// collectResult pairs what one Collect call learned, for tests.
|
||||
type collectResult struct {
|
||||
payload Inbound
|
||||
mine bool
|
||||
err error
|
||||
}
|
||||
|
||||
// TestTextBatchAggregatorPassesNonFragmentsThrough pins what a batch never
|
||||
// holds: media, a command, a message no person sent, and one with no text
|
||||
// dispatch at once whatever the clock says, and carry their own payload.
|
||||
func TestTextBatchAggregatorPassesNonFragmentsThrough(t *testing.T) {
|
||||
clock := newBatchClock(time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC))
|
||||
ag := NewTextBatchAggregator(time.Hour, 0, 0, clock.Now, clock.After)
|
||||
key := batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: "sam"}
|
||||
|
||||
media := fragment(1, "sam", "the attached log")
|
||||
media.Message.Media = []messaging.MediaAttachment{{Type: "document"}}
|
||||
command := fragment(2, "sam", "/status")
|
||||
stranger := fragment(3, "", "a route wrote this")
|
||||
empty := fragment(4, "sam", "")
|
||||
|
||||
for _, in := range []Inbound{media, command, stranger, empty} {
|
||||
payload, mine, err := ag.Collect(context.Background(), in)
|
||||
if err != nil {
|
||||
t.Fatalf("Collect(%q): %v", in.Message.Text, err)
|
||||
}
|
||||
if !mine || payload.Message.Text != in.Message.Text {
|
||||
t.Errorf("Collect(%q) = (payload %q, mine %v), want it dispatched as itself", in.Message.Text, payload.Message.Text, mine)
|
||||
}
|
||||
}
|
||||
if batchOf(ag, key) != nil {
|
||||
t.Error("non-fragment messages left a batch open behind them")
|
||||
}
|
||||
|
||||
// A lone plain-text fragment is its own batch: it dispatches once the
|
||||
// quiet window passes, with its payload unchanged.
|
||||
lone := make(chan collectResult, 1)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(5, "lone-person", "just one message"))
|
||||
lone <- collectResult{payload: payload, mine: mine, err: err}
|
||||
}()
|
||||
waitForFragments(t, ag, batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: "lone-person"}, 1)
|
||||
clock.Advance(2 * time.Hour)
|
||||
waitForSettled(t, ag, batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: "lone-person"})
|
||||
out := <-lone
|
||||
if out.err != nil || !out.mine || out.payload.Message.Text != "just one message" {
|
||||
t.Errorf("a singleton = %q, mine %v, err %v; want itself dispatched once the window passed", out.payload.Message.Text, out.mine, out.err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTextBatchAggregatorClosesOnItsBounds pins the early close: a batch
|
||||
// that reaches its fragment bound settles at once, without waiting out the
|
||||
// window, and releases its fragments; a later fragment forms a fresh batch.
|
||||
func TestTextBatchAggregatorClosesOnItsBounds(t *testing.T) {
|
||||
clock := newBatchClock(time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC))
|
||||
ag := NewTextBatchAggregator(time.Hour, 2, 0, clock.Now, clock.After)
|
||||
key := batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: "sam"}
|
||||
|
||||
results := make(chan collectResult, 2)
|
||||
for i := range 2 {
|
||||
go func(i int) {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(i, "sam", fmt.Sprintf("fragment %d", i)))
|
||||
results <- collectResult{payload: payload, mine: mine, err: err}
|
||||
}(i)
|
||||
if i == 0 {
|
||||
waitForFragments(t, ag, key, 1)
|
||||
}
|
||||
}
|
||||
// Both settles happened without any clock movement: the bound, not the
|
||||
// window, closed the batch.
|
||||
waitForSettled(t, ag, key)
|
||||
|
||||
var payloads []string
|
||||
for range 2 {
|
||||
out := <-results
|
||||
if out.err != nil {
|
||||
t.Errorf("Collect: %v", out.err)
|
||||
continue
|
||||
}
|
||||
if out.mine {
|
||||
payloads = append(payloads, out.payload.Message.Text)
|
||||
}
|
||||
}
|
||||
if len(payloads) != 1 || payloads[0] != "fragment 0\nfragment 1" {
|
||||
t.Errorf("the bounded batch dispatched %q from %d dispatchers, want the two fragments joined by its single dispatcher", strings.Join(payloads, "|"), len(payloads))
|
||||
}
|
||||
|
||||
// A fragment arriving after the bound closed its batch waits on a fresh
|
||||
// batch window rather than being attached to nothing.
|
||||
after := make(chan collectResult, 1)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(5, "sam", "after the bound"))
|
||||
after <- collectResult{payload: payload, mine: mine, err: err}
|
||||
}()
|
||||
waitForFragments(t, ag, key, 1)
|
||||
if bat := batchOf(ag, key); bat == nil || len(bat.fragments) != 1 {
|
||||
t.Error("the post-bound fragment did not start its own batch")
|
||||
}
|
||||
clock.Advance(2 * time.Hour)
|
||||
out := <-after
|
||||
if out.err != nil || !out.mine || out.payload.Message.Text != "after the bound" {
|
||||
t.Errorf("the post-bound fragment = %q, mine %v, err %v; want its own batch closed on the window", out.payload.Message.Text, out.mine, out.err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTextBatchAggregatorSeparatesSenders pins the batch key: two senders
|
||||
// in one conversation hold two open batches, and neither dispatches more
|
||||
// text than its sender wrote.
|
||||
func TestTextBatchAggregatorSeparatesSenders(t *testing.T) {
|
||||
clock := newBatchClock(time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC))
|
||||
ag := NewTextBatchAggregator(time.Hour, 0, 0, clock.Now, clock.After)
|
||||
keyOf := func(sender string) batchKey {
|
||||
return batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: sender}
|
||||
}
|
||||
|
||||
results := make(chan collectResult, 3)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(1, "sam", "did the build pass"))
|
||||
if mine {
|
||||
results <- collectResult{payload: payload, err: err}
|
||||
}
|
||||
}()
|
||||
waitForFragments(t, ag, keyOf("sam"), 1)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(2, "kim", "same here, checking"))
|
||||
if mine {
|
||||
results <- collectResult{payload: payload, err: err}
|
||||
}
|
||||
}()
|
||||
waitForFragments(t, ag, keyOf("kim"), 1)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(3, "sam", "and the tests"))
|
||||
if mine {
|
||||
results <- collectResult{payload: payload, err: err}
|
||||
}
|
||||
}()
|
||||
waitForFragments(t, ag, keyOf("sam"), 2)
|
||||
clock.Advance(2 * time.Hour)
|
||||
|
||||
var texts []string
|
||||
for range 2 {
|
||||
out := <-results
|
||||
if out.err != nil {
|
||||
t.Errorf("Collect: %v", out.err)
|
||||
}
|
||||
texts = append(texts, out.payload.Message.Text)
|
||||
}
|
||||
sam := strings.Join([]string{"did the build pass", "and the tests"}, "\n")
|
||||
for _, text := range texts {
|
||||
switch text {
|
||||
case sam, "same here, checking":
|
||||
default:
|
||||
t.Errorf("senders dispatched %q; want only %q and %q", text, sam, "same here, checking")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTextBatchAggregatorHandsTheDispatchToAStillWaitingFragment pins the
|
||||
// handover: the caller that opens a batch may leave before the batch
|
||||
// settles, and the batch's turn must still run -- the first fragment still
|
||||
// waiting inherits the dispatch.
|
||||
func TestTextBatchAggregatorHandsTheDispatchToAStillWaitingFragment(t *testing.T) {
|
||||
clock := newBatchClock(time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC))
|
||||
ag := NewTextBatchAggregator(time.Hour, 0, 0, clock.Now, clock.After)
|
||||
key := batchKey{Platform: "telegram", Conversation: "chat:1", SenderID: "sam"}
|
||||
|
||||
leaderCtx, cancelLeader := context.WithCancel(context.Background())
|
||||
results := make(chan collectResult, 2)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(leaderCtx, fragment(0, "sam", "half a thought"))
|
||||
results <- collectResult{payload: payload, mine: mine, err: err}
|
||||
}()
|
||||
waitForFragments(t, ag, key, 1)
|
||||
go func() {
|
||||
payload, mine, err := ag.Collect(context.Background(), fragment(1, "sam", "the other half"))
|
||||
results <- collectResult{payload: payload, mine: mine, err: err}
|
||||
}()
|
||||
waitForFragments(t, ag, key, 2)
|
||||
|
||||
cancelLeader()
|
||||
leader := <-results
|
||||
if leader.err == nil || leader.mine {
|
||||
t.Errorf("the cancelled dispatcher = mine %v, err %v; want its own error", leader.mine, leader.err)
|
||||
}
|
||||
|
||||
clock.Advance(2 * time.Hour)
|
||||
heir := <-results
|
||||
if heir.err != nil || !heir.mine {
|
||||
t.Fatalf("the remaining fragment = mine %v, err %v; want it to inherit the dispatch", heir.mine, heir.err)
|
||||
}
|
||||
if heir.payload.Message.Text != "half a thought\nthe other half" {
|
||||
t.Errorf("the inherited turn dispatched %q, want the whole batch joined", heir.payload.Message.Text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// The batcher's quiet window, its per-batch bounds, and its open-batch cap.
|
||||
// Chat clients -- Telegram in particular -- split one thought across several
|
||||
// messages sent within a second or two of each other, so a quiet window of
|
||||
// 1.5s since the last fragment catches that habit; a lone message is delayed
|
||||
// by exactly the window, which is the price a coalescer can never avoid
|
||||
// (every inbound message is bounded away from dispatch by at most the
|
||||
// window). A batch is also bounded up front: at most defaultBatchFragments
|
||||
// fragments or defaultBatchMaxRunes of combined text close it before the
|
||||
// window runs out, and at most defaultBatchOpenCap batches may be open at
|
||||
// once -- the oldest is settled early, never dropped, when a later one
|
||||
// opens. The cap bounds memory the way the deduplicator's cache does: one
|
||||
// open batch is a handful of Inbound values, and settling is bounded by the
|
||||
// same window.
|
||||
const (
|
||||
defaultBatchWindow = 1500 * time.Millisecond
|
||||
defaultBatchFragments = 8
|
||||
defaultBatchMaxRunes = 4000
|
||||
defaultBatchOpenCap = 256
|
||||
)
|
||||
|
||||
// TextBatchAggregator coalesces rapid-fire text fragments from one sender
|
||||
// into a single turn instead of running the agent loop once per fragment.
|
||||
//
|
||||
// Collect is the whole contract. A message that is not a fragment (media, a
|
||||
// command, anything without a per-person SenderID, anything without text)
|
||||
// passes through at once: those are not parts of one thought, and a /stop
|
||||
// must never wait on a window. A fragment is registered under the batch key
|
||||
// (platform, conversation, sender) and the call blocks until the batch
|
||||
// closes -- on a quiet window since the last fragment (reset by every join),
|
||||
// or on one of the size bounds. The first still-waiting fragment is the
|
||||
// dispatcher: it receives the combined payload and runs the one turn, and
|
||||
// every other fragment is released with mine=false, because the batch's
|
||||
// single dispatch covers it. Fragments arrive in order and are joined in
|
||||
// that order; the payload carries the first fragment's identity, so the
|
||||
// session records one message with one channel-native source ID.
|
||||
//
|
||||
// The release -- not the dispatch -- happens inside Collect: a covered
|
||||
// fragment's caller is free the moment its batch settles and renders
|
||||
// nothing on its own behalf, while the dispatcher's caller carries the turn
|
||||
// through the ordinary session machinery, which is where per-session
|
||||
// ordering stays enforced. The gate order upstream is unchanged: dedup and
|
||||
// the rate limit run per fragment before Collect, so a redelivered fragment
|
||||
// is a declined delivery as always and never joins the batch whose original
|
||||
// it repeats, and each fragment is charged its own budget.
|
||||
//
|
||||
// Cancellation is per call: a fragment whose context ends before the batch
|
||||
// settles leaves with its own error and takes no dispatch duty; if it was
|
||||
// the dispatcher, the first still-waiting fragment inherits the slot, so
|
||||
// the batch never loses its one turn to a caller that gave up. A batch
|
||||
// whose every caller left settles with no dispatcher at all.
|
||||
type TextBatchAggregator struct {
|
||||
window time.Duration
|
||||
maxFragments int
|
||||
maxRunes int
|
||||
openCap int
|
||||
// now and after inject the clock, so close times are tested without
|
||||
// sleeping; nil selects the system clock, which is the production shape.
|
||||
now func() time.Time
|
||||
after func(time.Duration) <-chan time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
batches map[batchKey]*textBatch
|
||||
// opened lists the open batches oldest-first, so eviction can settle the
|
||||
// oldest one when the open-batch cap is reached.
|
||||
opened []*textBatch
|
||||
}
|
||||
|
||||
// batchKey identifies one conversational stream a batch coalesces: the
|
||||
// channel that carried the fragments, the conversation, and the sender.
|
||||
// A struct, not a concatenated string, for the same reason the
|
||||
// deduplicator's key is one: no separator can ever collide.
|
||||
type batchKey struct {
|
||||
Platform string
|
||||
Conversation string
|
||||
SenderID string
|
||||
}
|
||||
|
||||
// coalescableText reports whether in is a fragment a batch may hold. A
|
||||
// fragment is plain text from a sender with a stable per-person ID: no
|
||||
// media (a photo is a turn of its own), no command (an operator's /stop is
|
||||
// never delayed into a window), and text to join. An empty sender means no
|
||||
// per-person stream exists to fragment -- a webhook route is an automated
|
||||
// source, not someone splitting a thought.
|
||||
func coalescableText(in Inbound) bool {
|
||||
text := strings.TrimSpace(in.Message.Text)
|
||||
if text == "" || strings.HasPrefix(text, "/") {
|
||||
return false
|
||||
}
|
||||
if len(in.Message.Media) != 0 || in.Message.SenderID == "" {
|
||||
return false
|
||||
}
|
||||
return in.Message.ToolCall == nil && in.Message.ToolResult == nil
|
||||
}
|
||||
|
||||
// textBatch is one open batch: the fragments in arrival order, the quiet
|
||||
// deadline the latest join set, and the release every waiting call reads
|
||||
// once the batch settles. The payload and the chosen dispatcher are written
|
||||
// under the aggregator's mutex before release closes, so a released caller
|
||||
// reads them safely.
|
||||
type textBatch struct {
|
||||
key batchKey
|
||||
fragments []Inbound
|
||||
left []bool
|
||||
runes int
|
||||
deadline time.Time
|
||||
|
||||
release chan struct{}
|
||||
wake chan struct{}
|
||||
settled bool
|
||||
payload Inbound
|
||||
dispatcher int
|
||||
}
|
||||
|
||||
// NewTextBatchAggregator returns a batcher with the given quiet window and
|
||||
// bounds. Zero values select the package defaults; nil now and after select
|
||||
// the real clock, which is the production shape.
|
||||
func NewTextBatchAggregator(window time.Duration, maxFragments, maxRunes int, now func() time.Time, after func(time.Duration) <-chan time.Time) *TextBatchAggregator {
|
||||
if window <= 0 {
|
||||
window = defaultBatchWindow
|
||||
}
|
||||
if maxFragments <= 0 {
|
||||
maxFragments = defaultBatchFragments
|
||||
}
|
||||
if maxRunes <= 0 {
|
||||
maxRunes = defaultBatchMaxRunes
|
||||
}
|
||||
if now == nil {
|
||||
now = time.Now
|
||||
}
|
||||
if after == nil {
|
||||
after = time.After
|
||||
}
|
||||
return &TextBatchAggregator{
|
||||
window: window,
|
||||
maxFragments: maxFragments,
|
||||
maxRunes: maxRunes,
|
||||
openCap: defaultBatchOpenCap,
|
||||
now: now,
|
||||
after: after,
|
||||
batches: make(map[batchKey]*textBatch),
|
||||
}
|
||||
}
|
||||
|
||||
// Collect registers a plain-text fragment in the batch for its key and
|
||||
// blocks until that batch settles. It reports the payload this call is
|
||||
// responsible for and whether this call must dispatch it: true for the
|
||||
// batch's dispatcher (whose payload equals its own message when no fragment
|
||||
// ever joined, and carries the joined text when one did), false for a
|
||||
// covered fragment that must render nothing of its own. A message that is
|
||||
// no fragment returns at once with its own payload. A call's own context
|
||||
// cancellation takes only itself out of the batch.
|
||||
func (b *TextBatchAggregator) Collect(ctx context.Context, in Inbound) (Inbound, bool, error) {
|
||||
if !coalescableText(in) {
|
||||
return in, true, nil
|
||||
}
|
||||
|
||||
key := batchKey{
|
||||
Platform: in.Platform,
|
||||
Conversation: in.Message.ConversationID.String(),
|
||||
SenderID: in.Message.SenderID,
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
bat := b.batches[key]
|
||||
if bat == nil {
|
||||
bat = &textBatch{
|
||||
key: key,
|
||||
deadline: b.now().Add(b.window),
|
||||
release: make(chan struct{}),
|
||||
wake: make(chan struct{}, 1),
|
||||
dispatcher: 0,
|
||||
}
|
||||
b.batches[key] = bat
|
||||
b.opened = append(b.opened, bat)
|
||||
for len(b.opened) > b.openCap {
|
||||
// Forced eviction settles the oldest batch early -- with the
|
||||
// fragments it holds, not empty-handed -- by moving its quiet
|
||||
// deadline to now; its caretaker wakes and settles it. Its key
|
||||
// stays in the map until then, so a join in flight still lands.
|
||||
oldest := b.opened[0]
|
||||
b.opened = b.opened[1:]
|
||||
oldest.deadline = b.now()
|
||||
select {
|
||||
case oldest.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
go b.watch(bat)
|
||||
}
|
||||
index := len(bat.fragments)
|
||||
bat.fragments = append(bat.fragments, in)
|
||||
bat.left = append(bat.left, false)
|
||||
bat.runes += utf8.RuneCountInString(strings.TrimSpace(in.Message.Text))
|
||||
if len(bat.fragments) >= b.maxFragments || bat.runes >= b.maxRunes {
|
||||
bat.deadline = b.now()
|
||||
}
|
||||
b.mu.Unlock()
|
||||
|
||||
select {
|
||||
case bat.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
|
||||
select {
|
||||
case <-bat.release:
|
||||
case <-ctx.Done():
|
||||
// This fragment's caller left before the batch settled: it takes no
|
||||
// dispatch duty, and if it held the dispatcher slot, the first still-
|
||||
// waiting fragment inherits it at settle.
|
||||
b.mu.Lock()
|
||||
bat.left[index] = true
|
||||
b.mu.Unlock()
|
||||
select {
|
||||
case bat.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return Inbound{}, false, ctx.Err()
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if index == bat.dispatcher {
|
||||
return bat.payload, true, nil
|
||||
}
|
||||
return messaging.Inbound{}, false, nil
|
||||
}
|
||||
|
||||
// watch drives one batch's quiet close: it re-arms on every fresh fragment
|
||||
// (each join resets the quiet deadline to now+window) and on eviction, and
|
||||
// settles the moment the deadline passes.
|
||||
func (b *TextBatchAggregator) watch(bat *textBatch) {
|
||||
for {
|
||||
b.mu.Lock()
|
||||
deadline := bat.deadline
|
||||
b.mu.Unlock()
|
||||
remaining := deadline.Sub(b.now())
|
||||
if remaining <= 0 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-b.after(remaining):
|
||||
case <-bat.wake:
|
||||
}
|
||||
}
|
||||
b.settle(bat)
|
||||
}
|
||||
|
||||
// settle closes one batch and releases its waiters. The payload joins every
|
||||
// fragment's text, in arrival order, under the first fragment's identity,
|
||||
// and the dispatch duty goes to the first fragment whose call still waits;
|
||||
// -1 when none does.
|
||||
func (b *TextBatchAggregator) settle(bat *textBatch) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if bat.settled {
|
||||
return
|
||||
}
|
||||
bat.settled = true
|
||||
delete(b.batches, bat.key)
|
||||
for i, listed := range b.opened {
|
||||
if listed == bat {
|
||||
b.opened = append(b.opened[:i], b.opened[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
// The dispatch duty goes to the first fragment whose call still waits;
|
||||
// a batch whose every caller left settles with no dispatcher (-1).
|
||||
bat.dispatcher = -1
|
||||
for i, gone := range bat.left {
|
||||
if !gone {
|
||||
bat.dispatcher = i
|
||||
break
|
||||
}
|
||||
}
|
||||
bat.payload = combined(bat.fragments)
|
||||
close(bat.release)
|
||||
}
|
||||
|
||||
// combined joins fragments into one turn payload: the first fragment's
|
||||
// identity fields, the texts joined in arrival order.
|
||||
func combined(fragments []Inbound) Inbound {
|
||||
ready := fragments[0]
|
||||
var body strings.Builder
|
||||
for i, f := range fragments {
|
||||
if i > 0 {
|
||||
body.WriteString("\n")
|
||||
}
|
||||
body.WriteString(strings.TrimSpace(f.Message.Text))
|
||||
}
|
||||
ready.Message.Text = body.String()
|
||||
return ready
|
||||
}
|
||||
Reference in new issue
Block a user