From fe71e7b36dd3a58722701a4559cc00a6bbfb4939 Mon Sep 17 00:00:00 2001 From: sausheong Date: Tue, 9 Jun 2026 23:34:44 +0800 Subject: [PATCH] feat(runtime): bounded-synchronous KG recall in RunTurn --- runtime/runturn.go | 14 +++++ runtime/runturn_kg_test.go | 101 +++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) diff --git a/runtime/runturn.go b/runtime/runturn.go index 9b4e66d..8ea4165 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -7,6 +7,7 @@ import ( "fmt" "sort" "strings" + "time" "github.com/sausheong/harness/llm" "github.com/sausheong/harness/session" @@ -71,7 +72,20 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag sort.SliceStable(toolDefs, func(i, j int) bool { return toolDefs[i].Name < toolDefs[j].Name }) toolDefs, _ = r.LLM.NormalizeToolSchema(toolDefs) + // KG recall (first round of the exchange only): bounded-synchronous so a + // slow embedder cannot stall the turn. The hint is a non-cached suffix — + // it varies per query, so caching it would poison the static prefix cache. + var kgHint string + if r.KG != nil && (userMsg != "" || len(images) > 0) && r.KG.ShouldRecall(userMsg) { + rctx, cancel := context.WithTimeout(ctx, 800*time.Millisecond) + kgHint = r.KG.Recall(rctx, userMsg) + cancel() + } + parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}} + if kgHint != "" { + parts = append(parts, llm.SystemPromptPart{Text: kgHint, Cache: false}) + } req := llm.ChatRequest{ Model: r.Model, Messages: msgs, diff --git a/runtime/runturn_kg_test.go b/runtime/runturn_kg_test.go index bec0cd5..6421a74 100644 --- a/runtime/runturn_kg_test.go +++ b/runtime/runturn_kg_test.go @@ -1,9 +1,12 @@ package runtime import ( + "context" "encoding/json" "testing" + "time" + "github.com/sausheong/harness/llm" "github.com/sausheong/harness/session" "github.com/stretchr/testify/require" ) @@ -62,3 +65,101 @@ func TestSessionThread_SkipsUndecodableEntry(t *testing.T) { func TestSessionThread_Empty(t *testing.T) { require.Nil(t, sessionThread(nil)) } + +// fakeKG is a controllable KnowledgeGraph for RunTurn wiring tests. +type fakeKG struct { + shouldRecall bool + recallReturn string + recallDelay time.Duration + recallCalls int + recallQuery string + + ingestCalls int + ingestThreads [][]Message +} + +func (f *fakeKG) ShouldRecall(q string) bool { return f.shouldRecall } +func (f *fakeKG) Recall(ctx context.Context, q string) string { + f.recallCalls++ + f.recallQuery = q + if f.recallDelay > 0 { + select { + case <-time.After(f.recallDelay): + case <-ctx.Done(): + return "" + } + } + return f.recallReturn +} +func (f *fakeKG) Ingest(_ context.Context, thread []Message) { + f.ingestCalls++ + f.ingestThreads = append(f.ingestThreads, thread) +} + +func TestRunTurn_RecallInjectedIntoPrompt(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: true, recallReturn: "Relevant memories:\n- the user likes tea\n"} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + _, err := rt.RunTurn(context.Background(), "what do I like?", nil, nil) + require.NoError(t, err) + require.Equal(t, 1, kg.recallCalls) + require.Equal(t, "what do I like?", kg.recallQuery) + + require.GreaterOrEqual(t, len(captured), 2, "expected static + recall parts") + require.Equal(t, "STATIC", captured[0].Text) + require.True(t, captured[0].Cache) + require.Equal(t, "Relevant memories:\n- the user likes tea\n", captured[len(captured)-1].Text) + require.False(t, captured[len(captured)-1].Cache, "recall hint must NOT be cached") +} + +func TestRunTurn_NoRecallWhenShouldRecallFalse(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: false, recallReturn: "should not appear"} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + _, err := rt.RunTurn(context.Background(), "hi", nil, nil) + require.NoError(t, err) + require.Equal(t, 0, kg.recallCalls, "ShouldRecall false ⇒ Recall not called") + require.Len(t, captured, 1, "only the static part") + require.Equal(t, "STATIC", captured[0].Text) +} + +func TestRunTurn_NoRecallOnContinuationRound(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: true, recallReturn: "hint"} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + _, err := rt.RunTurn(context.Background(), "", nil, nil) + require.NoError(t, err) + require.Equal(t, 0, kg.recallCalls, "continuation round must not recall") + require.Len(t, captured, 1) +} + +func TestRunTurn_RecallTimeoutInjectsNothing(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: true, recallReturn: "late", recallDelay: 2 * time.Second} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + start := time.Now() + _, err := rt.RunTurn(context.Background(), "slow?", nil, nil) + require.NoError(t, err) + require.Less(t, time.Since(start), 1500*time.Millisecond, "recall must be bounded ~800ms") + require.Len(t, captured, 1, "timed-out recall injects nothing") +}