Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 63 additions & 10 deletions pkgs/mcpx/internal/daemon/completion_ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ import (
"github.com/developing-today/code/pkgs/mcpx/internal/settings"
)

// #2387 handler contract: the limiter is consulted after shape
// validation and before the pool lookup, so a refused request is a 429
// naming the limit even for a server that does not exist -- it never
// reaches s.reg.Pool, let alone a pool lease or an upstream. An admitted
// request against the same unknown server is the pool's own 400, which
// is what makes the ordering observable.
// #2387 handler contract: for a server the registry knows, the
// limiter is consulted after shape validation and before the pool
// lookup, so a refused request is a 429 naming the limit -- it never
// reaches s.reg.Pool, let alone a pool lease or an upstream. An
// admitted request against a known server with no live pool is the
// pool's own 400, which is what makes the ordering observable.
// #6978 narrows the contract for names the registry does NOT know:
// they skip the limiter entirely (no buckets minted) and take the
// pool lookup's 400 directly.

func completeLimitSet(t *testing.T, perMinute, serverPerMinute string) *settings.Set {
t.Helper()
Expand All @@ -42,8 +45,21 @@ func postComplete(t *testing.T, s *Server, session string) *httptest.ResponseRec
return w
}

// knownNoPoolRegistry knows the name "nope" (a configured view) but
// holds no pool for it, so Pool("nope") still misses: an admitted
// request is observable as the pool lookup's 400, a refused one as
// the limiter's 429 -- the refusal-before-pool ordering, exercised
// on a KNOWN server as #6978 requires.
func knownNoPoolRegistry() *Registry {
return &Registry{
pools: map[string]*pool.Pool{},
views: map[string]*config.Resolved{"nope": {Namespace: "nope-ns"}},
order: []string{"nope"},
}
}

