feat(diagnostics): pin a Playground request to one relay (#167)

Resolved against #170 so a relay pin clears the per-attempt WARP choice
(attemptUseWARP). The relay list is now credential-redacted, and a pin may
name a relay by its redacted URL.
This commit is contained in:
Ray authored and Jason Xu committed 2026-11-05 12:56:56 +08:00
1 parent 46eb13ea03
commit b296a61d0e
7 files changed
+235 -7

No files matched your search

+28 -5
View File
@@ -31,9 +31,10 @@ type DebugKeySelection struct {
// expressed in, which upstream key to test (Mode "auto" or "selected", the
// latter naming Tier and ID), and the request body itself.
type DebugInferenceRequest struct {
Protocol protocol.Protocol `json:"protocol"`
Key DebugKeySelection `json:"key,omitempty"`
Request map[string]any `json:"request"`
Protocol protocol.Protocol `json:"protocol"`
Key DebugKeySelection `json:"key,omitempty"`
Relay gateway.RelaySelection `json:"relay,omitempty"`
Request map[string]any `json:"request"`
}
// DebugInferenceResult is the outcome of a Playground request: the status and
@@ -49,6 +50,7 @@ type DebugInferenceResult struct {
Route modelcatalog.RouteDiagnostic `json:"route"`
SelectedKey *gateway.DebugKeyView `json:"selected_key,omitempty"`
KeyTest string `json:"key_test,omitempty"`
RelayTest string `json:"relay_test,omitempty"`
Response any `json:"response"`
}
@@ -59,11 +61,12 @@ func (a *Server) handleDebugModels(w http.ResponseWriter, _ *http.Request) {
models, metadata := a.manager.DebugModels()
catalog := a.manager.Resources().Models
keys := a.manager.DebugKeys()
relays := a.manager.DebugRelays()
a.mu.Lock()
last := a.lastInference
a.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last})
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "relays": relays, "last_inference": last})
}
// handleDebugInference runs a request through the gateway itself, in process
@@ -112,6 +115,23 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
return
}
}
if !input.Relay.Empty() {
known := false
for index, name := range a.manager.DebugRelays() {
if input.Relay.Index != nil && *input.Relay.Index != index {
continue
}
if input.Relay.Name != "" && input.Relay.Name != name {
continue
}
known = true
break
}
if !known {
writeAdminError(w, http.StatusBadRequest, "unknown_relay", "relay.index or relay.name does not match a configured relay")
return
}
}
route := a.manager.DebugRoute(model, input.Protocol)
if selectedKey != nil {
selected, routeErr := a.manager.DebugRouteForTier(model, selectedKey.Tier)
@@ -140,6 +160,9 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
return
}
request.Header.Set("Authorization", "Bearer "+cfg.FirstEnabledServerKey())
if !input.Relay.Empty() {
request = request.WithContext(gateway.WithRelayOverride(request.Context(), input.Relay))
}
if selectedKey != nil {
request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID}))
}
@@ -178,7 +201,7 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
result := DebugInferenceResult{
OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status,
DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route,
SelectedKey: selectedKey, KeyTest: keyTest, Response: raw,
SelectedKey: selectedKey, KeyTest: keyTest, RelayTest: trace.Proxy, Response: raw,
}
a.mu.Lock()
a.lastInference = &result
+28
View File
@@ -104,6 +104,7 @@ type anonymousCursor struct {
start int
offset int
used []bool
single bool
}
// anonymousPool builds one anonymous node per proxy transport, or an empty
@@ -153,6 +154,24 @@ func (p *anonymousNodes) HasPool() bool {
// CursorFor returns a cursor whose first node is stable for a non-empty
// affinity key, keeping a conversation on one exit; an empty affinity rotates
// the starting node round-robin.
// CursorForProxy returns a cursor whose first Next hands back the node that
// uses proxy and whose second returns nil, so a relay-pinned diagnostic
// attempts exactly one exit. A proxy outside the pool yields the same
// single-shot cursor over no node, which the caller reports as an error.
func (p *anonymousNodes) CursorForProxy(proxy *proxyTransport) anonymousCursor {
c := anonymousCursor{pool: p, offset: len(p.nodes), single: true}
if p == nil || proxy == nil {
return c
}
for i, node := range p.nodes {
if node.proxy == proxy {
c.start = i
return c
}
}
return c
}
func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor {
if p == nil || len(p.nodes) == 0 {
return anonymousCursor{pool: p}
@@ -302,6 +321,15 @@ func (c *anonymousCursor) Next() *anonymousNode {
if c.used == nil {
c.used = make([]bool, n)
}
if c.single {
index := c.start
c.single = false
c.offset = n
if index < 0 || index >= n {
return nil
}
return c.pool.nodes[index]
}
now := time.Now().UnixNano()
isBlocked := func(node *anonymousNode) bool {
return node.proxy != nil && node.proxy.blockedUntil.Load() > now
+9
View File
@@ -586,6 +586,15 @@ type DebugKeyView struct {
CooldownUntil *time.Time `json:"cooldown_until,omitempty"`
}
// DebugRelays lists the anonymous relays in pool order for the Playground.
func (m *RuntimeController) DebugRelays() []string {
rt := m.current.Load()
if rt == nil || rt.gateway == nil {
return nil
}
return rt.gateway.RelayNames()
}
// DebugKeys lists every configured upstream key per tier so the Playground can
// offer an explicit per-key test target.
func (m *RuntimeController) DebugKeys() map[string][]DebugKeyView {
+125 -1
View File
@@ -59,6 +59,87 @@ func WithDebugKeyOverride(ctx context.Context, override DebugKeyOverride) contex
return context.WithValue(WithDiagnosticRequest(ctx), debugKeyOverrideContextKey{}, override)
}
// RelaySelection names one configured upstream relay (proxy) so a diagnostic
// request can be pinned to it. Index is the position in the configured proxy
// list, Name is the proxy URL; supplying both requires them to agree. Either
// alone is enough, and an empty selection means normal routing.
type RelaySelection struct {
Index *int `json:"index,omitempty"`
Name string `json:"name,omitempty"`
}
// Empty reports whether the selection names no relay.
func (r RelaySelection) Empty() bool {
return r.Index == nil && r.Name == ""
}
type relayOverrideContextKey struct{}
// WithRelayOverride pins one inference request to a single configured relay,
// on every tier: the anonymous lane walks exactly that exit and a key request
// is sent through that proxy, each with a single attempt and no failover.
// Session minting, system prompt, tool shaping and the transport stay the
// production path. The request is marked diagnostic, so the pinned attempt
// changes no cooldown, proxy health or IP-block state and cannot poison the
// relays it is meant to measure.
func WithRelayOverride(ctx context.Context, selection RelaySelection) context.Context {
return context.WithValue(WithDiagnosticRequest(ctx), relayOverrideContextKey{}, selection)
}
func relayOverrideFrom(ctx context.Context) (RelaySelection, bool) {
selection, ok := ctx.Value(relayOverrideContextKey{}).(RelaySelection)
if !ok || selection.Empty() {
return RelaySelection{}, false
}
return selection, true
}
// RelayNames lists the configured relays in configuration order, with any
// credentials redacted, so a caller can name one by index or by URL.
func (g *Gateway) RelayNames() []string {
if g.transports == nil {
return nil
}
names := make([]string, 0, len(g.transports.items))
for _, transport := range g.transports.items {
if transport != nil {
names = append(names, config.RedactURL(transport.name))
}
}
return names
}
// RelayProxy resolves a selection against the configured proxies. It reports
// false when nothing matches, so a typo surfaces as an error instead of a
// silent fallback to normal routing.
func (g *Gateway) RelayProxy(selection RelaySelection) (*proxyTransport, bool) {
if g.transports == nil {
return nil, false
}
index := -1
if selection.Index != nil {
index = *selection.Index
if index < 0 || index >= len(g.transports.items) {
return nil, false
}
}
for i, transport := range g.transports.items {
if transport == nil {
continue
}
if index >= 0 && i != index {
continue
}
if selection.Name != "" && transport.name != selection.Name && config.RedactURL(transport.name) != selection.Name {
continue
}
return transport, true
}
return nil, false
}
var errRelayNotFound = errors.New("relay does not match any configured proxy")
func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) {
override, ok := ctx.Value(debugKeyOverrideContextKey{}).(DebugKeyOverride)
return override, ok && override.KeyID != ""
@@ -380,6 +461,18 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
limit = g.cfg.Retry.MaxAttempts
}
// A relay-pinned diagnostic sends exactly one attempt through the chosen
// exit, so the answer describes that relay alone. An unresolvable relay is
// an error rather than a silent fallback, because a typo would otherwise
// read as a relay verdict.
if selection, ok := relayOverrideFrom(ctx); ok {
proxy, found := g.RelayProxy(selection)
if !found {
return nil, errRelayNotFound, 0
}
cursor = g.anonymous.CursorForProxy(proxy)
limit = 1
}
proxies := 0
attempts := 0
rawBody := bodies[config.TierZen]
@@ -844,6 +937,9 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
setRequestShape(ctx, changed, toolRenames)
useWARP := !node.bound && g.usesWARP(route.ID, override.Tier, false)
proxy := nodes.Proxy(node)
if pinned, ok := g.relayPin(ctx, proxy); ok {
proxy, useWARP = pinned, false
}
if !useWARP {
if proxy == nil {
return nil, errors.New("selected upstream key has no proxy binding"), 0
@@ -924,7 +1020,13 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
}
setRequestShape(ctx, changed, toolRenames)
useWARP := g.usesWARP(route.ID, route.Tier, false)
for attempts < g.cfg.Retry.MaxAttempts {
// A relay-pinned diagnostic gets exactly one attempt: rotating keys would
// no longer describe the relay that was asked for.
attemptLimit := g.cfg.Retry.MaxAttempts
if _, pinned := relayOverrideFrom(ctx); pinned {
attemptLimit = 1
}
for attempts < attemptLimit {
if ctx.Err() != nil {
// Same guard as the anonymous loop: an exhausted request budget
// must not be spent rotating keys that were never really tried.
@@ -954,6 +1056,11 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
return nil, err, attempts
}
proxy := nodes.Proxy(node)
// A relay pin replaces the proxy the key is bound to, so a pinned
// diagnostic measures that relay alone.
if pinned, ok := g.relayPin(ctx, proxy); ok {
proxy, attemptUseWARP = pinned, false
}
if !attemptUseWARP {
if proxy == nil {
lastErr = errors.New("upstream key has no proxy binding")
@@ -1148,6 +1255,9 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route,
leg += strconv.Itoa(status)
}
leg += ":" + strconv.FormatInt(max(duration.Milliseconds(), 0), 10) + "ms"
if anonymous && proxy != nil {
leg += "@" + config.RedactURL(proxy.name)
}
meta.Legs = append(meta.Legs, leg)
}
if g.monitor == nil {
@@ -1487,3 +1597,17 @@ func projectID(project string) string {
func isNonRetryableClientResponse(resp *http.Response, err error) bool {
return err == nil && resp != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests
}
// relayPin returns the proxy a relay-pinned diagnostic names, and whether a
// pin applied. An unresolvable pin keeps the request on its normal proxy: the
// admin endpoint validates the selection before it reaches here.
func (g *Gateway) relayPin(ctx context.Context, current *proxyTransport) (*proxyTransport, bool) {
selection, ok := relayOverrideFrom(ctx)
if !ok {
return current, false
}
if pinned, found := g.RelayProxy(selection); found {
return pinned, true
}
return current, false
}
+11
View File
@@ -296,6 +296,17 @@
指定 Key 后只测试该 Key:不切换、不回退,也不改变冷却与代理健康。
</p>
</div>
<div class="field full">
<label for="play-relay" data-i18n="playground.relay">Relay</label>
<select id="play-relay">
<option value="auto" data-i18n="playground.relay.auto">
任意 Relay(正常路由)
</option>
</select>
<p class="section-caption" data-i18n="playground.relay.caption">
指定 Relay 后只经它发送一次尝试:真实 session、system prompt 与 tool shaping,不切换、不回退,也不改变冷却与代理健康。
</p>
</div>
</div>
<div class="field">
<label for="play-request" data-i18n="playground.request">请求 JSON</label>
+15
View File
@@ -209,6 +209,10 @@ const DICTIONARY = {
"playground.key.auto": "Automatic routing (anonymous / Tier fallback / Key rotation)",
"playground.key.caption":
"When a specific key is chosen, only that key is tried: no switch to another key, another Tier, or the anonymous channel, and no change to the key's cooldown state or the proxy's health.",
"playground.relay": "Relay",
"playground.relay.auto": "Any relay (normal routing)",
"playground.relay.caption":
"Pinning a relay sends exactly one attempt through it, with real session minting, system prompt and tool shaping: no failover, and no change to cooldown or proxy health.",
"playground.request": "Request JSON",
"playground.reset": "Reset sample",
"playground.run": "Send diagnostic request",
@@ -454,6 +458,7 @@ const DICTIONARY = {
"play.mode.selected": "Specified {0} key",
"play.mode.auto": "Automatic routing",
"play.testedKey": "Key tested",
"play.testedRelay": "Relay tested",
"play.keyVerdict": "Key verdict",
"play.keyVerdict.none": "Automatic routing has no dedicated verdict",
"play.key.usable": "Key usable",
@@ -781,6 +786,10 @@ const DICTIONARY = {
"playground.key.auto": "Định tuyến tự động (ẩn danh / dự phòng Tier / luân phiên Key)",
"playground.key.caption":
"Khi chọn một Key cụ thể, chỉ Key đó được thử: không chuyển sang Key khác, Tier khác hay kênh ẩn danh, và không làm thay đổi trạng thái cooldown của Key hay sức khoẻ của proxy.",
"playground.relay": "Relay",
"playground.relay.auto": "Mọi relay (định tuyến thường)",
"playground.relay.caption":
"Ghim một relay sẽ gửi đúng một lần thử qua nó, với session, system prompt và tool shaping thật: không failover, không đổi cooldown hay sức khoẻ proxy.",
"playground.request": "JSON của request",
"playground.reset": "Đặt lại mẫu",
"playground.run": "Gửi request chẩn đoán",
@@ -1027,6 +1036,7 @@ const DICTIONARY = {
"play.mode.selected": "Chỉ định Key {0}",
"play.mode.auto": "Định tuyến tự động",
"play.testedKey": "Key được thử",
"play.testedRelay": "Relay được thử",
"play.keyVerdict": "Kết luận về Key",
"play.keyVerdict.none": "Định tuyến tự động không có kết luận riêng",
"play.key.usable": "Key dùng được",
@@ -1364,6 +1374,10 @@ const DICTIONARY = {
"Instradamento automatico (anonimo / fallback Tier / rotazione chiavi)",
"playground.key.caption":
"Quando viene scelta una chiave specifica, si prova solo quella: nessun passaggio a un'altra chiave, a un altro Tier o al canale anonimo, e nessuna modifica allo stato di cooldown della chiave o all'integrità del proxy.",
"playground.relay": "Relay",
"playground.relay.auto": "Qualsiasi relay (routing normale)",
"playground.relay.caption":
"Fissare un relay invia esattamente un tentativo attraverso di esso, con sessione, system prompt e tool shaping reali: nessun failover, nessuna modifica a cooldown o integrità del proxy.",
"playground.request": "JSON della richiesta",
"playground.reset": "Reimposta esempio",
"playground.run": "Invia richiesta diagnostica",
@@ -1613,6 +1627,7 @@ const DICTIONARY = {
"play.mode.selected": "Chiave {0} specificata",
"play.mode.auto": "Instradamento automatico",
"play.testedKey": "Chiave testata",
"play.testedRelay": "Relay testato",
"play.keyVerdict": "Verdetto sulla chiave",
"play.keyVerdict.none": "L'instradamento automatico non ha un verdetto dedicato",
"play.key.usable": "Chiave utilizzabile",
+19 -1
View File
@@ -78,6 +78,19 @@ function renderKeys() {
else select.value = "auto";
}
function renderRelays() {
const select = $("#play-relay");
if (!select) return;
const selected = select.value;
select.replaceChildren();
select.append(el("option", { value: "auto", text: t("任意 Relay(正常路由)", "playground.relay.auto") }));
(store.get("debug")?.relays || []).forEach((name, index) => {
select.append(el("option", { value: String(index), text: `${index} · ${name}` }));
});
if (selected && [...select.options].some((option) => option.value === selected)) select.value = selected;
else select.value = "auto";
}
function renderModels() {
const select = $("#play-model");
const selected = select.value;
@@ -88,6 +101,7 @@ function renderModels() {
if (selected && [...select.options].some((option) => option.value === selected)) select.value = selected;
if (!$("#play-request").value.trim()) resetTemplate();
renderKeys();
renderRelays();
}
function showResult(result) {
@@ -119,6 +133,7 @@ function showResult(result) {
keyTest || t("自动路由未单独判定", "play.keyVerdict.none"),
result.key_test === "usable" ? "ok" : result.key_test ? "bad" : "",
],
[t("测试 Relay", "play.testedRelay"), result.relay_test || "—"],
[t("实际路由", "play.actualRoute"), routeLabel],
[t("原生协议", "play.nativeProtocol"), route.native_protocol || "—"],
[
@@ -143,6 +158,9 @@ async function run(event) {
toast(t(`请求 JSON 无效:${error.message}`, "toast.play.invalidJson", error.message), true);
return;
}
const relayValue = $("#play-relay")?.value || "auto";
const relayNames = store.get("debug")?.relays || [];
const relay = relayValue === "auto" ? undefined : { index: Number(relayValue), name: relayNames[Number(relayValue)] };
const keyValue = $("#play-key").value;
const key =
keyValue === "auto"
@@ -158,7 +176,7 @@ async function run(event) {
"lastPlayground",
await api("/api/debug/inference", {
method: "POST",
body: JSON.stringify({ protocol: $("#play-protocol").value, key, request }),
body: JSON.stringify({ protocol: $("#play-protocol").value, key, ...(relay ? { relay } : {}), request }),
}),
);
} catch (error) {