fix(pier): reserve session slots atomically and build servers outside router locks

- an unexported reserver (Reserve, Release) next to updater: the memory
  store reserves under its mutex, the Redis store in one Lua script
  (prune, SCARD, SET PX plus SADD); serveNew reserves instead of Count
  then Put and releases on a failed connect or initialize (A-WR-03)
- serveNew, lookup's rehydration and the stateless getServer build the
  SDK server with no router-wide lock held and insert or adopt under the
  lock afterwards, so a slow guard or database check no longer stalls
  the instance (A-WR-07)
This commit is contained in:
Jakub Zych
2026-10-23 15:56:57 +02:00
parent 2bf9dca603
commit c1c0c77ddc
5 changed files with 223 additions and 36 deletions

View File

@@ -136,43 +136,76 @@ func (sr *sessionRouter) serveNew(w http.ResponseWriter, r *http.Request, id Ide
return
}
ctx := r.Context()
n, err := sr.p.store.Count(ctx, id.Binding)
if err != nil {
sr.p.storeUnavailable(w, err)
return
}
if n >= sr.p.cfg.MaxPerBinding {
writeJSON(w, http.StatusTooManyRequests, map[string]any{"error": "too_many_sessions", "max_per_binding": sr.p.cfg.MaxPerBinding})
return
}
sid := rand.Text()
sr.mu.Lock()
ls, err := sr.connect(ctx, sid, id, nil)
if err == nil {
sr.local[sid] = ls
rec := Record{Binding: id.Binding, Created: time.Now().UTC()}
// The slot is reserved atomically before the server is built
// (A-WR-03); a store without Reserve falls back to Count then Put.
res, reserves := sr.p.store.(reserver)
if reserves {
ok, err := res.Reserve(ctx, id.Binding, sid, rec, sr.p.cfg.MaxPerBinding, sr.p.cfg.IdleTTL)
if err != nil {
sr.p.storeUnavailable(w, err)
return
}
if !ok {
sr.tooMany(w)
return
}
} else {
n, err := sr.p.store.Count(ctx, id.Binding)
if err != nil {
sr.p.storeUnavailable(w, err)
return
}
if n >= sr.p.cfg.MaxPerBinding {
sr.tooMany(w)
return
}
}
sr.mu.Unlock()
release := func() {
if reserves {
_ = res.Release(context.WithoutCancel(ctx), id.Binding, sid)
} else {
_ = sr.p.store.Delete(context.WithoutCancel(ctx), sid)
}
}
// The server is built with no router lock held: its guard checks may
// query a database (A-WR-07). The id is new, so nothing else holds it.
ls, err := sr.connect(ctx, sid, id, nil)
if err != nil {
release()
logger().Error("pier: session connect failed", "error", err)
http.Error(w, "failed connection", http.StatusInternalServerError)
return
}
if err := sr.p.store.Put(ctx, sid, Record{Binding: id.Binding, Created: ls.created}, sr.p.cfg.IdleTTL); err != nil {
sr.closeLocal(sid)
sr.p.storeUnavailable(w, err)
return
ls.created = rec.Created
sr.mu.Lock()
sr.local[sid] = ls
sr.mu.Unlock()
if !reserves {
if err := sr.p.store.Put(ctx, sid, rec, sr.p.cfg.IdleTTL); err != nil {
sr.closeLocal(sid)
sr.p.storeUnavailable(w, err)
return
}
}
logSession(logger(), "open", sid, id.Binding)
ls.transport.ServeHTTP(w, r)
if ls.ss.InitializeParams() == nil {
// initialize failed: nothing to keep (the SDK cleans up the same way).
_ = sr.p.store.Delete(ctx, sid)
// initialize failed: nothing to keep (the SDK cleans up the same
// way), and the reserved slot frees.
release()
sr.closeLocal(sid)
return
}
sr.persist(ctx, ls)
}
// tooMany answers 429 for an initialize past mcp.sessions.max_per_binding.
func (sr *sessionRouter) tooMany(w http.ResponseWriter) {
writeJSON(w, http.StatusTooManyRequests, map[string]any{"error": "too_many_sessions", "max_per_binding": sr.p.cfg.MaxPerBinding})
}
// serveEphemeral answers one request outside any session with the state
// the SDK synthesises for a pre-initialize request.
func (sr *sessionRouter) serveEphemeral(w http.ResponseWriter, r *http.Request, id Identity) {
@@ -259,33 +292,41 @@ func (sr *sessionRouter) lookup(w http.ResponseWriter, r *http.Request, id Ident
}
sr.mu.Lock()
ls := sr.local[sid]
sr.mu.Unlock()
if ls == nil {
if len(rec.State) == 0 {
sr.mu.Unlock()
http.Error(w, "session not found", http.StatusNotFound)
return nil, false
}
var state mcp.ServerSessionState
if err := json.Unmarshal(rec.State, &state); err != nil || state.InitializeParams == nil {
sr.mu.Unlock()
http.Error(w, "session not found", http.StatusNotFound)
return nil, false
}
ls, err = sr.connect(ctx, sid, id, &state)
// Rehydrate with no router lock held (A-WR-07), then insert unless
// a concurrent request of the same session got there first.
built, err := sr.connect(ctx, sid, id, &state)
if err != nil {
sr.mu.Unlock()
logger().Error("pier: session rehydrate failed", "error", err)
http.Error(w, "failed connection", http.StatusInternalServerError)
return nil, false
}
ls.created = rec.Created
built.created = rec.Created
if state.InitializedParams != nil {
ls.persisted.Store(true)
built.persisted.Store(true)
}
sr.mu.Lock()
if cur := sr.local[sid]; cur != nil {
sr.mu.Unlock()
_ = built.ss.Close()
ls = cur
} else {
sr.local[sid] = built
sr.mu.Unlock()
ls = built
logSession(logger(), "rehydrate", sid, id.Binding)
}
sr.local[sid] = ls
logSession(logger(), "rehydrate", sid, id.Binding)
}
sr.mu.Unlock()
ls.mu.Lock()
ls.identity = id
ls.mu.Unlock()