Files
archie/internal/gateway/compress_ordering_test.go
T
sam fa6f4aef5f fix(gateway,daemon): repair regressions found by the adversarial review
Six defects, four of them introduced by the fixes in dbacb96, 44d43ef,
d5e016e, de1a899 and 4d44ef7. This is the third round in this codebase
where a round of fixes broke something the next round caught.

SANDBOX SILENTLY DROPPED. startContainers degrades a failed container
pool to nil, and the daemon's only test was `if ContainerPool != nil`.
So `containers.enabled = true` plus a missing agent image ran every
task's agent loop in-process, with the daemon's own authority and the
host filesystem -- the one thing [containers] exists to prevent -- while
logging only that containers were disabled. Nil now means two things and
they are distinguished: SandboxRequired parks the task instead. The
daemon still stays up; chat and the dashboard are unaffected.

SUMMARY AT THE WRONG END OF HISTORY. compressedHistory returns [head,
summary, tail], but ordering is by timestamp, not slice position. The
retained messages keep their original timestamps -- that is what
preserves their identity -- so the summary, being new, was clamped to
now and sorted after the tail it was meant to precede. The model read
the recent conversation and was only then told earlier context had been
summarised. Confirmed on both backends: index 23 of 24.

The monotonic clamp belongs to the append path, where an inbound message
must not sort ahead of the one that provoked it. ReplaceMessages is a
rewrite primitive and now honours explicit placement, and the summary
takes a timestamp inside the span it replaces.

A COMPRESSION SUMMARY ANSWERED A QUESTION. Following from the above,
PriorReply saw a bot-attributed record immediately after an unanswered
message and replayed it as the answer: a redelivered question was
"answered" with the compression banner and the model never ran. The
user's question was silently swallowed.

RECENCY STILL DIVERGED. sessionRecency preferred LastActiveAt whenever
set; SQLite used MAX(last_active_at, created_at). Those agree only when
LastActiveAt is the later of the two, so a clock step or an older record
made the caller and the store order the same sessions differently.

LASTACTIVEAT WAS NEVER UPDATED. Touch had no caller, so "resolve the
most recently active session" meant the most recently created one -- an
operator who moved to an older session with /topic and worked there was
dropped back into the newer, abandoned one on restart, which is the bug
d5e016e claimed to fix, with the direction reversed.

/branch WITH NO ACTIVE SESSION PANICKED, slicing an empty parent ID for
its default title. Pre-existing, but reachable: email and webhook call
Route directly without resolving first, and the email path runs in a
goroutine with no recover, so one message took the daemon down.

The sandbox guard has no test. The honest reason is that exercising it
needs a daemon with a forge and worktree the current harness does not
build, and a test that re-states the condition proves nothing -- which
is the same false confidence that let these regressions through.
2026-08-05 04:24:16 +10:00

115 lines
3.5 KiB
Go

package gateway
import (
"context"
"strings"
"testing"
)
// The summary stands in for the messages it replaced, so it belongs where
// they were: after the protected head, before the protected tail.
//
// Preserving the retained messages' original timestamps -- which is what
// stops compression destroying their identity -- means ordering is no longer
// the order the caller wrote them in. The summary is a new record, so the
// monotonic clamp stamps it with now and it sorts after everything it was
// supposed to precede. The model then reads the whole tail of the
// conversation and is told afterwards that earlier context was summarised.
func TestCompressSummaryLandsBetweenHeadAndTail(t *testing.T) {
for name, newStore := range compressBackends() {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
store := newStore(t)
r, sessionID := routerOn(t, store, "chat-1")
seedForCompress(t, store, sessionID, 40)
if _, err := r.applyCompress(ctx, sessionID, DefaultCompressionConfig()); err != nil {
t.Fatalf("applyCompress: %v", err)
}
after, err := store.RecentMessages(ctx, sessionID, 1000)
if err != nil {
t.Fatalf("RecentMessages: %v", err)
}
marker := DefaultCompressionConfig().SummaryMarker
idx := -1
for i, m := range after {
if strings.Contains(m.Text, marker) {
idx = i
break
}
}
if idx < 0 {
t.Fatal("no summary in the compressed history")
}
cfg := DefaultCompressionConfig()
if idx != cfg.ProtectFirst {
t.Errorf("summary is at index %d of %d, want %d (after the %d "+
"protected head messages, before the tail): the model reads "+
"the recent conversation and is only then told that earlier "+
"context was summarised",
idx, len(after), cfg.ProtectFirst, cfg.ProtectFirst)
}
if idx == len(after)-1 {
t.Error("the summary is the newest message in the session")
}
})
}
}
// PriorReply decides "was this message already answered?" by looking at
// whether the next turn came from the bot. A compression summary is
// attributed to the bot and is not an answer to anything, so it must not be
// mistaken for one -- otherwise a redelivered question is answered with a
// compression banner and the model is never called.
func TestPriorReplyIgnoresACompressionSummary(t *testing.T) {
const (
sessionID = "chat-1"
identity = "archie"
)
marker := DefaultCompressionConfig().SummaryMarker
history := []Message{
{
MessageID: CanonicalMessageID(sessionID, "tg-unanswered"),
SourceID: "tg-unanswered",
From: "alice",
Text: "what is 2+2?",
},
{
MessageID: "summary-record",
From: identity,
Text: marker + "\n\n[36 messages removed (~9000 tokens)]",
},
}
if got := PriorReply(history, sessionID, "tg-unanswered", identity); got != "" {
t.Errorf("PriorReply = %q, want \"\": the question was never answered, "+
"so redelivering it must re-run the model rather than replay a "+
"compression banner as the answer", got)
}
}
// A genuine reply is still recognised, so the dedup that stops a redelivered
// message being answered twice keeps working.
func TestPriorReplyStillMatchesARealReply(t *testing.T) {
const (
sessionID = "chat-1"
identity = "archie"
)
history := []Message{
{
MessageID: CanonicalMessageID(sessionID, "tg-1"),
SourceID: "tg-1",
From: "alice",
Text: "ping",
},
{MessageID: "reply", From: identity, Text: "pong"},
}
if got := PriorReply(history, sessionID, "tg-1", identity); got != "pong" {
t.Errorf("PriorReply = %q, want %q", got, "pong")
}
}