Compare commits

...
Author SHA1 Message Date
BaaRai 1f558d8681 fix(agent): reject tool calls and tool_calls finish_reason in TestConnection (#526) 2026-11-27 01:08:46 +01:00
4851aeea5a fix(db): check rows.Err after iterating query results (#539)
ListLogs, ListLogsBefore and the two task_relations reads in the task
archive code never checked rows.Err(). When a result set fails partway
(connection drop, statement timeout), Next returns false and closes the
rows, so the later Close returns nil and the caller got a silently
truncated list: missing log lines, or an archive whose source tasks
are incomplete.


Claude-Session: https://claude.ai/code/session_01JNRiKGwr3P1LP1njD8FbR4

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
2026-11-27 00:15:26 +01:00
BaaRai f76810aa04 Merge pull request #522 from BaaRai/feat/knowledge-pack
feat(agent): add versioned knowledge pack and knowledge_lookup tool
2026-11-27 00:15:05 +01:00
5 changed files with 215 additions and 1 deletions
+74
View File
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
@@ -36,3 +37,76 @@ func TestConnectionSendsNoTools(t *testing.T) {
t.Fatalf("connection test sent %d tools, want none:\n%s", len(req.Tools), body)
}
}
// Regression for #526: Ollama returning a tool call (with or without accompanying
// text) or finish_reason="tool_calls", or whitespace-only content, must fail
// TestConnection instead of reporting Connected.
func TestConnectionRejectsToolCallsAndWhitespaceReplies(t *testing.T) {
cases := []struct {
name string
stream bool
statusBody string
wantErrSub string
}{
{
name: "ollama_nonstream_tool_call_with_text",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`,
wantErrSub: "tool call",
},
{
name: "ollama_nonstream_tool_call_only",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`,
wantErrSub: "tool call",
},
{
name: "ollama_nonstream_finish_reason_tool_calls_without_array",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":2,"total_tokens":22}}`,
wantErrSub: "tool call",
},
{
name: "ollama_stream_tool_call_with_text",
stream: true,
statusBody: strings.Join([]string{
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"role":"assistant","content":"OK"}}]}`,
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]}}]}`,
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
`data: [DONE]`,
``,
}, "\n\n"),
wantErrSub: "tool call",
},
{
name: "ollama_whitespace_only_content",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":" \n\t "},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":3,"total_tokens":23}}`,
wantErrSub: "no content",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tc.stream {
w.Header().Set("Content-Type", "text/event-stream")
} else {
w.Header().Set("Content-Type", "application/json")
}
_, _ = w.Write([]byte(tc.statusBody))
}))
defer srv.Close()
cfg := ConfigFrom("ollama", "baronllm", srv.URL+"/v1", "", "")
cfg.Stream = tc.stream
_, reply, err := TestConnection(context.Background(), cfg)
if err == nil {
t.Fatalf("expected TestConnection to reject %s, got Connected with reply=%q", tc.name, reply)
}
if !strings.Contains(strings.ToLower(err.Error()), tc.wantErrSub) {
t.Fatalf("unexpected error for %s: %v (want substring %q)", tc.name, err, tc.wantErrSub)
}
})
}
}
+57 -1
View File
@@ -14,6 +14,7 @@ import (
"context"
"fmt"
"io"
"iter"
"log/slog"
"net/http"
"net/url"
@@ -689,8 +690,9 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
// budget to emit OK cleanly (finish=stop).
// EscalateMaxTokens stays false: don't raise the cap and retry on truncation, to
// avoid burning tokens in a resume loop.
probe := &connTestProvider{inner: prov}
reply, err := agentcore.Run(ctx, agentcore.Options{
Provider: prov,
Provider: probe,
SystemPrompt: []string{"You are a connection test. Just output the two characters OK — no thinking, no explanation, nothing else."},
Tools: []actool.CoreTool{}, // not nil: nil means the SDK's unconfined file and shell tools
PermissionMode: acperm.ModeBypass,
@@ -712,6 +714,12 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
}
return lat, "", err
}
// Reject tool-call replies (#526): the connection test asks for plain text
// with no tools; a model answering with a tool call or tool_calls/tool_use
// finish reason must not be reported as Connected even if it also emitted text.
if probe.sawToolCall || isToolCallStopReason(probe.stopReason) {
return lat, "", fmt.Errorf("the model returned a tool call instead of a text reply (finish_reason=%q)", probe.stopReason)
}
// err==nil is not enough: requests that go through while the model emits nothing
// at all really happen (thinking burned the whole budget, the body got swallowed
// by a safety policy, a compatibility layer dropped the content). Such a config
@@ -723,3 +731,51 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
}
return lat, reply, nil
}
// connTestProvider observes the raw provider response during TestConnection so
// tool-call replies and tool_calls/tool_use stop reasons are rejected (#526).
type connTestProvider struct {
inner llm.Provider
sawToolCall bool
stopReason string
}
func (p *connTestProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
for ev, err := range p.inner.Stream(ctx, req) {
if err == nil {
if ev.Type == llm.SEToolUseStart {
p.sawToolCall = true
}
if ev.StopReason != "" {
p.stopReason = ev.StopReason
}
}
if !yield(ev, err) {
return
}
}
}
}
func (p *connTestProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
msg, stopReason, usage, err := p.inner.Complete(ctx, req)
if err == nil {
if len(msg.ToolUses()) > 0 {
p.sawToolCall = true
}
if stopReason != "" {
p.stopReason = stopReason
}
}
return msg, stopReason, usage, err
}
func isToolCallStopReason(stopReason string) bool {
switch strings.ToLower(strings.TrimSpace(stopReason)) {
case "tool_use", "tool_calls":
return true
default:
return false
}
}
+6
View File
@@ -43,6 +43,9 @@ func (d *DB) RecentLogs(limit int) ([]*DBLog, error) {
}
out = append(out, l)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Reverse to oldest-first
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
@@ -70,6 +73,9 @@ func (d *DB) ListLogsBefore(beforeID int64, limit int) ([]*DBLog, error) {
}
out = append(out, l)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Reverse to oldest-first
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
+66
View File
@@ -0,0 +1,66 @@
package db
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"sync"
"testing"
"time"
)
type midStreamErrDriver struct{}
type midStreamErrConn struct{}
type midStreamErrRows struct{ n int }
func (midStreamErrDriver) Open(string) (driver.Conn, error) { return midStreamErrConn{}, nil }
func (midStreamErrConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("unused") }
func (midStreamErrConn) Close() error { return nil }
func (midStreamErrConn) Begin() (driver.Tx, error) { return nil, errors.New("unused") }
func (midStreamErrConn) QueryContext(_ context.Context, _ string, _ []driver.NamedValue) (driver.Rows, error) {
return &midStreamErrRows{}, nil
}
func (r *midStreamErrRows) Columns() []string {
return []string{"id", "created_at", "level", "tag", "text"}
}
func (r *midStreamErrRows) Close() error { return nil }
func (r *midStreamErrRows) Next(dest []driver.Value) error {
if r.n == 0 {
r.n++
dest[0] = int64(1)
dest[1] = time.Now()
dest[2] = "info"
dest[3] = "test"
dest[4] = "first row"
return nil
}
if r.n == 1 {
r.n++
return errors.New("simulated mid-stream connection drop")
}
return io.EOF
}
var registerMidStreamErrDriverOnce sync.Once
func TestLogsMethodsReturnRowsErr(t *testing.T) {
registerMidStreamErrDriverOnce.Do(func() {
sql.Register("artex_test_mid_stream_err", midStreamErrDriver{})
})
raw, err := sql.Open("artex_test_mid_stream_err", "")
if err != nil {
t.Fatal(err)
}
defer raw.Close()
d := &DB{DB: raw}
if _, err := d.RecentLogs(10); err == nil {
t.Fatal("RecentLogs returned nil error on mid-stream rows.Next failure")
}
if _, err := d.ListLogsBefore(100, 10); err == nil {
t.Fatal("ListLogsBefore returned nil error on mid-stream rows.Next failure")
}
}
+12
View File
@@ -295,6 +295,12 @@ LIMIT 1`, taskID).Scan(&dependent)
}
sources = append(sources, id)
}
// Next closes rows on an error, after which Close returns nil: only Err
// reports a failure partway through the result set.
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
if err := rows.Close(); err != nil {
return nil, err
}
@@ -664,6 +670,12 @@ func (d *DB) snapshotTaskArchive(taskID int64, llmRecords io.Writer) (*TaskArchi
}
sources = append(sources, id)
}
// Next closes rows on an error, after which Close returns nil: only Err
// reports a failure partway through the result set.
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
if err := rows.Close(); err != nil {
return nil, err
}