Harden Harness runtime, persistence and execution for Hand

This commit is contained in:
sausheong committed 2026-09-09 22:55:55 +08:00
1 parent 09c30fe2d5
commit 0972eed3ea
164 files changed
+15912 -506

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
package compaction
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"strings"
"testing"
)
type budgetProvider struct {
fakeProvider
requests []llm.ChatRequest
}
func (p *budgetProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.requests = append(p.requests, req)
return p.fakeProvider.ChatStream(ctx, req)
}
func TestSummariserOutputBudgetAndResponseBound(t *testing.T) {
entries := []session.SessionEntry{session.UserMessageEntry("task")}
for _, limit := range []int{0, 1, 2048, 32768, -1, 32769} {
provider := &budgetProvider{fakeProvider: fakeProvider{text: "summary"}}
s := &Summarizer{Provider: provider, MaxOutputTokens: limit}
_, err := s.Summarize(context.Background(), entries, "")
if limit < 0 || limit > 32768 {
if err == nil || len(provider.requests) != 0 {
t.Fatal("invalid budget dispatched")
}
continue
}
want := limit
if want == 0 {
want = 4096
}
if err != nil || len(provider.requests) != 1 || provider.requests[0].MaxTokens != want {
t.Fatalf("budget %d: %v %+v", limit, err, provider.requests)
}
}
provider := &budgetProvider{fakeProvider: fakeProvider{text: strings.Repeat("x", (256<<10)+1)}}
s := &Summarizer{Provider: provider}
out, err := s.Summarize(context.Background(), entries, "")
if err == nil || out != "" || len(provider.requests) != 1 {
t.Fatal("oversized summary accepted or retried")
}
}
+122 -48
View File
@@ -4,16 +4,15 @@ import (
"context"
"errors"
"log/slog"
"strings"
"sync"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
// MaxConsecutiveFailures is the per-session circuit-breaker threshold.
// After this many consecutive autocompact attempts that drop to the
// placeholder stage (stage 3), MaybeCompact stops attempting compaction
// After this many consecutive failed autocompact attempts, MaybeCompact stops attempting compaction
// for the session and returns Skipped="circuit_breaker".
//
// The breaker resets on any genuine summarizer success (stage 1 or 2
@@ -34,6 +33,8 @@ const (
// false, Skipped names the reason ("too_short", "empty_summary",
// "ollama_down", "model_missing", "timeout", "summarizer_error").
type Result struct {
Requests []llm.RequestUsage
Compacted bool
Reason Reason
Skipped string
@@ -46,7 +47,23 @@ type Result struct {
// Manager orchestrates compaction for sessions. One Manager is shared across
// the whole agent runtime; it tracks per-session mutexes internally.
type CommitNotification struct {
SessionID string
Reason Reason
TurnsCompacted int
TokensBefore int
TokensAfter int
}
type Manager struct {
// OnCommitted observes a successfully committed compaction after its lock is released.
// Configure while idle; callbacks must honour their bounded context. Panics are contained.
OnCommitted func(context.Context, CommitNotification)
// OnUsage receives compaction attempt records, including background work.
// The callback must be concurrency-safe and must not mutate records.
OnUsage func(llm.RequestUsage)
Summarizer *Summarizer
PreserveTurns int // K; default 4 if zero
Threshold float64 // fraction of context window that triggers preventive compaction (e.g. 0.6); 0 means use caller default
@@ -65,13 +82,14 @@ type Manager struct {
// mutexes so awaiting an in-flight compaction (WaitForInFlight)
// never serializes on the per-session lock-map or failure-counter.
inFlightMu sync.Mutex
inFlight map[string]*inFlightCompaction // session.ID → in-flight handle
inFlight map[string]*inFlightCompaction // stable session key → active or unconsumed handle
}
// inFlightCompaction tracks a background compaction goroutine spawned
// via MaybeCompactAsync. The done channel is closed when the goroutine
// returns; result holds the outcome for any waiter that wants it.
type inFlightCompaction struct {
cancel context.CancelFunc
done chan struct{}
result Result
err error
@@ -90,11 +108,32 @@ type inFlightCompaction struct {
// will block until the first completes. This is intentional — it prevents
// two compactions from racing on session.Append — but callers triggering
// manual compactions while a preventive one is in flight should expect a wait.
func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reason Reason, instructions string) (Result, error) {
func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reason Reason, instructions string) (result Result, resultErr error) {
ledger := &llm.UsageLedger{}
ctx = llm.WithUsageObserver(ctx, func(record llm.RequestUsage) {
ledger.Record(record)
if m != nil && m.OnUsage != nil {
m.OnUsage(record)
}
})
defer func() { result.Requests = ledger.Records() }()
if m == nil || m.Summarizer == nil {
return Result{Reason: reason, Skipped: "no_summarizer"}, nil
}
defer func() {
if resultErr == nil && result.Compacted && m.OnCommitted != nil {
observerCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()
defer func() {
if recovered := recover(); recovered != nil {
slog.Warn("compaction observer panicked")
}
}()
m.OnCommitted(observerCtx, CommitNotification{sess.ID, result.Reason, result.TurnsCompacted, result.TokensBefore, result.TokensAfter})
}
}()
key := stableKey(sess)
if fc := m.failureCount(key); fc >= MaxConsecutiveFailures {
slog.Info("compaction skipped",
@@ -124,27 +163,20 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
slog.Info("compaction triggered", "session_id", sess.ID, "reason", string(reason))
summary, err := m.Summarizer.Summarize(ctx, toCompact, instructions)
combined, err := guidanceFor(ctx, instructions)
if err != nil {
return Result{Reason: reason, Skipped: "invalid_guidance"}, err
}
summary, err := m.Summarizer.Summarize(ctx, toCompact, combined)
if err != nil {
skipReason := classifySummarizerError(err)
slog.Warn("compaction skipped", "session_id", sess.ID, "reason", string(reason), "skipped", skipReason, "detail", err.Error())
// A hard error from Summarize means even stage 3 didn't run.
// Count it as a failure for breaker accounting.
// Leave both raw and effective history unchanged on summarizer failure.
m.incrementFailure(key)
return Result{Reason: reason, Skipped: skipReason}, nil
}
// summarizeWithFallback's stage 3 returns a placeholder summary
// (no error) when both stage 1 and stage 2 failed. We detect
// placeholders by their stable marker phrase and treat them as
// failures for breaker accounting; real (stage-1 or stage-2)
// summaries reset the counter.
isPlaceholder := strings.Contains(summary, "compaction failed and the summary could not be generated")
if isPlaceholder {
m.incrementFailure(key)
} else {
m.resetFailures(key)
}
m.resetFailures(key)
first := toCompact[0]
last := toCompact[len(toCompact)-1]
@@ -156,14 +188,8 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
// compaction at the leaf and View() would terminate on it immediately,
// silently dropping every preserved turn.
entry.ParentID = toPreserve[0].ParentID
sess.Append(entry)
for i, e := range toPreserve {
if i == 0 {
e.ParentID = entry.ID
}
// Re-append with same ID — Session.Append's entryMap overwrite and
// the loader's last-write-wins behaviour both make this safe.
sess.Append(e)
if err := sess.CommitCompaction(view[len(view)-1].ID, entry, toPreserve); err != nil {
return Result{}, err
}
dur := time.Since(start).Milliseconds()
@@ -197,6 +223,18 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
// enough for the three-stage fallback path) so that a returning
// caller's cancellation can't kill the in-flight summary.
func (m *Manager) MaybeCompactAsync(sess *session.Session, reason Reason) <-chan struct{} {
return m.maybeCompactAsync(context.Background(), sess, reason, false)
}
// MaybeCompactAsyncContext retains caller cancellation and usage observation.
// Its completed result remains available until JoinInFlight or ForgetSession;
// another launch for this session returns the existing handle until then.
// Callers must join before releasing ownership, including on error paths.
func (m *Manager) MaybeCompactAsyncContext(parent context.Context, sess *session.Session, reason Reason) <-chan struct{} {
return m.maybeCompactAsync(parent, sess, reason, true)
}
func (m *Manager) maybeCompactAsync(parent context.Context, sess *session.Session, reason Reason, retainResult bool) <-chan struct{} {
if m == nil || m.Summarizer == nil || sess == nil {
ch := make(chan struct{})
close(ch)
@@ -211,27 +249,26 @@ func (m *Manager) MaybeCompactAsync(sess *session.Session, reason Reason) <-chan
if m.inFlight == nil {
m.inFlight = make(map[string]*inFlightCompaction)
}
fl := &inFlightCompaction{done: make(chan struct{})}
m.inFlight[key] = fl
m.inFlightMu.Unlock()
timeout := m.Summarizer.Timeout
if timeout == 0 {
timeout = 60 * time.Second
}
ctx, cancel := context.WithTimeout(parent, 2*timeout)
fl := &inFlightCompaction{done: make(chan struct{}), cancel: cancel}
m.inFlight[key] = fl
m.inFlightMu.Unlock()
go func() {
defer close(fl.done)
ctx, cancel := context.WithTimeout(context.Background(), 2*timeout)
defer cancel()
res, err := m.MaybeCompact(ctx, sess, reason, "")
fl.result = res
fl.err = err
// Drop our entry from the map so a subsequent burst can fire a
// fresh compaction (the next turn's WaitForInFlight will see no
// entry and proceed straight to its own threshold check).
m.inFlightMu.Lock()
delete(m.inFlight, key)
m.inFlightMu.Unlock()
defer func() {
cancel()
m.inFlightMu.Lock()
close(fl.done)
if !retainResult && m.inFlight[key] == fl {
delete(m.inFlight, key)
}
m.inFlightMu.Unlock()
}()
fl.result, fl.err = m.MaybeCompact(ctx, sess, reason, "")
}()
return fl.done
}
@@ -281,8 +318,16 @@ func (m *Manager) HasInFlight(sess *session.Session) bool {
key := stableKey(sess)
m.inFlightMu.Lock()
defer m.inFlightMu.Unlock()
_, ok := m.inFlight[key]
return ok
fl, ok := m.inFlight[key]
if !ok {
return false
}
select {
case <-fl.done:
return false
default:
return true
}
}
// ForgetSession removes the per-session lock, failure counter, and
@@ -300,6 +345,9 @@ func (m *Manager) ForgetSession(sess *session.Session) {
if m == nil || sess == nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
m.JoinInFlight(ctx, sess)
key := stableKey(sess)
m.mu.Lock()
delete(m.locks, key)
@@ -307,9 +355,7 @@ func (m *Manager) ForgetSession(sess *session.Session) {
m.failMu.Lock()
delete(m.failures, key)
m.failMu.Unlock()
// Drop any in-flight tracking entry too. The goroutine itself
// already deletes its entry on completion; this covers the rare
// case of a session being forgotten mid-compaction.
// Clear tracking after joining; the owner must prevent concurrent launches.
m.inFlightMu.Lock()
delete(m.inFlight, key)
m.inFlightMu.Unlock()
@@ -389,3 +435,31 @@ func classifySummarizerError(err error) string {
return "summarizer_error"
}
}
// JoinInFlight waits for and consumes the current background producer, returning its result
// and error. Cancellation cancels that producer, then still waits for it to
// finish; it never reports a join while session writes can continue. Callers
// must prevent concurrent new launches while ending session ownership.
func (m *Manager) JoinInFlight(ctx context.Context, sess *session.Session) (Result, bool, error) {
if m == nil || sess == nil {
return Result{}, false, nil
}
m.inFlightMu.Lock()
fl, ok := m.inFlight[stableKey(sess)]
m.inFlightMu.Unlock()
if !ok {
return Result{}, false, nil
}
select {
case <-fl.done:
case <-ctx.Done():
fl.cancel()
<-fl.done
}
m.inFlightMu.Lock()
if m.inFlight[stableKey(sess)] == fl {
delete(m.inFlight, stableKey(sess))
}
m.inFlightMu.Unlock()
return fl.result, true, fl.err
}
+84 -24
View File
@@ -93,12 +93,7 @@ func TestManagerRefusesShortSession(t *testing.T) {
assert.Equal(t, "too_short", res.Skipped)
}
func TestManagerSummarizerErrorFallsBackToPlaceholder(t *testing.T) {
// With the three-stage fallback chain, an empty model response no
// longer surfaces ErrEmptySummary to the Manager — stage 3 emits a
// placeholder summary so compaction "succeeds" with a stub. The
// circuit breaker (Task 5) detects the stub by string match for
// breaker accounting.
func TestManagerSummarizerErrorSkipsWithoutSummary(t *testing.T) {
mgr := &Manager{
Summarizer: &Summarizer{
Provider: &fakeProvider{text: ""},
@@ -110,9 +105,9 @@ func TestManagerSummarizerErrorFallsBackToPlaceholder(t *testing.T) {
sess := longSession()
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonManual, "")
require.NoError(t, err)
assert.True(t, res.Compacted, "stage-3 placeholder counts as a successful compaction")
assert.Contains(t, res.Summary, "compaction failed",
"summary must contain the placeholder marker so Task 5's breaker can detect it")
assert.False(t, res.Compacted)
assert.Empty(t, res.Summary)
assert.NotEmpty(t, res.Skipped)
}
func TestManagerSerializesPerSession(t *testing.T) {
@@ -342,24 +337,11 @@ func TestCircuitBreakerTripsAfterMaxFailures(t *testing.T) {
}
sess := longSession()
// First N-1 attempts run the summarizer; the alwaysFailingProvider
// makes every call drop to stage 3 (placeholder). The breaker treats
// hitting stage 3 as failure for circuit-breaker accounting.
//
// After each placeholder compaction, View() walks back to the new
// compaction entry and Split sees only the preserved K turns — too
// short to compact again. To keep the loop reaching the summarizer
// (so the failure counter can increment) we add a new user/assistant
// pair between iterations, simulating real conversation continuing
// through repeated compaction failures.
//
// First MaxConsecutiveFailures calls: Compacted=true (placeholder)
// — each increments the failure counter. The next call sees
// counter >= MaxConsecutiveFailures and is blocked by the breaker.
// Failed attempts leave history available and increment the breaker.
for i := range MaxConsecutiveFailures {
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonPreventive, "")
require.NoError(t, err, "iteration %d", i)
assert.True(t, res.Compacted, "iteration %d should still attempt", i)
assert.False(t, res.Compacted, "iteration %d must preserve history", i)
// Add new turns so the next iteration has something to compact.
sess.Append(session.UserMessageEntry("follow-up"))
sess.Append(session.AssistantMessageEntry("more reply"))
@@ -429,3 +411,81 @@ func longSessionWith(agentID, key string) *session.Session {
}
return sess
}
func TestCommittedObserverSeesCommittedHistoryAndCannotChangeResult(t *testing.T) {
for _, mode := range []string{"success", "panic", "skip", "failure"} {
t.Run(mode, func(t *testing.T) {
sess := longSession()
defer sess.Close()
mgr := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: "summary"}, Model: "m", Timeout: time.Second}, PreserveTurns: 4}
if mode == "skip" {
mgr.Summarizer = nil
}
if mode == "failure" {
mgr.Summarizer.Provider = &fakeProvider{err: errors.New("unavailable")}
}
calls := 0
mgr.OnCommitted = func(ctx context.Context, event CommitNotification) {
calls++
if event.SessionID != sess.ID || event.TurnsCompacted == 0 || sess.View()[0].Type != session.EntryTypeCompaction {
t.Fatal(event, sess.View())
}
deadline, ok := ctx.Deadline()
if !ok || time.Until(deadline) > 2*time.Second {
t.Fatal("observer not bounded")
}
lock := mgr.lockFor(stableKey(sess))
if !lock.TryLock() {
t.Fatal("observer called under compaction lock")
}
lock.Unlock()
if mode == "panic" {
panic("observer failure")
}
}
result, err := mgr.MaybeCompact(context.Background(), sess, ReasonManual, "")
if err != nil {
t.Fatal(err)
}
expected := mode == "success" || mode == "panic"
if result.Compacted != expected || (calls == 1) != expected {
t.Fatal(result, calls)
}
})
}
}
func TestBackgroundCompactionJoinsCommittedObserver(t *testing.T) {
sess := longSession()
defer sess.Close()
entered, release := make(chan struct{}), make(chan struct{})
manager := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: "summary"}, Model: "m", Timeout: time.Second}, PreserveTurns: 4}
manager.OnCommitted = func(ctx context.Context, event CommitNotification) {
close(entered)
select {
case <-release:
case <-ctx.Done():
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := manager.MaybeCompactAsyncContext(ctx, sess, ReasonPreventive)
select {
case <-entered:
case <-ctx.Done():
t.Fatal("observer never entered")
}
select {
case <-done:
t.Fatal("background finished before observer joined")
default:
}
if !manager.HasInFlight(sess) {
t.Fatal("active observer not tracked")
}
close(release)
result, joined, err := manager.JoinInFlight(ctx, sess)
if err != nil || !joined || !result.Compacted || manager.HasInFlight(sess) {
t.Fatal(result, joined, err)
}
}
+29
View File
@@ -0,0 +1,29 @@
package compaction
import (
"context"
"errors"
"strings"
"unicode/utf8"
)
type guidanceKey struct{}
// WithGuidance binds immutable caller guidance to synchronous and asynchronous
// compaction derived from this context. It does not modify shared managers.
func WithGuidance(ctx context.Context, guidance string) (context.Context, error) {
if len(guidance) > 48<<10 || !utf8.ValidString(guidance) || strings.ContainsRune(guidance, 0) {
return ctx, errors.New("compaction guidance exceeds 48 KiB or is invalid UTF-8")
}
return context.WithValue(ctx, guidanceKey{}, guidance), nil
}
func guidanceFor(ctx context.Context, focus string) (string, error) {
guidance, _ := ctx.Value(guidanceKey{}).(string)
if len(focus) > 16<<10 || !utf8.ValidString(focus) || strings.ContainsRune(focus, 0) {
return "", errors.New("compaction focus exceeds 16 KiB or is invalid UTF-8")
}
if guidance == "" {
return focus, nil
}
return guidance + "\n\nCurrent compaction focus:\n" + focus, nil
}
+36
View File
@@ -0,0 +1,36 @@
package compaction
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestJoinRetainsCompletedResultUntilConsumed(t *testing.T) {
mgr := &Manager{Summarizer: &Summarizer{Provider: usageSummaryProvider{}, Model: "summary"}, PreserveTurns: 1}
sess := longSession()
done := mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonManual)
<-done
require.False(t, mgr.HasInFlight(sess), "completed producer is not running")
// Neither a legacy waiter nor another launch may erase an unconsumed result.
res, found := mgr.WaitForInFlight(sess, time.Second)
require.True(t, found)
require.True(t, res.Compacted)
require.Equal(t, done, mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonPreventive))
res, found, err := mgr.JoinInFlight(context.Background(), sess)
require.NoError(t, err)
require.True(t, found)
require.True(t, res.Compacted)
require.Len(t, res.Requests, 1)
_, found, err = mgr.JoinInFlight(context.Background(), sess)
require.NoError(t, err)
require.False(t, found)
next := mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonPreventive)
require.NotEqual(t, done, next)
<-next
_, found, err = mgr.JoinInFlight(context.Background(), sess)
require.NoError(t, err)
require.True(t, found)
}
+22
View File
@@ -0,0 +1,22 @@
package compaction
import (
"context"
"github.com/stretchr/testify/require"
"testing"
)
func TestFailedSummarisationPreservesEffectiveAndRawHistory(t *testing.T) {
sess := longSession()
before := sess.View()
raw := sess.Entries()
leaf := sess.LeafID()
manager := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: ""}, Model: "test"}, PreserveTurns: 4}
result, err := manager.MaybeCompact(context.Background(), sess, ReasonManual, "")
require.NoError(t, err)
require.False(t, result.Compacted)
require.NotEmpty(t, result.Skipped)
require.Equal(t, before, sess.View())
require.Equal(t, raw, sess.Entries())
require.Equal(t, leaf, sess.LeafID())
}
+35 -43
View File
@@ -18,25 +18,21 @@ var ErrEmptySummary = errors.New("compaction: empty summary returned")
// for compaction. The provider is expected to be the bundled Ollama in
// production but any LLMProvider works (used for tests).
type Summarizer struct {
Provider llm.LLMProvider
Model string // bare model id, e.g. "qwen2.5:3b-instruct"
Timeout time.Duration // per-call deadline; 0 → 60s
Route llm.CallRoute // identifies the independently selected provider client
Provider llm.LLMProvider
MaxOutputTokens int // 0 defaults to 4096; otherwise 1-32768
Model string // bare model id, e.g. "qwen2.5:3b-instruct"
Timeout time.Duration // per-call deadline; 0 → 60s
}
// Summarize sends entries through the configured provider and returns the
// trimmed, formatted summary text. additionalInstructions is appended to
// the prompt when non-empty (used by manual /compact <focus...>).
//
// The call wraps three fallback stages:
// 1. Full transcript — preferred; preserves all detail.
// 2. Small-only — drops oversized messages, keeps a note that they were
// elided. Triggered when stage 1 returns a context-overflow error
// or a stream error.
// 3. Placeholder — a static stub indicating compaction failed; never
// returns an error to the caller so the agent loop can continue.
//
// Each stage applies FormatCompactSummary to strip the analysis scratchpad
// and unwrap the summary block.
// A full transcript is attempted first. Overflow/stream failures may retry
// with oversized messages explicitly elided. If neither attempt produces a
// summary, return the error so the manager preserves effective history.
func (s *Summarizer) Summarize(ctx context.Context, entries []session.SessionEntry, additionalInstructions string) (string, error) {
return s.summarizeWithFallback(ctx, entries, additionalInstructions)
}
@@ -49,16 +45,8 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
}
stage1Err := err
// Context cancellation/deadline propagates up — the caller asked us to
// stop, so don't burn an extra provider call on stage 2 or paper over
// the cancel with a placeholder. This preserves the Manager's ability
// to classify cancellation/timeout distinctly from "compaction is
// genuinely broken; degrade gracefully".
//
// We also propagate a per-call deadline (Summarizer.Timeout firing while
// the parent ctx is still alive) — otherwise a per-call timeout would
// flow into stage 2/3, masking timeout as a placeholder. Manager
// classifies the wrapped DeadlineExceeded as Skipped: "timeout".
// Cancellation and per-call deadlines stop retries and retain their
// classification for the manager.
if ctxErr := ctx.Err(); ctxErr != nil || errors.Is(stage1Err, context.DeadlineExceeded) {
return "", stage1Err
}
@@ -67,7 +55,7 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
// buildSmallOnlyTranscript actually elides something — otherwise we'd
// be re-sending the same transcript with the same prompt against the
// same provider (predictable failure, wasted call). Fall through to
// stage 3 in that case.
// the final error in that case.
if isOverflowError(stage1Err) || isStreamError(stage1Err) {
small, droppedCount := buildSmallOnlyTranscript(entries)
if droppedCount > 0 {
@@ -79,9 +67,10 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
}
}
// Stage 3: placeholder. Never returns an error — the agent loop must
// be able to continue even if compaction is wholly broken.
return placeholderSummary(len(entries)), nil
if failure := errors.Join(stage1Err, err); failure != nil {
return "", failure
}
return "", ErrEmptySummary
}
// callOnce performs a single summarizer invocation against a pre-built
@@ -94,6 +83,16 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
// 5-minute TTL window hits cache_read for the prefix, dropping a few
// seconds off TTFT.
func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstructions string) (string, error) {
maxTokens := s.MaxOutputTokens
if maxTokens == 0 {
maxTokens = 4096
}
if maxTokens < 1 || maxTokens > 32768 {
return "", errors.New("summariser output token limit must be 1-32768")
}
if s.Provider == nil {
return "", errors.New("summariser provider unavailable")
}
systemPrompt, userMessage := BuildPromptParts(transcript, additionalInstructions)
timeout := s.Timeout
if timeout == 0 {
@@ -103,6 +102,7 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
defer cancel()
req := llm.ChatRequest{
Route: s.Route,
Model: s.Model,
Messages: []llm.Message{{Role: "user", Content: userMessage}},
// One cache-marked system part: providers that support caching
@@ -111,9 +111,9 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
SystemPromptParts: []llm.SystemPromptPart{
{Text: systemPrompt, Cache: true},
},
MaxTokens: 4096,
MaxTokens: maxTokens,
}
stream, err := s.Provider.ChatStream(callCtx, req)
stream, err := llm.ObserveChat(callCtx, req, llm.CallCompaction, s.Provider.ChatStream)
if err != nil {
return "", fmt.Errorf("compaction: chat stream: %w", err)
}
@@ -122,11 +122,17 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
for ev := range stream {
switch ev.Type {
case llm.EventTextDelta:
if len(ev.Text) > 256<<10-sb.Len() {
return "", errors.New("summariser response exceeds 256 KiB")
}
sb.WriteString(ev.Text)
case llm.EventError:
return "", fmt.Errorf("compaction: stream error: %w", ev.Error)
}
}
if err := callCtx.Err(); err != nil {
return "", err
}
out := strings.TrimSpace(sb.String())
if out == "" {
return "", ErrEmptySummary
@@ -161,20 +167,6 @@ func buildSmallOnlyTranscript(entries []session.SessionEntry) (string, int) {
return BuildTranscript(kept), dropped
}
// placeholderSummary is the stage-3 fallback. It must be a valid summary
// the model can pick up from — minimally describing what was elided so
// the next turn doesn't act as if the conversation was empty. The
// "compaction failed and the summary could not be generated" phrase is
// stable: Task 5's circuit breaker detects placeholders by string match
// on this fragment to count them as failures for breaker accounting.
func placeholderSummary(entryCount int) string {
return fmt.Sprintf(
"Summary:\nConversation history (%d entries) — compaction failed and the summary could not be generated. "+
"The conversation continues; refer to the recent preserved turns and ask the user for any context you need.",
entryCount,
)
}
// isOverflowError reports whether err looks like a "your prompt is too big"
// signal from any provider. Re-uses the overflow signature list rather
// than depending on package-level state.
+9 -24
View File
@@ -58,37 +58,26 @@ func TestSummarizerTrimsWhitespace(t *testing.T) {
assert.Equal(t, "summary text", got)
}
func TestSummarizerEmptyResponseFallsBackToPlaceholder(t *testing.T) {
// An empty model response is no longer surfaced as ErrEmptySummary —
// the three-stage fallback chain catches it: stage 1 returns
// ErrEmptySummary internally, stage 2 is skipped (not an overflow or
// stream error), stage 3 emits the placeholder. The underlying
// ErrEmptySummary remains the failure mode that callOnce reports
// inside the chain; the user-facing contract is "always returns a
// usable summary string, never an error".
func TestSummarizerEmptyResponseReturnsError(t *testing.T) {
s := &Summarizer{
Provider: &fakeProvider{text: " \n "},
Model: "qwen2.5:3b-instruct",
Timeout: 5 * time.Second,
}
got, err := s.Summarize(context.Background(), []session.SessionEntry{session.UserMessageEntry("hi")}, "")
require.NoError(t, err)
assert.Contains(t, got, "compaction failed")
require.Error(t, err)
assert.Empty(t, got)
}
func TestSummarizerProviderErrorFallsBackToPlaceholder(t *testing.T) {
// A provider-level ChatStream error is wrapped as
// "compaction: chat stream: <err>" — neither an overflow nor a
// stream-event error, so stage 2 is skipped and we fall straight
// through to the placeholder. The agent loop sees no error.
func TestSummarizerProviderErrorReturnsError(t *testing.T) {
s := &Summarizer{
Provider: &fakeProvider{err: errors.New("ollama down")},
Model: "qwen2.5:3b-instruct",
Timeout: 5 * time.Second,
}
got, err := s.Summarize(context.Background(), []session.SessionEntry{session.UserMessageEntry("hi")}, "")
require.NoError(t, err)
assert.Contains(t, got, "compaction failed")
require.Error(t, err)
assert.Empty(t, got)
}
// flakyProvider returns ChatStream errors a configured number of times,
@@ -153,7 +142,7 @@ func TestSummarizeFallbackToSmallOnlyOnOverflow(t *testing.T) {
"second-stage success must produce the summary")
}
func TestSummarizeFallbackToPlaceholderWhenAllStagesFail(t *testing.T) {
func TestSummarizeReturnsErrorWhenAllStagesFail(t *testing.T) {
entries := []session.SessionEntry{session.UserMessageEntry("hi")}
s := &Summarizer{
Provider: &flakyProvider{failsRemaining: 99, successText: ""},
@@ -161,12 +150,8 @@ func TestSummarizeFallbackToPlaceholderWhenAllStagesFail(t *testing.T) {
Timeout: time.Second,
}
got, err := s.Summarize(context.Background(), entries, "")
require.NoError(t, err,
"placeholder stage must not surface the underlying error to caller")
assert.Contains(t, got, "Conversation history",
"placeholder must be a usable summary stub")
assert.Contains(t, got, "compaction failed",
"placeholder must indicate the failure so the next turn can adapt")
require.Error(t, err)
assert.Empty(t, got)
}
func TestSummarizePerCallTimeoutPropagates(t *testing.T) {
+33
View File
@@ -0,0 +1,33 @@
package compaction
import (
"context"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/stretchr/testify/require"
)
type usageSummaryProvider struct{ llmtest.Base }
func (usageSummaryProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Summary of prior work."}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1200, OutputTokens: 20}}
close(ch)
return ch, nil
}
func TestCompactionUsageRecordsAndBackgroundObserver(t *testing.T) {
ledger := &llm.UsageLedger{}
manager := &Manager{Summarizer: &Summarizer{Provider: usageSummaryProvider{}, Model: "summary-model"}, OnUsage: ledger.Record, PreserveTurns: 4}
result, err := manager.MaybeCompact(context.Background(), longSession(), ReasonManual, "")
require.NoError(t, err)
require.True(t, result.Compacted)
require.Len(t, result.Requests, 1)
require.Equal(t, llm.CallCompaction, result.Requests[0].Category)
require.Equal(t, "summary-model", result.Requests[0].Model)
<-manager.MaybeCompactAsync(longSession(), ReasonPreventive)
require.Len(t, ledger.Records(), 2)
require.Equal(t, 2400, ledger.Total().InputTokens)
}