func TestHandleCompleteRateLimitRefusesBeforePool(t *testing.T) {
s := &Server{set: completeLimitSet(t, "1", "0"), reg: &Registry{}}
s := &Server{set: completeLimitSet(t, "1", "0"), reg: knownNoPoolRegistry()}
if w := postComplete(t, s, "sess-1"); w.Code != http.StatusBadRequest {
t.Fatalf("first request: got %d (%s), want 400 from the pool lookup it reached", w.Code, w.Body)
}
Expand All @@ -64,7 +80,7 @@ func TestHandleCompleteRateLimitRefusesBeforePool(t *testing.T) {
}

func TestHandleCompleteServerWindowBindsAcrossCallers(t *testing.T) {
s := &Server{set: completeLimitSet(t, "0", "1"), reg: &Registry{}}
s := &Server{set: completeLimitSet(t, "0", "1"), reg: knownNoPoolRegistry()}
if w := postComplete(t, s, "sess-1"); w.Code != http.StatusBadRequest {
t.Fatalf("first request: got %d, want 400 (admitted)", w.Code)
}
Expand All @@ -76,7 +92,7 @@ func TestHandleCompleteServerWindowBindsAcrossCallers(t *testing.T) {
}

func TestHandleCompleteRateLimitHotChangeAndZeroDisables(t *testing.T) {
s := &Server{set: completeLimitSet(t, "1", "1"), reg: &Registry{}}
s := &Server{set: completeLimitSet(t, "1", "1"), reg: knownNoPoolRegistry()}
_ = postComplete(t, s, "sess-1")
if w := postComplete(t, s, "sess-1"); w.Code != http.StatusTooManyRequests {
t.Fatalf("at limit 1: got %d, want 429", w.Code)
Expand Down Expand Up @@ -150,7 +166,7 @@ func TestCompletionCallerIgnoresSharedPID(t *testing.T) {
}

func TestHandleCompleteSharedPIDCallersDoNotRefuseEachOther(t *testing.T) {
s := &Server{set: completeLimitSet(t, "1", "0"), reg: &Registry{}}
s := &Server{set: completeLimitSet(t, "1", "0"), reg: knownNoPoolRegistry()}
post := func(call string) *httptest.ResponseRecorder {
body := `{"server":"nope","ref":{"type":"ref/prompt","name":"p"},` +
`"argument":{"name":"a","value":""}}`
Expand All @@ -177,3 +193,40 @@ func TestHandleCompleteSharedPIDCallersDoNotRefuseEachOther(t *testing.T) {
t.Fatalf("repeat same call id: got %d (%s), want 429 (same per-call key, limit 1)", w.Code, w.Body)
}
}

// #6978: a name the registry does not know must not mint limiter
// buckets. Repeated calls under one unknown name never trip a
// window, and many distinct unknown names leave the bucket count
// at zero -- bucket growth is not request-controlled.
func TestHandleCompleteUnknownServersMintNoLimiterBuckets(t *testing.T) {
s := &Server{set: completeLimitSet(t, "1", "1"), reg: &Registry{}}
post := func(server string) *httptest.ResponseRecorder {
body := `{"server":"` + server + `","ref":{"type":"ref/prompt","name":"p"},` +
`"argument":{"name":"a","value":""},"session":"sess-1"}`
req := httptest.NewRequest(http.MethodPost, "/v1/complete", strings.NewReader(body))
w := httptest.NewRecorder()
s.handleComplete(w, req)
return w
}
for i := 0; i < 3; i++ {
if w := post("nope"); w.Code != http.StatusBadRequest {
t.Fatalf("repeat unknown name call %d: got %d (%s), want 400 (pool miss, never a limiter 429)", i, w.Code, w.Body)
}
}
for i := 0; i < 20; i++ {
name := "bogus-" + strconv.Itoa(i)
if w := post(name); w.Code != http.StatusBadRequest {
t.Fatalf("distinct unknown name %q: got %d (%s), want 400", name, w.Code, w.Body)
}
}
if got := len(s.completeLimiter.buckets); got != 0 {
t.Fatalf("limiter buckets after unknown-name calls: got %d, want 0", got)
}
// The same name under a registry that KNOWS it is still limited:
// the gate is registry knowledge, not the name itself.
known := &Server{set: completeLimitSet(t, "1", "0"), reg: knownNoPoolRegistry()}
_ = postComplete(t, known, "sess-1")
if w := postComplete(t, known, "sess-1"); w.Code != http.StatusTooManyRequests {
t.Fatalf("known server second call: got %d, want 429", w.Code)
}
}
40 changes: 26 additions & 14 deletions pkgs/mcpx/internal/daemon/ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,20 +375,32 @@ func (s *Server) handleComplete(w http.ResponseWriter, r *http.Request) {
// review, PR #3730). CanonicalName is a registry map read -- it
// acquires no lease and wakes no upstream.
serverName := s.reg.CanonicalName(req.Server)
if refused := s.completeLimiter.admit([]limitCheck{
{
Name: "completion.perMinute",
What: "this caller and server",
Key: "caller\x00" + completionCaller(cc) + "\x00" + serverName,
Limit: cs.Int("completion.perMinute"),
},
{
Name: "completion.serverPerMinute",
What: "this server",
Key: "server\x00" + serverName,
Limit: cs.Int("completion.serverPerMinute"),
},
}); refused != nil {
// Unknown names skip the limiter entirely (#6978): CanonicalName
// returns a name the registry does not know unchanged, so admitting
// first would mint a fresh pair of limiter buckets per distinct
// bogus name -- bucket growth at request rate, and a per-server
// window that never binds anything. KnownServer is a registry map
// read (no lease, no upstream), so refusal-before-pool is unchanged
// for configured servers, and an unknown name falls through to the
// pool lookup's own 400 below without having counted anything.
var refused *limitCheck
if s.reg.KnownServer(req.Server) {
refused = s.completeLimiter.admit([]limitCheck{
{
Name: "completion.perMinute",
What: "this caller and server",
Key: "caller\x00" + completionCaller(cc) + "\x00" + serverName,
Limit: cs.Int("completion.perMinute"),
},
{
Name: "completion.serverPerMinute",
What: "this server",
Key: "server\x00" + serverName,
Limit: cs.Int("completion.serverPerMinute"),
},
})
}
if refused != nil {
writeErr(w, http.StatusTooManyRequests, fmt.Errorf(
"completion rate limit: %s allows %d per minute for %s",
refused.Name, refused.Limit, refused.What))
Expand Down
24 changes: 24 additions & 0 deletions pkgs/mcpx/internal/daemon/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -1638,6 +1638,30 @@ func (r *Registry) Pool(nameOrNS string) (*pool.Pool, bool) {
return nil, false
}

// KnownServer reports whether nameOrNS names a configured server --
// by its configured name, by a live pool under that name, or by the
// namespace of a configured server. It is a map read only, like
// CanonicalName: no lease, no upstream. Callers that must not act on
// names the registry does not know (the completion rate limiter,
// #6978) check this first, so a request naming nothing real is
// refused by the pool lookup without side effects.
func (r *Registry) KnownServer(nameOrNS string) bool {
r.mu.RLock()
defer r.mu.RUnlock()
if _, ok := r.pools[nameOrNS]; ok {
return true
}
if _, ok := r.views[nameOrNS]; ok {
return true
}
for _, name := range r.order {
if r.views[name].Namespace == nameOrNS {
return true
}
}
return false
}

// CanonicalName resolves a name-or-namespace the way Pool does and
// returns the configured server name, or the input unchanged when it
// names nothing. It is a map read only -- no lease, no upstream -- so
Expand Down
Loading