From 7725259edcb91a4c768c148142d50e0836f29add Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 12:32:22 -0600 Subject: [PATCH] fix(mcpx): match semantic feedback to exact tool identities The feedback store matched tools with a substring LIKE over the comma-joined tools_used list, while writers and readers spelled the same tool differently: the direct-call path records "server:tool", semantic ranking asks for "namespace.tool" (the view Function), and proxy capture stored the client's offered tool names as if they had been invoked. Feedback for one tool therefore leaked into longer names it is a prefix of, colon-spelled history never matched the dot-spelled query, and merely-offered tools collected execution evidence. - logstore canonicalises tool identities on write to the stable namespace.tool form (the historical colon spelling maps onto it), and matches whole list elements exactly at query time across both spellings, so legacy rows keep answering. - ToolFeedbackAdjustment and FindCorrelatedQueries accept alias identities; semantic ranking passes the server identity behind the view's function name, so call-path feedback and view-path ranking share one history. - Interactions gain a tools_offered list (column added in place for existing stores). Proxy capture records offered tools there: execution adjustments count invoked tools only, retrieval adjustments and correlated queries count invoked + offered. - New disposable-store tests cover exact matching (score A once; A_suffix and unrelated tools unchanged), the historical colon form, a namespace alias, offered-vs-invoked separation, and legacy rows preserved. Refs #13573. --- pkgs/mcpx/internal/daemon/registry.go | 10 +- pkgs/mcpx/internal/daemon/routes_proxy.go | 24 +-- pkgs/mcpx/internal/logstore/feedback.go | 171 +++++++++++++++--- .../logstore/feedback_identity_test.go | 159 ++++++++++++++++ pkgs/mcpx/internal/logstore/feedback_test.go | 2 +- 5 files changed, 323 insertions(+), 43 deletions(-) create mode 100644 pkgs/mcpx/internal/logstore/feedback_identity_test.go diff --git a/pkgs/mcpx/internal/daemon/registry.go b/pkgs/mcpx/internal/daemon/registry.go index 60f5bd3668..0377373756 100644 --- a/pkgs/mcpx/internal/daemon/registry.go +++ b/pkgs/mcpx/internal/daemon/registry.go @@ -2102,7 +2102,15 @@ func (r *Registry) SearchSemanticOpts(query string, limit int, semantic bool, ta // Combined hybrid score: 60% semantic cosine, 40% keyword combined := float32(kwScore)*0.4 + (sim*100.0)*0.6 if fb := r.FeedbackStore(); fb != nil { - execMult, retrMult := fb.ToolFeedbackAdjustment(t.Function) + // Feedback recorded by the call path is keyed by the server + // identity, while ranking asks by this view's function name; + // pass the server identity as an alias so both spellings of + // the same tool share one feedback history. + alias := "" + if t.Server != "" { + alias = t.Server + "." + t.Tool + } + execMult, retrMult := fb.ToolFeedbackAdjustment(t.Function, alias) combined = combined * retrMult * (0.5 + 0.5*execMult) } if combined > 15.0 || kwScore > 0 { diff --git a/pkgs/mcpx/internal/daemon/routes_proxy.go b/pkgs/mcpx/internal/daemon/routes_proxy.go index cb1ec03cdb..f8c652d2df 100644 --- a/pkgs/mcpx/internal/daemon/routes_proxy.go +++ b/pkgs/mcpx/internal/daemon/routes_proxy.go @@ -242,12 +242,12 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { if fb := s.reg.FeedbackStore(); fb != nil { outStr := fmt.Sprintf("mcpx reverse proxy: semantically injected %d tools for query %q.", len(discovered), query) _ = fb.RecordInteraction(logstore.InteractionRecord{ - TraceID: turnID, - Timestamp: time.Now(), - Source: "proxy", - Input: query, - Output: outStr, - ToolsUsed: toolNames, + TraceID: turnID, + Timestamp: time.Now(), + Source: "proxy", + Input: query, + Output: outStr, + ToolsOffered: toolNames, }) } @@ -302,12 +302,12 @@ func (s *Server) proxyToUpstream(w http.ResponseWriter, r *http.Request, upstrea if fb := s.reg.FeedbackStore(); fb != nil { _ = fb.RecordInteraction(logstore.InteractionRecord{ - TraceID: turnID, - Timestamp: time.Now(), - Source: "proxy", - Input: query, - Output: buf.String(), - ToolsUsed: toolNames, + TraceID: turnID, + Timestamp: time.Now(), + Source: "proxy", + Input: query, + Output: buf.String(), + ToolsOffered: toolNames, }) } } diff --git a/pkgs/mcpx/internal/logstore/feedback.go b/pkgs/mcpx/internal/logstore/feedback.go index 488110d3f3..2c62f1d96a 100644 --- a/pkgs/mcpx/internal/logstore/feedback.go +++ b/pkgs/mcpx/internal/logstore/feedback.go @@ -20,13 +20,17 @@ const ( // InteractionRecord represents an input/output turn or tool execution with its trace ID and feedback. type InteractionRecord struct { - TraceID string `json:"traceId"` - Timestamp time.Time `json:"timestamp"` - SessionID string `json:"sessionId,omitempty"` - Source string `json:"source"` // "proxy", "call", "task", etc. - Input string `json:"input"` - Output string `json:"output,omitempty"` - ToolsUsed []string `json:"toolsUsed,omitempty"` + TraceID string `json:"traceId"` + Timestamp time.Time `json:"timestamp"` + SessionID string `json:"sessionId,omitempty"` + Source string `json:"source"` // "proxy", "call", "task", etc. + Input string `json:"input"` + Output string `json:"output,omitempty"` + ToolsUsed []string `json:"toolsUsed,omitempty"` + // ToolsOffered names the tools presented for selection (e.g. by the + // reverse proxy) that were not necessarily invoked. Retrieval feedback + // may speak for offered tools; execution feedback never does. + ToolsOffered []string `json:"toolsOffered,omitempty"` Score *float64 `json:"score,omitempty"` // primary score (e.g. 1.0 = good, 0.0 = bad) Target string `json:"target,omitempty"` // "retrieval" vs "execution" RetrievalScore *float64 `json:"retrievalScore,omitempty"` // score for search / tool match relevance @@ -103,15 +107,104 @@ func NewFeedbackStore(path string) (*FeedbackStore, error) { _ = db.Close() return nil, err } + // Stores created before tools_offered existed gain the column in place; + // their rows keep NULL there, which reads back as "nothing offered". + if _, err := db.Exec(`ALTER TABLE interactions ADD COLUMN tools_offered TEXT`); err != nil && + !strings.Contains(err.Error(), "duplicate column") { + _ = db.Close() + return nil, err + } return &FeedbackStore{db: db}, nil } +// canonicalToolIdentity returns the stable spelling of a tool identity: the +// namespace/function form ("browser.screenshot") that semantic ranking asks +// for. The historical direct-call spelling ("browser:screenshot") canonicalises +// to it; the separator is the first ':' or '.', and the remainder is the tool +// name verbatim. Identities without a separator are kept as-is. +func canonicalToolIdentity(raw string) string { + s := strings.TrimSpace(raw) + if i := strings.Index(s, ":"); i > 0 { + return s[:i] + "." + s[i+1:] + } + return s +} + +// canonicalToolList canonicalises every identity in the list, dropping empty +// entries and duplicates while preserving order. +func canonicalToolList(in []string) []string { + var out []string + seen := make(map[string]bool, len(in)) + for _, raw := range in { + id := canonicalToolIdentity(raw) + if id == "" || seen[id] { + continue + } + seen[id] = true + out = append(out, id) + } + return out +} + +// toolIdentitySpellings returns every stored spelling equivalent to a tool +// identity: the canonical dot form and the historical colon form. Rows written +// before canonicalisation keep the colon spelling, so queries must accept both. +func toolIdentitySpellings(tool string) []string { + canon := canonicalToolIdentity(tool) + out := []string{canon} + if i := strings.Index(canon, "."); i > 0 { + if colon := canon[:i] + ":" + canon[i+1:]; colon != canon { + out = append(out, colon) + } + } + return out +} + +// toolIdentitySet is the union of spellings for a tool and its aliases (e.g. +// the server identity behind a view's function name). +func toolIdentitySet(tool string, aliases []string) []string { + var out []string + seen := make(map[string]bool) + for _, t := range append([]string{tool}, aliases...) { + if strings.TrimSpace(t) == "" { + continue + } + for _, s := range toolIdentitySpellings(t) { + if !seen[s] { + seen[s] = true + out = append(out, s) + } + } + } + return out +} + +// toolListMatch builds a SQL predicate (and its args) that matches a row when +// any of the given comma-joined list columns contains one of the identities as +// a whole element. instr() compares literally, so a tool never matches a +// longer name it is merely a prefix or substring of. +func toolListMatch(columns []string, identities []string) (string, []any) { + var preds []string + var args []any + for _, col := range columns { + for _, id := range identities { + preds = append(preds, "instr(',' || COALESCE("+col+", '') || ',', ',' || ? || ',') > 0") + args = append(args, id) + } + } + if len(preds) == 0 { + return "1 = 0", nil + } + return "(" + strings.Join(preds, " OR ") + ")", args +} + // RecordInteraction inserts or updates an interaction record. func (fs *FeedbackStore) RecordInteraction(rec InteractionRecord) error { fs.mu.Lock() defer fs.mu.Unlock() - toolsStr := strings.Join(rec.ToolsUsed, ",") + toolsStr := strings.Join(canonicalToolList(rec.ToolsUsed), ",") + offeredStr := strings.Join(canonicalToolList(rec.ToolsOffered), ",") tsMs := rec.Timestamp.UnixMilli() if tsMs == 0 { tsMs = time.Now().UnixMilli() @@ -126,11 +219,12 @@ func (fs *FeedbackStore) RecordInteraction(rec InteractionRecord) error { _, err := fs.db.Exec(` INSERT INTO interactions ( trace_id, ts_unix_ms, session_id, source, input_text, output_text, - tools_used, score, target, retrieval_score, execution_score, scores_json, feedback_notes, feedback_ts_unix_ms - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + tools_used, tools_offered, score, target, retrieval_score, execution_score, scores_json, feedback_notes, feedback_ts_unix_ms + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(trace_id) DO UPDATE SET output_text = COALESCE(excluded.output_text, interactions.output_text), tools_used = CASE WHEN excluded.tools_used != '' THEN excluded.tools_used ELSE interactions.tools_used END, + tools_offered = CASE WHEN excluded.tools_offered != '' THEN excluded.tools_offered ELSE interactions.tools_offered END, score = COALESCE(excluded.score, interactions.score), target = COALESCE(excluded.target, interactions.target), retrieval_score = COALESCE(excluded.retrieval_score, interactions.retrieval_score), @@ -139,7 +233,7 @@ func (fs *FeedbackStore) RecordInteraction(rec InteractionRecord) error { feedback_notes = COALESCE(excluded.feedback_notes, interactions.feedback_notes), feedback_ts_unix_ms = COALESCE(excluded.feedback_ts_unix_ms, interactions.feedback_ts_unix_ms) `, rec.TraceID, tsMs, rec.SessionID, rec.Source, rec.Input, rec.Output, - toolsStr, rec.Score, rec.Target, rec.RetrievalScore, rec.ExecutionScore, rec.ScoresJSON, rec.FeedbackNotes, fbMs) + toolsStr, offeredStr, rec.Score, rec.Target, rec.RetrievalScore, rec.ExecutionScore, rec.ScoresJSON, rec.FeedbackNotes, fbMs) return err } @@ -209,7 +303,7 @@ func (fs *FeedbackStore) Get(traceID string) (*InteractionRecord, error) { row := fs.db.QueryRow(` SELECT trace_id, ts_unix_ms, session_id, source, input_text, output_text, - tools_used, score, target, retrieval_score, execution_score, + tools_used, tools_offered, score, target, retrieval_score, execution_score, scores_json, feedback_notes, feedback_ts_unix_ms FROM interactions WHERE trace_id = ? `, traceID) @@ -217,12 +311,12 @@ func (fs *FeedbackStore) Get(traceID string) (*InteractionRecord, error) { var rec InteractionRecord var tsMs int64 var fbMs sql.NullInt64 - var toolsStr sql.NullString + var toolsStr, offeredStr sql.NullString var sessID, outText, tgt, sJSON, notes sql.NullString var sc, rSc, eSc sql.NullFloat64 err := row.Scan(&rec.TraceID, &tsMs, &sessID, &rec.Source, &rec.Input, &outText, - &toolsStr, &sc, &tgt, &rSc, &eSc, &sJSON, ¬es, &fbMs) + &toolsStr, &offeredStr, &sc, &tgt, &rSc, &eSc, &sJSON, ¬es, &fbMs) if err != nil { return nil, err } @@ -237,6 +331,9 @@ func (fs *FeedbackStore) Get(traceID string) (*InteractionRecord, error) { if toolsStr.Valid && toolsStr.String != "" { rec.ToolsUsed = strings.Split(toolsStr.String, ",") } + if offeredStr.Valid && offeredStr.String != "" { + rec.ToolsOffered = strings.Split(offeredStr.String, ",") + } if sc.Valid { v := sc.Float64 rec.Score = &v @@ -340,7 +437,7 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er query := fmt.Sprintf(` SELECT trace_id, ts_unix_ms, session_id, source, input_text, output_text, - tools_used, score, target, retrieval_score, execution_score, + tools_used, tools_offered, score, target, retrieval_score, execution_score, scores_json, feedback_notes, feedback_ts_unix_ms FROM interactions %s @@ -359,12 +456,12 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er var rec InteractionRecord var tsMs int64 var fbMs sql.NullInt64 - var toolsStr sql.NullString + var toolsStr, offeredStr sql.NullString var sessID, outText, tgt, sJSON, notes sql.NullString var sc, rSc, eSc sql.NullFloat64 if err := rows.Scan(&rec.TraceID, &tsMs, &sessID, &rec.Source, &rec.Input, &outText, - &toolsStr, &sc, &tgt, &rSc, &eSc, &sJSON, ¬es, &fbMs); err == nil { + &toolsStr, &offeredStr, &sc, &tgt, &rSc, &eSc, &sJSON, ¬es, &fbMs); err == nil { rec.Timestamp = time.UnixMilli(tsMs) if sessID.Valid { rec.SessionID = sessID.String @@ -375,6 +472,9 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er if toolsStr.Valid && toolsStr.String != "" { rec.ToolsUsed = strings.Split(toolsStr.String, ",") } + if offeredStr.Valid && offeredStr.String != "" { + rec.ToolsOffered = strings.Split(offeredStr.String, ",") + } if sc.Valid { v := sc.Float64 rec.Score = &v @@ -408,21 +508,30 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er // ToolFeedbackAdjustment computes the feedback multipliers for tool execution and retrieval. // Returns (executionMultiplier, retrievalMultiplier). -func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string) (execMult float32, retrMult float32) { +// +// The tool is matched by exact identity: whole elements of the stored lists, +// under the canonical spelling, the historical colon spelling, and any alias +// the caller supplies (semantic ranking passes the server identity behind a +// view's function name). Execution evidence counts only interactions that +// actually invoked the tool; retrieval evidence also counts interactions that +// merely offered it, since retrieval feedback judges the offered set. +func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string, aliases ...string) (execMult float32, retrMult float32) { fs.mu.RLock() defer fs.mu.RUnlock() execMult = 1.0 retrMult = 1.0 - likePattern := "%" + tool + "%" + identities := toolIdentitySet(tool, aliases) + invoked, invokedArgs := toolListMatch([]string{"tools_used"}, identities) + known, knownArgs := toolListMatch([]string{"tools_used", "tools_offered"}, identities) // 1. Tool execution score: how reliably this tool executes - rowExec := fs.db.QueryRow(` + rowExec := fs.db.QueryRow(fmt.Sprintf(` SELECT COUNT(*), AVG(COALESCE(execution_score, score)) FROM interactions - WHERE tools_used LIKE ? AND (execution_score IS NOT NULL OR target = 'execution' OR (target IS NULL AND score IS NOT NULL)) - `, likePattern) + WHERE %s AND (execution_score IS NOT NULL OR target = 'execution' OR (target IS NULL AND score IS NOT NULL)) + `, invoked), invokedArgs...) var eCount int var eAvg sql.NullFloat64 if err := rowExec.Scan(&eCount, &eAvg); err == nil && eCount > 0 && eAvg.Valid { @@ -431,11 +540,11 @@ func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string) (execMult float32, } // 2. Retrieval relevance score: how relevant this tool is when recommended for queries - rowRetr := fs.db.QueryRow(` + rowRetr := fs.db.QueryRow(fmt.Sprintf(` SELECT COUNT(*), AVG(COALESCE(retrieval_score, score)) FROM interactions - WHERE tools_used LIKE ? AND (retrieval_score IS NOT NULL OR target = 'retrieval') - `, likePattern) + WHERE %s AND (retrieval_score IS NOT NULL OR target = 'retrieval') + `, known), knownArgs...) var rCount int var rAvg sql.NullFloat64 if err := rowRetr.Scan(&rCount, &rAvg); err == nil && rCount > 0 && rAvg.Valid { @@ -447,20 +556,24 @@ func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string) (execMult float32, } // FindCorrelatedQueries returns user queries that resulted in high retrieval feedback for a tool. -func (fs *FeedbackStore) FindCorrelatedQueries(tool string, minScore float64) []string { +// Matching is by exact tool identity (see ToolFeedbackAdjustment), and offered +// tools count: a query that scored well for a tool it was offered is evidence +// the tool belongs with that query. +func (fs *FeedbackStore) FindCorrelatedQueries(tool string, minScore float64, aliases ...string) []string { fs.mu.RLock() defer fs.mu.RUnlock() - likePattern := "%" + tool + "%" + known, knownArgs := toolListMatch([]string{"tools_used", "tools_offered"}, toolIdentitySet(tool, aliases)) + args := append(append([]any{}, knownArgs...), minScore, minScore) rows, err := fs.db.Query(fmt.Sprintf(` SELECT input_text FROM interactions - WHERE tools_used LIKE ? + WHERE %s AND (retrieval_score >= ? OR (target = 'retrieval' AND score >= ?)) AND input_text != '' ORDER BY ts_unix_ms DESC LIMIT %d - `, defaults.RegistryLimit), likePattern, minScore, minScore) + `, known, defaults.RegistryLimit), args...) if err != nil { return nil } diff --git a/pkgs/mcpx/internal/logstore/feedback_identity_test.go b/pkgs/mcpx/internal/logstore/feedback_identity_test.go new file mode 100644 index 0000000000..bb9e6a5cb6 --- /dev/null +++ b/pkgs/mcpx/internal/logstore/feedback_identity_test.go @@ -0,0 +1,159 @@ +package logstore + +import ( + "path/filepath" + "testing" + "time" +) + +func newIdentityStore(t *testing.T) *FeedbackStore { + t.Helper() + fs, err := NewFeedbackStore(filepath.Join(t.TempDir(), "feedback.db")) + if err != nil { + t.Fatalf("NewFeedbackStore: %v", err) + } + t.Cleanup(func() { _ = fs.Close() }) + return fs +} + +func recordAndScore(t *testing.T, fs *FeedbackStore, rec InteractionRecord, params FeedbackParams) { + t.Helper() + if err := fs.RecordInteraction(rec); err != nil { + t.Fatalf("RecordInteraction(%s): %v", rec.TraceID, err) + } + params.TraceID = rec.TraceID + if err := fs.ProvideFeedback(params); err != nil { + t.Fatalf("ProvideFeedback(%s): %v", rec.TraceID, err) + } +} + +func f64(v float64) *float64 { return &v } + +// Scoring tool A must move A's multipliers only: a longer tool name that A is +// a prefix of, and unrelated tools, keep neutral multipliers — and A's own +// average must not be diluted by the longer tool's rows. +func TestToolIdentityExactMatching(t *testing.T) { + fs := newIdentityStore(t) + + recordAndScore(t, fs, InteractionRecord{ + TraceID: "a", Timestamp: time.Now(), Source: "call", + Input: "shot", ToolsUsed: []string{"browser.screenshot"}, + }, FeedbackParams{Score: 0.0, Target: TargetExecution, ExecutionScore: f64(0.0)}) + + recordAndScore(t, fs, InteractionRecord{ + TraceID: "a-suffix", Timestamp: time.Now(), Source: "call", + Input: "shot again", ToolsUsed: []string{"browser.screenshot2"}, + }, FeedbackParams{Score: 1.0, Target: TargetExecution, ExecutionScore: f64(1.0)}) + + recordAndScore(t, fs, InteractionRecord{ + TraceID: "other", Timestamp: time.Now(), Source: "call", + Input: "read", ToolsUsed: []string{"files.read"}, + }, FeedbackParams{Score: 1.0, Target: TargetExecution, ExecutionScore: f64(1.0)}) + + if exec, _ := fs.ToolFeedbackAdjustment("browser.screenshot"); exec != 0.5 { + t.Fatalf("browser.screenshot execMult = %v, want 0.5 (only its own 0.0 row)", exec) + } + if exec, _ := fs.ToolFeedbackAdjustment("browser.screenshot2"); exec != 1.5 { + t.Fatalf("browser.screenshot2 execMult = %v, want 1.5 (only its own 1.0 row)", exec) + } + if exec, retr := fs.ToolFeedbackAdjustment("browser.screensho"); exec != 1.0 || retr != 1.0 { + t.Fatalf("prefix-only name got (%v, %v), want neutral (1.0, 1.0)", exec, retr) + } + if exec, retr := fs.ToolFeedbackAdjustment("never.seen"); exec != 1.0 || retr != 1.0 { + t.Fatalf("unrelated tool got (%v, %v), want neutral (1.0, 1.0)", exec, retr) + } +} + +// Rows stored before canonicalisation keep the colon spelling; they must +// still answer queries in either spelling, and new records written with the +// colon spelling are stored canonically. +func TestToolIdentityHistoricalColonSpelling(t *testing.T) { + fs := newIdentityStore(t) + + // A legacy row, written straight to the table the way pre-change code did. + if _, err := fs.db.Exec(` + INSERT INTO interactions (trace_id, ts_unix_ms, source, input_text, tools_used, score, target, execution_score) + VALUES ('legacy', ?, 'call', 'shot', 'browser:screenshot', 0.0, 'execution', 0.0) + `, time.Now().UnixMilli()); err != nil { + t.Fatalf("insert legacy row: %v", err) + } + if exec, _ := fs.ToolFeedbackAdjustment("browser.screenshot"); exec != 0.5 { + t.Fatalf("dot query over colon row: execMult = %v, want 0.5", exec) + } + if exec, _ := fs.ToolFeedbackAdjustment("browser:screenshot"); exec != 0.5 { + t.Fatalf("colon query over colon row: execMult = %v, want 0.5", exec) + } + + // A new record written with the colon spelling is stored canonically. + if err := fs.RecordInteraction(InteractionRecord{ + TraceID: "new", Timestamp: time.Now(), Source: "call", + Input: "shot", ToolsUsed: []string{"browser:screenshot"}, + }); err != nil { + t.Fatalf("RecordInteraction: %v", err) + } + got, err := fs.Get("new") + if err != nil { + t.Fatalf("Get: %v", err) + } + if len(got.ToolsUsed) != 1 || got.ToolsUsed[0] != "browser.screenshot" { + t.Fatalf("stored identity = %v, want [browser.screenshot]", got.ToolsUsed) + } +} + +// A view's function name and the server identity behind it are aliases for +// the same tool: feedback recorded under the server spelling must answer a +// ranking query that supplies the alias, and must not leak to the view name +// without it. +func TestToolIdentityNamespaceAlias(t *testing.T) { + fs := newIdentityStore(t) + + recordAndScore(t, fs, InteractionRecord{ + TraceID: "srv", Timestamp: time.Now(), Source: "call", + Input: "shot", ToolsUsed: []string{"browser:screenshot"}, + }, FeedbackParams{Score: 1.0, Target: TargetRetrieval, RetrievalScore: f64(1.0)}) + + if _, retr := fs.ToolFeedbackAdjustment("chrome.screenshot", "browser.screenshot"); retr != 1.5 { + t.Fatalf("aliased query retrMult = %v, want 1.5", retr) + } + if _, retr := fs.ToolFeedbackAdjustment("chrome.screenshot"); retr != 1.0 { + t.Fatalf("unaliased query retrMult = %v, want neutral 1.0", retr) + } +} + +// Offered tools are not invocations: execution feedback on an interaction +// that only offered a tool must not move its execution multiplier, while +// retrieval feedback on the offered set does move the retrieval multiplier +// and feeds correlated queries. +func TestOfferedToolsAreNotInvocations(t *testing.T) { + fs := newIdentityStore(t) + + recordAndScore(t, fs, InteractionRecord{ + TraceID: "offered-exec", Timestamp: time.Now(), Source: "proxy", + Input: "take a screenshot", ToolsOffered: []string{"browser.screenshot"}, + }, FeedbackParams{Score: 0.0, Target: TargetExecution, ExecutionScore: f64(0.0)}) + + if exec, _ := fs.ToolFeedbackAdjustment("browser.screenshot"); exec != 1.0 { + t.Fatalf("offered-only execution feedback moved execMult to %v, want 1.0", exec) + } + + recordAndScore(t, fs, InteractionRecord{ + TraceID: "offered-retr", Timestamp: time.Now(), Source: "proxy", + Input: "take a screenshot", ToolsOffered: []string{"browser.screenshot"}, + }, FeedbackParams{Score: 1.0, Target: TargetRetrieval, RetrievalScore: f64(1.0)}) + + if _, retr := fs.ToolFeedbackAdjustment("browser.screenshot"); retr != 1.5 { + t.Fatalf("offered retrieval feedback: retrMult = %v, want 1.5", retr) + } + queries := fs.FindCorrelatedQueries("browser.screenshot", 0.8) + if len(queries) != 1 || queries[0] != "take a screenshot" { + t.Fatalf("correlated queries = %v, want [take a screenshot]", queries) + } + + got, err := fs.Get("offered-retr") + if err != nil { + t.Fatalf("Get: %v", err) + } + if len(got.ToolsUsed) != 0 || len(got.ToolsOffered) != 1 || got.ToolsOffered[0] != "browser.screenshot" { + t.Fatalf("round trip = used %v offered %v, want used [] offered [browser.screenshot]", got.ToolsUsed, got.ToolsOffered) + } +} diff --git a/pkgs/mcpx/internal/logstore/feedback_test.go b/pkgs/mcpx/internal/logstore/feedback_test.go index f4f398f8e5..dc1819fe54 100644 --- a/pkgs/mcpx/internal/logstore/feedback_test.go +++ b/pkgs/mcpx/internal/logstore/feedback_test.go @@ -32,7 +32,7 @@ func TestFeedbackStoreOperations(t *testing.T) { if err != nil { t.Fatalf("Get: %v", err) } - if got.Input != rec.Input || len(got.ToolsUsed) != 1 || got.ToolsUsed[0] != "browser:screenshot" { + if got.Input != rec.Input || len(got.ToolsUsed) != 1 || got.ToolsUsed[0] != "browser.screenshot" { t.Fatalf("unexpected record: %+v", got) } if got.Score != nil {