mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
feat: add probe profiles, dual-probe recovery, and thinking guard
Add a configurable quality-guard probe catalog (last-line / contains / regex markers). User-traffic degrade isolates immediately; restore only after a QUALITY_OK probe is healthy and includes thinking tokens. Missing thinking is a hard isolate even at normal TPS.
This commit is contained in:
1 parent
86ae605717
commit
71517cc609
13 files changed
+1189
-84
No files matched your search
@@ -0,0 +1,62 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const (
|
||||
MatchContains = "contains"
|
||||
MatchLastLine = "last_line"
|
||||
MatchRegex = "regex"
|
||||
)
|
||||
|
||||
func NormalizeMatchMode(mode string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(mode)) {
|
||||
case MatchLastLine, "last-line", "lastline":
|
||||
return MatchLastLine
|
||||
case MatchRegex, "regexp":
|
||||
return MatchRegex
|
||||
default:
|
||||
return MatchContains
|
||||
}
|
||||
}
|
||||
|
||||
func lastNonEmptyLine(text string) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
for i := len(lines) - 1; i >= 0; i-- {
|
||||
line := strings.TrimSpace(lines[i])
|
||||
if line != "" {
|
||||
return line
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// MatchExpected reports whether the probe body satisfies the expected marker.
|
||||
// An empty expected string always matches so throughput-only profiles can skip
|
||||
// content checks.
|
||||
func MatchExpected(text, expected, mode string) bool {
|
||||
expected = strings.TrimSpace(expected)
|
||||
if expected == "" {
|
||||
return true
|
||||
}
|
||||
text = strings.TrimRightFunc(text, unicode.IsSpace)
|
||||
switch NormalizeMatchMode(mode) {
|
||||
case MatchLastLine:
|
||||
line := lastNonEmptyLine(text)
|
||||
if line == "" {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(line, expected) || strings.Contains(line, expected)
|
||||
case MatchRegex:
|
||||
re, err := regexp.Compile(expected)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return re.MatchString(text)
|
||||
default:
|
||||
return strings.Contains(text, expected)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package egress
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMatchExpectedModes(t *testing.T) {
|
||||
text := "天空是蓝的,因为瑞利散射。\nQUALITY_OK\n"
|
||||
if !MatchExpected(text, "QUALITY_OK", MatchLastLine) {
|
||||
t.Fatal("last line QUALITY_OK should match")
|
||||
}
|
||||
if MatchExpected("hello\nNOT_OK", "QUALITY_OK", MatchLastLine) {
|
||||
t.Fatal("wrong last line must not match")
|
||||
}
|
||||
if !MatchExpected("prefix QUALITY_OK suffix", "QUALITY_OK", MatchContains) {
|
||||
t.Fatal("contains should match")
|
||||
}
|
||||
if !MatchExpected("done\nstatus=QUALITY_OK", "QUALITY_OK", MatchLastLine) {
|
||||
t.Fatal("last line containing the marker should match")
|
||||
}
|
||||
if !MatchExpected("alpha\nbeta QUALITY_OK", `QUALITY_OK$`, MatchRegex) {
|
||||
t.Fatal("regex should match")
|
||||
}
|
||||
if MatchExpected("nope", "[", MatchRegex) {
|
||||
t.Fatal("invalid regex must not match")
|
||||
}
|
||||
if !MatchExpected("anything", "", MatchContains) {
|
||||
t.Fatal("empty expected is always a match")
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ type QualityProbeInput struct {
|
||||
Model string
|
||||
Prompt string
|
||||
Expected string
|
||||
MatchMode string
|
||||
MaxOutputTokens int
|
||||
}
|
||||
|
||||
@@ -128,13 +129,15 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality
|
||||
input.Model = strings.TrimSpace(input.Model)
|
||||
input.Prompt = strings.TrimSpace(input.Prompt)
|
||||
input.Expected = strings.TrimSpace(input.Expected)
|
||||
rawMatchMode := strings.TrimSpace(input.MatchMode)
|
||||
input.MatchMode = NormalizeMatchMode(input.MatchMode)
|
||||
if input.Model == "" {
|
||||
return QualityProbeResult{}, fmt.Errorf("%w: model 必填", ErrInvalidInput)
|
||||
}
|
||||
if input.Prompt == "" {
|
||||
input.Prompt = DefaultQualityProbePrompt
|
||||
}
|
||||
if input.Expected == "" {
|
||||
if input.Expected == "" && rawMatchMode == "" {
|
||||
input.Expected = DefaultQualityProbeExpected
|
||||
}
|
||||
if len(input.Prompt) > MaxQualityProbePromptBytes || len(input.Expected) > MaxQualityProbeExpectedBytes {
|
||||
|
||||
@@ -184,7 +184,7 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e
|
||||
FirstTokenMS: firstTokenMS, DurationMS: durationMS, GenerationMS: generationMS,
|
||||
ChunkCount: chunkCount, OutputTokens: usage.OutputTokens, ReasoningTokens: usage.ReasoningTokens,
|
||||
VisibleTokens: visibleTokens, VisibleCharacters: visibleCharacters, OutputTokensPerSecond: outputTokensPerSecond,
|
||||
ExpectedMatched: strings.Contains(text, input.Expected), ResponseSHA256: hex.EncodeToString(digest[:]),
|
||||
ExpectedMatched: egressapp.MatchExpected(text, input.Expected, input.MatchMode), ResponseSHA256: hex.EncodeToString(digest[:]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,10 @@ func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
router.POST("/egress-nodes/:id/quality-test", h.testQuality)
|
||||
router.GET("/egress-quality-guard", h.qualityGuardStatus)
|
||||
router.PUT("/egress-quality-guard/config", h.updateQualityGuardConfig)
|
||||
router.GET("/egress-quality-guard/profiles", h.listQualityGuardProfiles)
|
||||
router.POST("/egress-quality-guard/profiles", h.createQualityGuardProfile)
|
||||
router.PUT("/egress-quality-guard/profiles/:id", h.updateQualityGuardProfile)
|
||||
router.DELETE("/egress-quality-guard/profiles/:id", h.deleteQualityGuardProfile)
|
||||
router.POST("/egress-quality-guard/nodes/:id/test", h.testQualityGuardNode)
|
||||
router.POST("/egress-nodes/:id/accounts", h.assignAccounts)
|
||||
router.DELETE("/egress-nodes/accounts", h.unassignAccounts)
|
||||
@@ -203,6 +207,10 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) {
|
||||
if state.Statistics.StartedAt > 0 {
|
||||
payload["statistics"] = state.Statistics
|
||||
}
|
||||
if profiles, err := loadProbeProfileFile(h.profilesPath()); err == nil {
|
||||
payload["activeProfileId"] = profiles.ActiveProfileID
|
||||
payload["profiles"] = profiles.summaries()
|
||||
}
|
||||
response.Success(c, http.StatusOK, payload)
|
||||
}
|
||||
|
||||
@@ -361,11 +369,24 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" || h.guardProbe.Prompt == "" || h.guardProbe.Expected == "" {
|
||||
if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用")
|
||||
return
|
||||
}
|
||||
value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, h.guardProbe)
|
||||
var request struct {
|
||||
ProfileID string `json:"profileId"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&request)
|
||||
input, err := h.resolveProbeInput(strings.TrimSpace(request.ProfileID))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(input.Prompt) == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用")
|
||||
return
|
||||
}
|
||||
value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, input)
|
||||
if err != nil {
|
||||
h.writeQualityProbeError(c, err)
|
||||
return
|
||||
|
||||
@@ -94,6 +94,37 @@ func TestWriteQualityProbeErrorIdentifiesMissingProbeAccount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualityGuardProfilesCRUDAndStatusOmitsPrompt(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
statePath := directory + "/state.json"
|
||||
configPath := directory + "/runtime-config.json"
|
||||
if err := os.WriteFile(statePath, []byte(`{"version":1,"guard":{"mode":"hybrid","model":"grok-4.5","node_ids":["8"]},"nodes":{}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := NewHandler(nil, statePath, configPath)
|
||||
|
||||
createRecorder := httptest.NewRecorder()
|
||||
createContext, _ := gin.CreateTestContext(createRecorder)
|
||||
createContext.Request = httptest.NewRequest("POST", "/egress-quality-guard/profiles", bytes.NewBufferString(`{"name":"自定义标记","prompt":"只输出 FLAG_OK","expectedText":"FLAG_OK","matchMode":"last_line","active":true}`))
|
||||
createContext.Request.Header.Set("Content-Type", "application/json")
|
||||
handler.createQualityGuardProfile(createContext)
|
||||
if createRecorder.Code != 200 || !strings.Contains(createRecorder.Body.String(), `"FLAG_OK"`) {
|
||||
t.Fatalf("create status=%d body=%s", createRecorder.Code, createRecorder.Body.String())
|
||||
}
|
||||
|
||||
statusRecorder := httptest.NewRecorder()
|
||||
statusContext, _ := gin.CreateTestContext(statusRecorder)
|
||||
statusContext.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil)
|
||||
handler.qualityGuardStatus(statusContext)
|
||||
body := statusRecorder.Body.String()
|
||||
if statusRecorder.Code != 200 || !strings.Contains(body, `"activeProfileId":"p-2"`) || !strings.Contains(body, `"has_expected":true`) {
|
||||
t.Fatalf("status=%d body=%s", statusRecorder.Code, body)
|
||||
}
|
||||
if strings.Contains(body, "只输出 FLAG_OK") || strings.Contains(body, "FLAG_OK") {
|
||||
t.Fatalf("status leaked probe prompt or marker: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateQualityGuardConfigWritesPrivateAtomicFile(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
statePath := directory + "/state.json"
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
egressapp "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/shared/response"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
profileThroughput = "throughput"
|
||||
profileQualityMarker = "quality-marker"
|
||||
maxCustomProfiles = 32
|
||||
)
|
||||
|
||||
type probeProfile struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
BuiltIn bool `json:"built_in"`
|
||||
Prompt string `json:"prompt"`
|
||||
ExpectedText string `json:"expected_text,omitempty"`
|
||||
MatchMode string `json:"match_mode"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
UpdatedAt float64 `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
type probeProfileFile struct {
|
||||
Version int `json:"version"`
|
||||
ActiveProfileID string `json:"active_profile_id"`
|
||||
NextID int `json:"next_id"`
|
||||
Profiles map[string]probeProfile `json:"profiles"`
|
||||
}
|
||||
|
||||
func builtinProbeProfiles() []probeProfile {
|
||||
return []probeProfile{
|
||||
{
|
||||
ID: profileQualityMarker,
|
||||
Name: "预期标记",
|
||||
BuiltIn: true,
|
||||
Prompt: "先用三点总结为什么天空呈蓝色,最后一行只输出 QUALITY_OK。",
|
||||
ExpectedText: "QUALITY_OK",
|
||||
MatchMode: egressapp.MatchLastLine,
|
||||
},
|
||||
{
|
||||
ID: profileThroughput,
|
||||
Name: "吞吐基线",
|
||||
BuiltIn: true,
|
||||
Prompt: "Write a detailed technical explanation of how TCP slow start works, at least 12 sentences, plain text only.",
|
||||
MatchMode: egressapp.MatchContains,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) profilesPath() string {
|
||||
if h.guardConfigPath == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(filepath.Dir(h.guardConfigPath), "profiles.json")
|
||||
}
|
||||
|
||||
func seedProbeProfileFile(data *probeProfileFile) {
|
||||
if data.Profiles == nil {
|
||||
data.Profiles = map[string]probeProfile{}
|
||||
}
|
||||
if data.Version == 0 {
|
||||
data.Version = 1
|
||||
}
|
||||
now := float64(time.Now().Unix())
|
||||
for _, builtin := range builtinProbeProfiles() {
|
||||
existing, ok := data.Profiles[builtin.ID]
|
||||
if !ok {
|
||||
builtin.UpdatedAt = now
|
||||
data.Profiles[builtin.ID] = builtin
|
||||
continue
|
||||
}
|
||||
if existing.BuiltIn {
|
||||
existing.Name = builtin.Name
|
||||
existing.Prompt = builtin.Prompt
|
||||
existing.ExpectedText = builtin.ExpectedText
|
||||
existing.MatchMode = builtin.MatchMode
|
||||
data.Profiles[builtin.ID] = existing
|
||||
}
|
||||
}
|
||||
if data.ActiveProfileID == "" {
|
||||
data.ActiveProfileID = profileQualityMarker
|
||||
}
|
||||
if _, ok := data.Profiles[data.ActiveProfileID]; !ok {
|
||||
data.ActiveProfileID = profileQualityMarker
|
||||
}
|
||||
if data.NextID < 1 {
|
||||
data.NextID = 1
|
||||
}
|
||||
}
|
||||
|
||||
func loadProbeProfileFile(path string) (probeProfileFile, error) {
|
||||
data := probeProfileFile{Version: 1, Profiles: map[string]probeProfile{}}
|
||||
if path == "" {
|
||||
seedProbeProfileFile(&data)
|
||||
return data, nil
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
seedProbeProfileFile(&data)
|
||||
return data, nil
|
||||
}
|
||||
return probeProfileFile{}, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &data); err != nil {
|
||||
return probeProfileFile{}, err
|
||||
}
|
||||
seedProbeProfileFile(&data)
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func saveProbeProfileFile(path string, data probeProfileFile) error {
|
||||
if path == "" {
|
||||
return errors.New("profiles path is empty")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".profiles-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
if err := temporary.Chmod(0o600); err != nil {
|
||||
_ = temporary.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := temporary.Write(raw); err != nil {
|
||||
_ = temporary.Close()
|
||||
return err
|
||||
}
|
||||
if err := temporary.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temporaryPath, path)
|
||||
}
|
||||
|
||||
func (data probeProfileFile) resolve(id string) (probeProfile, bool) {
|
||||
if id == "" {
|
||||
id = data.ActiveProfileID
|
||||
}
|
||||
profile, ok := data.Profiles[id]
|
||||
return profile, ok
|
||||
}
|
||||
|
||||
func (data probeProfileFile) summaries() []map[string]any {
|
||||
out := make([]map[string]any, 0, len(data.Profiles))
|
||||
for _, profile := range data.Profiles {
|
||||
out = append(out, map[string]any{
|
||||
"id": profile.ID,
|
||||
"name": profile.Name,
|
||||
"built_in": profile.BuiltIn,
|
||||
"match_mode": profile.MatchMode,
|
||||
"has_expected": strings.TrimSpace(profile.ExpectedText) != "",
|
||||
})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
leftBuiltIn, _ := out[i]["built_in"].(bool)
|
||||
rightBuiltIn, _ := out[j]["built_in"].(bool)
|
||||
if leftBuiltIn != rightBuiltIn {
|
||||
return leftBuiltIn
|
||||
}
|
||||
leftID, _ := out[i]["id"].(string)
|
||||
rightID, _ := out[j]["id"].(string)
|
||||
return leftID < rightID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func validateProbeProfile(profile *probeProfile, creating bool) error {
|
||||
profile.Name = strings.TrimSpace(profile.Name)
|
||||
profile.Prompt = strings.TrimSpace(profile.Prompt)
|
||||
profile.ExpectedText = strings.TrimSpace(profile.ExpectedText)
|
||||
profile.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode)
|
||||
if profile.Name == "" {
|
||||
return errors.New("方案名称不能为空")
|
||||
}
|
||||
if len(profile.Name) > 80 {
|
||||
return errors.New("方案名称不能超过 80 个字符")
|
||||
}
|
||||
if profile.Prompt == "" {
|
||||
return errors.New("探测 Prompt 不能为空")
|
||||
}
|
||||
if len(profile.Prompt) > egressapp.MaxQualityProbePromptBytes {
|
||||
return errors.New("探测 Prompt 过长")
|
||||
}
|
||||
if len(profile.ExpectedText) > egressapp.MaxQualityProbeExpectedBytes {
|
||||
return errors.New("预期标记过长")
|
||||
}
|
||||
if profile.MatchMode == egressapp.MatchRegex && profile.ExpectedText != "" {
|
||||
if _, err := regexp.Compile(profile.ExpectedText); err != nil {
|
||||
return fmt.Errorf("正则预期标记无效")
|
||||
}
|
||||
}
|
||||
if profile.MaxOutputTokens < 0 || profile.MaxOutputTokens > egressapp.MaxQualityProbeOutputTokens {
|
||||
return fmt.Errorf("方案最大输出需在 0 到 %d Token 之间", egressapp.MaxQualityProbeOutputTokens)
|
||||
}
|
||||
if creating && profile.BuiltIn {
|
||||
return errors.New("不能新建内置方案")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyProfile(base egressapp.QualityProbeInput, profile probeProfile) egressapp.QualityProbeInput {
|
||||
base.Prompt = profile.Prompt
|
||||
base.Expected = profile.ExpectedText
|
||||
base.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode)
|
||||
if profile.MaxOutputTokens > 0 {
|
||||
base.MaxOutputTokens = profile.MaxOutputTokens
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func (h *Handler) listQualityGuardProfiles(c *gin.Context) {
|
||||
data, err := loadProbeProfileFile(h.profilesPath())
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
items := make([]probeProfile, 0, len(data.Profiles))
|
||||
for _, profile := range data.Profiles {
|
||||
items = append(items, profile)
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].BuiltIn != items[j].BuiltIn {
|
||||
return items[i].BuiltIn
|
||||
}
|
||||
return items[i].ID < items[j].ID
|
||||
})
|
||||
response.Success(c, http.StatusOK, gin.H{
|
||||
"activeProfileId": data.ActiveProfileID,
|
||||
"items": items,
|
||||
})
|
||||
}
|
||||
|
||||
type probeProfileWriteRequest struct {
|
||||
Name string `json:"name"`
|
||||
Prompt string `json:"prompt"`
|
||||
ExpectedText string `json:"expectedText"`
|
||||
MatchMode string `json:"matchMode"`
|
||||
MaxOutputTokens int `json:"maxOutputTokens"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
func (h *Handler) createQualityGuardProfile(c *gin.Context) {
|
||||
path := h.profilesPath()
|
||||
if path == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读")
|
||||
return
|
||||
}
|
||||
var request probeProfileWriteRequest
|
||||
if c.ShouldBindJSON(&request) != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效")
|
||||
return
|
||||
}
|
||||
data, err := loadProbeProfileFile(path)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
custom := 0
|
||||
for _, profile := range data.Profiles {
|
||||
if !profile.BuiltIn {
|
||||
custom++
|
||||
}
|
||||
}
|
||||
if custom >= maxCustomProfiles {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", fmt.Sprintf("自定义方案最多 %d 个", maxCustomProfiles))
|
||||
return
|
||||
}
|
||||
profile := probeProfile{
|
||||
Name: request.Name, Prompt: request.Prompt, ExpectedText: request.ExpectedText,
|
||||
MatchMode: request.MatchMode, MaxOutputTokens: request.MaxOutputTokens,
|
||||
}
|
||||
if err := validateProbeProfile(&profile, true); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error())
|
||||
return
|
||||
}
|
||||
data.NextID++
|
||||
profile.ID = fmt.Sprintf("p-%d", data.NextID)
|
||||
profile.UpdatedAt = float64(time.Now().Unix())
|
||||
data.Profiles[profile.ID] = profile
|
||||
if request.Active {
|
||||
data.ActiveProfileID = profile.ID
|
||||
}
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, profile)
|
||||
}
|
||||
|
||||
func (h *Handler) updateQualityGuardProfile(c *gin.Context) {
|
||||
path := h.profilesPath()
|
||||
if path == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(c.Param("id"))
|
||||
var request probeProfileWriteRequest
|
||||
if c.ShouldBindJSON(&request) != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效")
|
||||
return
|
||||
}
|
||||
data, err := loadProbeProfileFile(path)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
existing, ok := data.Profiles[id]
|
||||
if !ok {
|
||||
response.Error(c, http.StatusNotFound, "notFound", "方案不存在")
|
||||
return
|
||||
}
|
||||
if existing.BuiltIn {
|
||||
if request.Active {
|
||||
data.ActiveProfileID = existing.ID
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, existing)
|
||||
return
|
||||
}
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能修改,请复制后另存")
|
||||
return
|
||||
}
|
||||
existing.Name = request.Name
|
||||
existing.Prompt = request.Prompt
|
||||
existing.ExpectedText = request.ExpectedText
|
||||
existing.MatchMode = request.MatchMode
|
||||
existing.MaxOutputTokens = request.MaxOutputTokens
|
||||
if err := validateProbeProfile(&existing, false); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error())
|
||||
return
|
||||
}
|
||||
existing.UpdatedAt = float64(time.Now().Unix())
|
||||
data.Profiles[id] = existing
|
||||
if request.Active {
|
||||
data.ActiveProfileID = id
|
||||
}
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, existing)
|
||||
}
|
||||
|
||||
func (h *Handler) deleteQualityGuardProfile(c *gin.Context) {
|
||||
path := h.profilesPath()
|
||||
if path == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(c.Param("id"))
|
||||
data, err := loadProbeProfileFile(path)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
existing, ok := data.Profiles[id]
|
||||
if !ok {
|
||||
response.Error(c, http.StatusNotFound, "notFound", "方案不存在")
|
||||
return
|
||||
}
|
||||
if existing.BuiltIn {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能删除")
|
||||
return
|
||||
}
|
||||
delete(data.Profiles, id)
|
||||
if data.ActiveProfileID == id {
|
||||
data.ActiveProfileID = profileQualityMarker
|
||||
}
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, gin.H{"deleted": true})
|
||||
}
|
||||
|
||||
func (h *Handler) resolveProbeInput(profileID string) (egressapp.QualityProbeInput, error) {
|
||||
input := h.guardProbe
|
||||
data, err := loadProbeProfileFile(h.profilesPath())
|
||||
if err != nil {
|
||||
return input, err
|
||||
}
|
||||
profile, ok := data.resolve(profileID)
|
||||
if !ok {
|
||||
if profileID != "" {
|
||||
return input, fmt.Errorf("方案不存在")
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
return applyProfile(input, profile), nil
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Pencil, Plus, Star, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { createProbeProfile, deleteProbeProfile, listProbeProfiles, updateProbeProfile, type ProbeProfile } from "@/features/quality-guard/quality-guard-api";
|
||||
|
||||
type Draft = {
|
||||
name: string;
|
||||
prompt: string;
|
||||
expectedText: string;
|
||||
matchMode: string;
|
||||
};
|
||||
|
||||
const emptyDraft = (): Draft => ({ name: "", prompt: "", expectedText: "", matchMode: "last_line" });
|
||||
|
||||
export function ProbeProfilesPanel() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = useState<ProbeProfile | null | undefined>(undefined);
|
||||
const [draft, setDraft] = useState<Draft>(emptyDraft());
|
||||
const [deleting, setDeleting] = useState<ProbeProfile | null>(null);
|
||||
const query = useQuery({ queryKey: ["quality-guard-profiles"], queryFn: listProbeProfiles });
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["quality-guard-profiles"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["quality-guard"] });
|
||||
};
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const payload = {
|
||||
name: draft.name.trim(),
|
||||
prompt: draft.prompt.trim(),
|
||||
expectedText: draft.expectedText.trim(),
|
||||
matchMode: draft.matchMode,
|
||||
};
|
||||
if (editing && !editing.built_in) {
|
||||
return updateProbeProfile(editing.id, payload);
|
||||
}
|
||||
return createProbeProfile(payload);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t("qualityGuard.profileSaved"));
|
||||
setEditing(undefined);
|
||||
invalidate();
|
||||
},
|
||||
onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")),
|
||||
});
|
||||
const activateMutation = useMutation({
|
||||
mutationFn: (profile: ProbeProfile) => updateProbeProfile(profile.id, {
|
||||
name: profile.name,
|
||||
prompt: profile.prompt,
|
||||
expectedText: profile.expected_text ?? "",
|
||||
matchMode: profile.match_mode,
|
||||
active: true,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
toast.success(t("qualityGuard.profileSaved"));
|
||||
invalidate();
|
||||
},
|
||||
onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")),
|
||||
});
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (profile: ProbeProfile) => deleteProbeProfile(profile.id),
|
||||
onSuccess: () => {
|
||||
toast.success(t("qualityGuard.profileDeleted"));
|
||||
setDeleting(null);
|
||||
invalidate();
|
||||
},
|
||||
onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")),
|
||||
});
|
||||
|
||||
const items = query.data?.items ?? [];
|
||||
const activeId = query.data?.activeProfileId;
|
||||
const readonly = Boolean(editing?.built_in);
|
||||
const matchLabel = (mode: string) => {
|
||||
if (mode === "last_line") return t("qualityGuard.profileMatchLastLine");
|
||||
if (mode === "regex") return t("qualityGuard.profileMatchRegex");
|
||||
return t("qualityGuard.profileMatchContains");
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="overflow-hidden rounded-lg bg-card">
|
||||
<div className="flex flex-col gap-2 border-b px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("qualityGuard.profilesTab")}</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t("qualityGuard.profilesHelp")}</p>
|
||||
</div>
|
||||
<Button type="button" size="sm" onClick={() => { setEditing(null); setDraft(emptyDraft()); }}>
|
||||
<Plus />{t("qualityGuard.profileCreate")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{items.map((profile) => {
|
||||
const active = profile.id === activeId;
|
||||
const marker = profile.expected_text
|
||||
? `${t("qualityGuard.profileExpected")} ${profile.expected_text} · ${matchLabel(profile.match_mode)}`
|
||||
: t("qualityGuard.profileNoExpected");
|
||||
return (
|
||||
<div key={profile.id} className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<strong className="text-sm">{profile.name}</strong>
|
||||
<Badge variant={profile.built_in ? "secondary" : "outline"}>{t(profile.built_in ? "qualityGuard.profileBuiltin" : "qualityGuard.profileCustom")}</Badge>
|
||||
{active ? <Badge>{t("qualityGuard.profileActive")}</Badge> : null}
|
||||
</div>
|
||||
<p className="mt-1 truncate text-xs text-muted-foreground">{marker}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{!active ? <Button type="button" variant="secondary" size="sm" disabled={activateMutation.isPending} onClick={() => activateMutation.mutate(profile)}><Star />{t("qualityGuard.profileActivate")}</Button> : null}
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => {
|
||||
setEditing(profile);
|
||||
setDraft({ name: profile.name, prompt: profile.prompt, expectedText: profile.expected_text ?? "", matchMode: profile.match_mode || "contains" });
|
||||
}}><Pencil />{t(profile.built_in ? "qualityGuard.profileView" : "qualityGuard.profileEdit")}</Button>
|
||||
{!profile.built_in ? <Button type="button" variant="ghost" size="sm" className="text-destructive hover:text-destructive" onClick={() => setDeleting(profile)}><Trash2 />{t("common.delete")}</Button> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Dialog open={editing !== undefined} onOpenChange={(open) => { if (!open && !saveMutation.isPending) setEditing(undefined); }}>
|
||||
<DialogContent className="max-h-[calc(100svh-2rem)] overflow-y-auto sm:max-w-[560px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editing ? t(readonly ? "qualityGuard.profileView" : "qualityGuard.profileEdit") : t("qualityGuard.profileCreate")}</DialogTitle>
|
||||
<DialogDescription>{t("qualityGuard.profilesHelp")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form className="space-y-3.5" onSubmit={(event) => { event.preventDefault(); if (!readonly) saveMutation.mutate(); }}>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="probe-profile-name">{t("qualityGuard.profileName")}</Label>
|
||||
<Input id="probe-profile-name" value={draft.name} disabled={readonly} onChange={(event) => setDraft({ ...draft, name: event.target.value })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>{t("qualityGuard.profileMatch")}</Label>
|
||||
<Select value={draft.matchMode} disabled={readonly} onValueChange={(matchMode) => setDraft({ ...draft, matchMode })}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="last_line">{t("qualityGuard.profileMatchLastLine")}</SelectItem>
|
||||
<SelectItem value="contains">{t("qualityGuard.profileMatchContains")}</SelectItem>
|
||||
<SelectItem value="regex">{t("qualityGuard.profileMatchRegex")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="probe-profile-expected">{t("qualityGuard.profileExpected")}</Label>
|
||||
<Input id="probe-profile-expected" value={draft.expectedText} disabled={readonly} onChange={(event) => setDraft({ ...draft, expectedText: event.target.value })} />
|
||||
<p className="text-xs text-muted-foreground">{t("qualityGuard.profileExpectedHelp")}</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="probe-profile-prompt">{t("qualityGuard.profilePrompt")}</Label>
|
||||
<Textarea id="probe-profile-prompt" value={draft.prompt} disabled={readonly} onChange={(event) => setDraft({ ...draft, prompt: event.target.value })} />
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="secondary" size="sm" onClick={() => setEditing(undefined)}>{t("common.cancel")}</Button>
|
||||
{readonly ? null : <Button type="submit" size="sm" disabled={!draft.name.trim() || !draft.prompt.trim() || saveMutation.isPending}>{saveMutation.isPending ? <Spinner /> : null}{t("common.save")}</Button>}
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog open={deleting !== null} onOpenChange={(open) => { if (!open && !deleteMutation.isPending) setDeleting(null); }}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("common.delete")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t("qualityGuard.profileDeleteConfirm", { name: deleting?.name ?? "" })}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>{t("common.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction className="bg-destructive text-white hover:bg-destructive/90" disabled={deleteMutation.isPending || !deleting} onClick={(event) => { event.preventDefault(); if (deleting) deleteMutation.mutate(deleting); }}>
|
||||
{deleteMutation.isPending ? <Spinner /> : null}{t("common.delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -56,6 +56,24 @@ export type QualityGuardStatistics = {
|
||||
actions: { quarantined: number; restored: number; suppressed: number };
|
||||
};
|
||||
|
||||
export type ProbeProfileSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
built_in: boolean;
|
||||
match_mode: string;
|
||||
has_expected: boolean;
|
||||
};
|
||||
|
||||
export type ProbeProfile = {
|
||||
id: string;
|
||||
name: string;
|
||||
built_in: boolean;
|
||||
prompt: string;
|
||||
expected_text?: string;
|
||||
match_mode: string;
|
||||
max_output_tokens?: number;
|
||||
};
|
||||
|
||||
export type QualityGuardStatus = {
|
||||
available: boolean;
|
||||
editable?: boolean;
|
||||
@@ -63,6 +81,8 @@ export type QualityGuardStatus = {
|
||||
updatedAt?: number;
|
||||
lastActiveCycleAt?: number;
|
||||
lastPassivePollAt?: number;
|
||||
activeProfileId?: string;
|
||||
profiles?: ProbeProfileSummary[];
|
||||
config?: {
|
||||
mode: "active" | "passive" | "hybrid";
|
||||
model: string;
|
||||
@@ -131,7 +151,11 @@ const decodeStatus = (value: unknown): QualityGuardStatus => {
|
||||
}
|
||||
return createObjectDecoder<QualityGuardStatus>("quality guard", {
|
||||
available: isBoolean, editable: isOptional(isBoolean), startedAt: isNumber, updatedAt: isNumber, lastActiveCycleAt: isNumber,
|
||||
lastPassivePollAt: isNumber, config: configValidator, nodes: isRecordOf(nodeStateValidator),
|
||||
lastPassivePollAt: isNumber, activeProfileId: isOptional(isString),
|
||||
profiles: isOptional(isArrayOf(hasShape({
|
||||
id: isString, name: isString, built_in: isBoolean, match_mode: isString, has_expected: isBoolean,
|
||||
}))),
|
||||
config: configValidator, nodes: isRecordOf(nodeStateValidator),
|
||||
protectedNodeIds: isOptional(isArrayOf(isString)),
|
||||
recentEvents: isArrayOf(eventValidator), statistics: isOptional(statisticsValidator),
|
||||
})(value);
|
||||
@@ -146,9 +170,39 @@ export function getQualityGuardStatus(): Promise<QualityGuardStatus> {
|
||||
return apiRequest("/api/admin/v1/egress-quality-guard", {}, decodeStatus);
|
||||
}
|
||||
|
||||
export function runQualityTest(nodeId: string, status: QualityGuardStatus): Promise<QualityTestResult> {
|
||||
export function runQualityTest(nodeId: string, status: QualityGuardStatus, profileId?: string): Promise<QualityTestResult> {
|
||||
if (!status.config) throw new Error("Quality guard configuration is unavailable");
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/nodes/${nodeId}/test`, { method: "POST" }, decodeQualityTest);
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/nodes/${nodeId}/test`, {
|
||||
method: "POST",
|
||||
body: profileId ? { profileId } : {},
|
||||
}, decodeQualityTest);
|
||||
}
|
||||
|
||||
const decodeProfile = createObjectDecoder<ProbeProfile>("probe profile", {
|
||||
id: isString, name: isString, built_in: isBoolean, prompt: isString,
|
||||
expected_text: isOptional(isString), match_mode: isString, max_output_tokens: isOptional(isNumber),
|
||||
});
|
||||
|
||||
export function listProbeProfiles(): Promise<{ activeProfileId: string; items: ProbeProfile[] }> {
|
||||
return apiRequest("/api/admin/v1/egress-quality-guard/profiles", {}, createObjectDecoder("probe profiles", {
|
||||
activeProfileId: isString,
|
||||
items: isArrayOf(hasShape({
|
||||
id: isString, name: isString, built_in: isBoolean, prompt: isString,
|
||||
expected_text: isOptional(isString), match_mode: isString, max_output_tokens: isOptional(isNumber),
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
export function createProbeProfile(input: { name: string; prompt: string; expectedText?: string; matchMode: string; active?: boolean }): Promise<ProbeProfile> {
|
||||
return apiRequest("/api/admin/v1/egress-quality-guard/profiles", { method: "POST", body: input }, decodeProfile);
|
||||
}
|
||||
|
||||
export function updateProbeProfile(id: string, input: { name: string; prompt: string; expectedText?: string; matchMode: string; active?: boolean }): Promise<ProbeProfile> {
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/profiles/${id}`, { method: "PUT", body: input }, decodeProfile);
|
||||
}
|
||||
|
||||
export function deleteProbeProfile(id: string): Promise<{ deleted: boolean }> {
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/profiles/${id}`, { method: "DELETE" }, createObjectDecoder("delete profile", { deleted: isBoolean }));
|
||||
}
|
||||
|
||||
export function updateQualityGuardPolicy(policy: QualityGuardPolicy): Promise<{ saved: boolean }> {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { Switch } from "@/components/ui/switch";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { DegradeAccountsPanel } from "@/features/quality-guard/degrade-accounts-panel";
|
||||
import { ProbeProfilesPanel } from "@/features/quality-guard/probe-profiles-panel";
|
||||
import { getQualityGuardStatus, runQualityTest, updateQualityGuardPolicy, type QualityGuardEvent, type QualityGuardNodeState, type QualityGuardPolicy, type QualityGuardStatistics, type QualityGuardStatus, type QualityTestResult } from "@/features/quality-guard/quality-guard-api";
|
||||
import { createEgressNode, deleteEgressNodes, listAllEgressNodes, updateEgressNode, updateEgressNodesEnabled, type EgressNodeDTO, type EgressNodeInput } from "@/features/settings/settings-api";
|
||||
import { ErrorState } from "@/shared/components/data-state";
|
||||
@@ -164,8 +165,12 @@ export function QualityGuardPage() {
|
||||
<Tabs defaultValue="nodes">
|
||||
<TabsList>
|
||||
<TabsTrigger value="nodes">{t("qualityGuard.nodesTab")}</TabsTrigger>
|
||||
<TabsTrigger value="profiles">{t("qualityGuard.profilesTab")}</TabsTrigger>
|
||||
<TabsTrigger value="accounts">{t("qualityGuard.degrade.tab")}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="profiles" className="mt-6">
|
||||
<ProbeProfilesPanel />
|
||||
</TabsContent>
|
||||
<TabsContent value="accounts" className="mt-6">
|
||||
<DegradeAccountsPanel
|
||||
softTPS={status?.config?.soft_tps}
|
||||
|
||||
@@ -478,10 +478,31 @@ const resources = {
|
||||
sources: { active: "主动探针", passive: "请求审计" }, quarantined: "已隔离", fixedFallback: "固定回退(受保护)", suspect: "可疑", healthy: "正常", pending: "待观测", probeFailed: "检测失败",
|
||||
events: "最近事件", noEvents: "暂无异常或恢复事件", eventTypes: { node_quarantined: "节点已隔离", node_restored: "节点已恢复", node_rotated: "节点已更换 IP", passive_audit_anomaly: "检测到异常请求" },
|
||||
statistics: "自动检测统计", statisticsSince: "自 {{time}} 开始累计,不含手动检测。", statisticsChecks: "有效检测总数", statisticsChecksHelp: "主动探测与有效被动审计", statisticsActive: "主动探测", statisticsActiveDetail: "正常 {{healthy}},错误 {{errors}}", statisticsPassive: "被动审计", statisticsPassiveDetail: "正常 {{healthy}},来自真实请求", statisticsTokens: "主动探测输出 Token", statisticsTokensHelp: "包含推理 Token,不代表代理流量", statisticsAnomalies: "异常命中", statisticsAnomalyDetail: "软异常 {{soft}},硬异常 {{hard}}", statisticsQuarantines: "执行隔离", statisticsActionDetail: "已恢复 {{restored}},受保护未隔离 {{suppressed}}",
|
||||
reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", passive_hard_tps: "请求速度超过硬阈值", passive_soft_tps: "请求速度连续超过软阈值", quality_probe_healthy: "模型质量检测恢复正常", expected_marker_missing: "响应标记缺失", insufficient_output_tokens: "输出 Token 不足", insufficient_visible_tokens: "可见 Token 不足", insufficient_generation_window: "有效生成窗口不足", probe_errors: "主动检测连续失败", probe_no_account: "暂无可调度账号,已延后复测", recovery_probe_error: "恢复检测失败", rotation_error: "更换 IP 失败" },
|
||||
reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", missing_thinking: "输出缺少 thinking", passive_hard_tps: "请求速度超过硬阈值", passive_soft_tps: "请求速度连续超过软阈值", quality_probe_healthy: "模型质量检测恢复正常", expected_marker_missing: "响应标记缺失", insufficient_output_tokens: "输出 Token 不足", insufficient_visible_tokens: "可见 Token 不足", insufficient_generation_window: "有效生成窗口不足", probe_errors: "主动检测连续失败", probe_no_account: "暂无可调度账号,已延后复测", recovery_probe_error: "恢复检测失败", rotation_error: "更换 IP 失败" },
|
||||
policy: "当前策略", editPolicy: "编辑策略", editPolicyTitle: "编辑质量守护策略", editPolicyDescription: "保存后由守护进程热加载,无需重启服务。", restoreDefaults: "恢复默认值", policySaved: "策略已保存,正在热加载", invalidPolicyValue: "数值超出允许范围", softThresholdMustBeLower: "软阈值必须低于硬阈值", activeIntervalSeconds: "主动检测间隔(秒)", passiveIntervalSeconds: "被动审计间隔(秒)", consecutiveSoft: "软阈值连续次数", consecutiveErrors: "检测错误连续次数", quarantineSeconds: "隔离时长(秒)", softThreshold: "软阈值", hardThreshold: "硬阈值", activeInterval: "主动间隔", passiveInterval: "审计间隔", quarantineDuration: "隔离时长", minimumNodes: "最少保留节点",
|
||||
unavailable: "质量守护尚未连接", unavailableHelp: "在 config.yaml 中启用 qualityGuard,并启动 quality-guard Compose profile 后,这里会显示实时状态。", testing: "正在检测节点质量", testComplete: "检测完成:{{speed}}", testFailed: "质量检测暂不可用,请稍后重试",
|
||||
nodesTab: "节点质量",
|
||||
profilesTab: "探针方案",
|
||||
profilesHelp: "主动质量探测用的 Prompt 与预期标记。标记缺失记为硬异常。",
|
||||
profileActive: "当前使用",
|
||||
profileBuiltin: "内置",
|
||||
profileCustom: "自定义",
|
||||
profileCreate: "新建方案",
|
||||
profileEdit: "编辑方案",
|
||||
profileView: "查看方案",
|
||||
profileName: "名称",
|
||||
profilePrompt: "探测 Prompt",
|
||||
profileExpected: "预期标记",
|
||||
profileExpectedHelp: "留空则只看 Token/s;有标记时短回复命中不因虚高 TPS 误杀",
|
||||
profileMatch: "匹配方式",
|
||||
profileMatchContains: "全文包含",
|
||||
profileMatchLastLine: "最后一行",
|
||||
profileMatchRegex: "正则",
|
||||
profileSaved: "方案已保存",
|
||||
profileDeleted: "方案已删除",
|
||||
profileDeleteConfirm: "将删除“{{name}}”。若正在使用会回退到预期标记。",
|
||||
profileActivate: "设为当前",
|
||||
profileNoExpected: "无预期标记",
|
||||
degrade: {
|
||||
tab: "降智账号", overview: "降智账号概览", series: "降智时序", nodes: "按出口节点",
|
||||
hits: "降智次数", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}",
|
||||
@@ -1489,8 +1510,29 @@ const resources = {
|
||||
media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", totalImages: "Total images", totalBytes: "Storage", pageSummary: "Showing {{count}} / {{total}}", openImage: "Open image {{id}}", deleteTitle: "Delete {{count}} selected images?", deleteDescription: "The image files and gallery records will be permanently removed, and existing image links will stop working. This cannot be undone.", deleted: "Deleted {{count}} images" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", statusProgress: "Status / progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", time: "Time", createdShort: "Created", completedShort: "Done", preview: "Preview video", previewTitle: "Video preview", previewUnavailable: "Local video unavailable", deleteTitle: "Delete {{count}} video records?", deleteDescription: "The task records and their local videos will be permanently removed, and existing video links will stop working. This cannot be undone.", deleted: "Deleted {{count}} video records", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } },
|
||||
auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" },
|
||||
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
|
||||
qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.",
|
||||
qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", missing_thinking: "Missing thinking tokens", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.",
|
||||
nodesTab: "Node quality",
|
||||
profilesTab: "Probe profiles",
|
||||
profilesHelp: "Prompt and expected marker for active quality probes. A missing marker is a hard failure.",
|
||||
profileActive: "In use",
|
||||
profileBuiltin: "Built-in",
|
||||
profileCustom: "Custom",
|
||||
profileCreate: "New profile",
|
||||
profileEdit: "Edit profile",
|
||||
profileView: "View profile",
|
||||
profileName: "Name",
|
||||
profilePrompt: "Probe prompt",
|
||||
profileExpected: "Expected marker",
|
||||
profileMatch: "Match mode",
|
||||
profileMatchContains: "Contains",
|
||||
profileMatchLastLine: "Last line",
|
||||
profileMatchRegex: "Regex",
|
||||
profileSaved: "Profile saved",
|
||||
profileDeleted: "Profile deleted",
|
||||
profileDeleteConfirm: "Delete “{{name}}”. The active profile falls back to the marker recipe.",
|
||||
profileActivate: "Use this",
|
||||
profileNoExpected: "No expected marker",
|
||||
profileExpectedHelp: "Leave empty to score throughput only.",
|
||||
degrade: {
|
||||
tab: "Degraded accounts", overview: "Degraded account overview", series: "Degrade timeline", nodes: "By egress node",
|
||||
hits: "Degrade hits", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}",
|
||||
|
||||
@@ -81,6 +81,7 @@ class Config:
|
||||
state_file: Path
|
||||
lock_file: Path
|
||||
runtime_config_file: Path
|
||||
profiles_file: Path = dataclasses.field(default_factory=lambda: Path("/var/lib/grok2api-quality-guard/profiles.json"))
|
||||
|
||||
@classmethod
|
||||
def from_bootstrap(cls, path: Path = BOOTSTRAP_FILE) -> "Config":
|
||||
@@ -132,6 +133,7 @@ class Config:
|
||||
state_file=Path("/var/lib/grok2api-quality-guard/state.json"),
|
||||
lock_file=Path("/var/lib/grok2api-quality-guard/guard.lock"),
|
||||
runtime_config_file=Path("/var/lib/grok2api-quality-guard/runtime-config.json"),
|
||||
profiles_file=Path("/var/lib/grok2api-quality-guard/profiles.json"),
|
||||
)
|
||||
config.validate()
|
||||
return config
|
||||
@@ -302,8 +304,9 @@ class ApiClient:
|
||||
result.add(node_id)
|
||||
return result
|
||||
|
||||
def quality_test(self, node_id: str) -> dict[str, Any]:
|
||||
return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/quality-test")
|
||||
def quality_test(self, node_id: str, profile_id: str = "") -> dict[str, Any]:
|
||||
body = {"profileId": profile_id} if profile_id else {}
|
||||
return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/quality-test", body or None)
|
||||
|
||||
def connectivity_test(self, node_id: str) -> dict[str, Any]:
|
||||
return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/test")
|
||||
@@ -350,8 +353,13 @@ class ApiClient:
|
||||
return payload
|
||||
|
||||
|
||||
def classify_result(result: dict[str, Any], config: Config) -> tuple[str, str]:
|
||||
if not bool(result.get("expectedMatched")):
|
||||
def classify_result(result: dict[str, Any], config: Config, profile: dict[str, Any] | None = None) -> tuple[str, str]:
|
||||
expected = ""
|
||||
if profile:
|
||||
expected = str(profile.get("expected_text") or profile.get("expected") or "").strip()
|
||||
if expected and not bool(result.get("expectedMatched")):
|
||||
return "hard", "expected_marker_missing"
|
||||
if profile is None and not bool(result.get("expectedMatched")):
|
||||
return "soft", "expected_marker_missing"
|
||||
output_tokens = int(result.get("outputTokens") or result.get("visibleTokens") or 0)
|
||||
speed_value = result.get("outputTokensPerSecond")
|
||||
@@ -362,8 +370,15 @@ def classify_result(result: dict[str, Any], config: Config) -> tuple[str, str]:
|
||||
generation_ms = int(result.get("generationMs") or 0)
|
||||
if generation_ms <= 0:
|
||||
generation_ms = max(0, int(result.get("durationMs") or 0) - int(result.get("firstTokenMs") or 0))
|
||||
# QUALITY_OK is a content marker, not a quality proof. Apply the same
|
||||
# token / window / TPS rules used for user-traffic audits.
|
||||
if output_tokens < 32:
|
||||
return "soft", "insufficient_output_tokens"
|
||||
reasoning_tokens = max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0))
|
||||
if output_tokens >= 64 and reasoning_tokens <= 0:
|
||||
return "hard", "missing_thinking"
|
||||
if config.fail_closed and generation_ms < config.min_generation_ms and speed >= config.soft_tps:
|
||||
return "hard", "buffered_burst"
|
||||
if config.fail_closed and generation_ms < config.min_generation_ms:
|
||||
return "soft", "insufficient_generation_window"
|
||||
if speed >= config.hard_tps:
|
||||
@@ -373,6 +388,35 @@ def classify_result(result: dict[str, Any], config: Config) -> tuple[str, str]:
|
||||
return "healthy", "within_threshold"
|
||||
|
||||
|
||||
def load_probe_profiles(path: Path) -> dict[str, Any]:
|
||||
data = {"version": 1, "active_profile_id": "quality-marker", "profiles": {}}
|
||||
try:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
loaded = json.load(handle)
|
||||
if isinstance(loaded, dict):
|
||||
data.update(loaded)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
profiles = data.get("profiles")
|
||||
if not isinstance(profiles, dict):
|
||||
profiles = {}
|
||||
data["profiles"] = profiles
|
||||
return data
|
||||
|
||||
|
||||
def resolve_probe_profile(path: Path, profile_id: str = "") -> tuple[str, dict[str, Any] | None]:
|
||||
data = load_probe_profiles(path)
|
||||
profiles = data.get("profiles") if isinstance(data.get("profiles"), dict) else {}
|
||||
active = str(data.get("active_profile_id") or "quality-marker")
|
||||
chosen = str(profile_id or active)
|
||||
profile = profiles.get(chosen)
|
||||
if isinstance(profile, dict):
|
||||
return chosen, profile
|
||||
return chosen, None
|
||||
|
||||
|
||||
def classify_audit(value: dict[str, Any], config: Config) -> tuple[str, str, float, int]:
|
||||
if value.get("provider") != "grok_build" or not bool(value.get("streaming")):
|
||||
return "ignored", "not_build_stream", 0.0, 0
|
||||
@@ -387,6 +431,11 @@ def classify_audit(value: dict[str, Any], config: Config) -> tuple[str, str, flo
|
||||
if generation_ms <= 0 or output_tokens < 32:
|
||||
return "ignored", "insufficient_output_tokens", 0.0, output_tokens
|
||||
speed = float(output_tokens) * 1000 / float(generation_ms)
|
||||
reasoning_tokens = max(0, int(value.get("reasoningTokens") or 0))
|
||||
# Backend model swaps often keep a normal 80-200 TPS but drop thinking.
|
||||
# TPS-only rules treat those as healthy.
|
||||
if output_tokens >= 64 and reasoning_tokens <= 0:
|
||||
return "hard", "missing_thinking", speed, output_tokens
|
||||
if config.fail_closed and generation_ms < config.min_generation_ms and speed >= config.soft_tps:
|
||||
return "hard", "buffered_burst", speed, output_tokens
|
||||
if speed >= config.hard_tps:
|
||||
@@ -416,6 +465,8 @@ def default_node_state() -> dict[str, Any]:
|
||||
"last_rotation_exit_ip": "",
|
||||
"rotation_failures": 0,
|
||||
"last_no_account_log_at": 0.0,
|
||||
"quarantine_source": "",
|
||||
"passive_degrade_repeats": 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -538,6 +589,7 @@ class Guard:
|
||||
"rotatable_node_ids": list(self.config.rotatable_node_ids),
|
||||
"prompt": self.config.prompt,
|
||||
"expected": self.config.expected,
|
||||
"active_profile_id": resolve_probe_profile(self.config.profiles_file)[0],
|
||||
}
|
||||
|
||||
def _save(self) -> None:
|
||||
@@ -600,7 +652,7 @@ class Guard:
|
||||
bool(self.config.rotation_url)
|
||||
and node_id in set(self.config.rotatable_node_ids)
|
||||
and reason in {
|
||||
"hard_tps", "soft_tps", "buffered_burst", "expected_marker_missing",
|
||||
"hard_tps", "soft_tps", "buffered_burst", "missing_thinking", "expected_marker_missing",
|
||||
"insufficient_output_tokens", "insufficient_generation_window", "probe_errors",
|
||||
"recovery_probe_error", "rotation_error",
|
||||
}
|
||||
@@ -610,7 +662,7 @@ class Guard:
|
||||
def _probe_account_unavailable(exc: Exception) -> bool:
|
||||
return isinstance(exc, ApiError) and exc.code == "egressQualityProbeNoAccount"
|
||||
|
||||
def _quarantine(self, nodes: list[dict[str, Any]], node: dict[str, Any], reason: str, now: float) -> None:
|
||||
def _quarantine(self, nodes: list[dict[str, Any]], node: dict[str, Any], reason: str, now: float, recover_now: bool = True) -> None:
|
||||
node_id = str(node["id"])
|
||||
state = self._state_for(node_id)
|
||||
if not self._can_quarantine(nodes, node_id):
|
||||
@@ -618,13 +670,20 @@ class Guard:
|
||||
log_event("quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, minimum_healthy=self.config.min_healthy_nodes)
|
||||
return
|
||||
previous_state = dict(state)
|
||||
source = "passive" if not recover_now else "active"
|
||||
repeats = int(state.get("passive_degrade_repeats", 0))
|
||||
if source == "passive":
|
||||
repeats += 1
|
||||
scale = min(8, 2 ** max(0, repeats - 1)) if source == "passive" else 1
|
||||
state.update({
|
||||
"active_soft_strikes": 0,
|
||||
"passive_soft_strikes": 0,
|
||||
"error_strikes": 0,
|
||||
"quarantined_until": now + self.config.quarantine_seconds,
|
||||
"quarantined_until": now + self.config.quarantine_seconds * scale,
|
||||
"disabled_by_guard": True,
|
||||
"last_reason": reason,
|
||||
"quarantine_source": source,
|
||||
"passive_degrade_repeats": repeats if source == "passive" else int(state.get("passive_degrade_repeats", 0)),
|
||||
})
|
||||
# Persist ownership before changing backend scheduling state. A crash
|
||||
# after the API call can then be reconciled safely on restart.
|
||||
@@ -647,11 +706,37 @@ class Guard:
|
||||
self._bump_statistic("actions", "quarantined")
|
||||
append_state_event(self.state, "node_quarantined", node_id=node_id, node_name=node.get("name"), reason=reason)
|
||||
self._save()
|
||||
log_event("node_quarantined", node_id=node_id, node_name=node.get("name"), reason=reason, quarantine_seconds=self.config.quarantine_seconds)
|
||||
if reason == "buffered_burst":
|
||||
self._recover_quarantined(node, time.time(), rotate=False, rotate_on_failure=True)
|
||||
log_event(
|
||||
"node_quarantined",
|
||||
node_id=node_id,
|
||||
node_name=node.get("name"),
|
||||
reason=reason,
|
||||
quarantine_seconds=self.config.quarantine_seconds,
|
||||
quarantine_hold_seconds=self.config.quarantine_seconds * scale,
|
||||
quarantine_source=source,
|
||||
degrade_repeats=repeats if source == "passive" else 0,
|
||||
recover_now=recover_now,
|
||||
)
|
||||
if recover_now:
|
||||
if reason == "buffered_burst":
|
||||
self._recover_quarantined(node, time.time(), rotate=False, rotate_on_failure=True)
|
||||
elif self._should_rotate(node_id, reason):
|
||||
self._recover_quarantined(node, time.time(), rotate=True)
|
||||
elif self._should_rotate(node_id, reason):
|
||||
self._recover_quarantined(node, time.time(), rotate=True)
|
||||
try:
|
||||
rotation = self.api.rotate_node(node_id, str(node.get("exitIp") or ""))
|
||||
except Exception as exc:
|
||||
state["rotation_failures"] = int(state.get("rotation_failures", 0)) + 1
|
||||
log_event("node_rotation_failed", node_id=node_id, node_name=node.get("name"), error_type=type(exc).__name__, trigger="passive_hold")
|
||||
else:
|
||||
state.update({
|
||||
"last_rotation_at": time.time(),
|
||||
"last_rotation_exit_ip": str(rotation.get("newExitIp") or ""),
|
||||
"rotation_failures": 0,
|
||||
})
|
||||
append_state_event(self.state, "node_rotated", node_id=node_id, node_name=node.get("name"), exit_ip=str(rotation.get("newExitIp") or ""))
|
||||
self._save()
|
||||
log_event("node_rotated", node_id=node_id, node_name=node.get("name"), exit_ip=str(rotation.get("newExitIp") or ""), trigger="passive_hold")
|
||||
|
||||
def _record_probe(self, node: dict[str, Any], result: dict[str, Any], classification: str, reason: str, now: float) -> None:
|
||||
node_id = str(node["id"])
|
||||
@@ -668,6 +753,7 @@ class Guard:
|
||||
"last_classification": classification,
|
||||
"last_output_tps": round(output_tps, 3),
|
||||
"last_output_tokens": output_tokens,
|
||||
"last_reasoning_tokens": max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0)),
|
||||
"last_first_token_ms": int(result.get("firstTokenMs") or 0),
|
||||
"last_duration_ms": int(result.get("durationMs") or 0),
|
||||
})
|
||||
@@ -689,6 +775,7 @@ class Guard:
|
||||
reason=reason,
|
||||
output_tps=round(output_tps, 3),
|
||||
output_tokens=output_tokens,
|
||||
reasoning_tokens=max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0)),
|
||||
first_token_ms=int(result.get("firstTokenMs") or 0),
|
||||
duration_ms=int(result.get("durationMs") or 0),
|
||||
chunk_count=int(result.get("chunkCount") or 0),
|
||||
@@ -701,8 +788,9 @@ class Guard:
|
||||
if state.get("last_reason") == "probe_no_account" and now < float(state.get("quarantined_until", 0.0)):
|
||||
return
|
||||
self._bump_statistic("active", "total")
|
||||
profile_id, profile = resolve_probe_profile(self.config.profiles_file)
|
||||
try:
|
||||
result = self.api.quality_test(node_id)
|
||||
result = self.api.quality_test(node_id, profile_id)
|
||||
except Exception as exc:
|
||||
if self._probe_account_unavailable(exc):
|
||||
self._defer_no_account(state, node, now, "quality_probe_deferred", trigger=trigger)
|
||||
@@ -714,7 +802,7 @@ class Guard:
|
||||
if trigger == "scheduled" and state["error_strikes"] >= self.config.consecutive_errors:
|
||||
self._quarantine(nodes, node, "probe_errors", now)
|
||||
return
|
||||
classification, reason = classify_result(result, self.config)
|
||||
classification, reason = classify_result(result, self.config, profile)
|
||||
self._record_probe(node, result, classification, reason, now)
|
||||
if classification == "hard" or (
|
||||
classification == "soft" and self.config.fail_closed
|
||||
@@ -760,8 +848,9 @@ class Guard:
|
||||
connectivity_status = "error"
|
||||
log_event("recovery_connectivity_probe_failed", node_id=node_id, node_name=node.get("name"), error_type=type(exc).__name__)
|
||||
self._bump_statistic("active", "total")
|
||||
result = self.api.quality_test(node_id)
|
||||
classification, reason = classify_result(result, self.config)
|
||||
profile_id, profile = resolve_probe_profile(self.config.profiles_file)
|
||||
result = self.api.quality_test(node_id, profile_id)
|
||||
classification, reason = classify_result(result, self.config, profile)
|
||||
self._record_probe(node, result, classification, reason, now)
|
||||
except Exception as exc:
|
||||
if self._probe_account_unavailable(exc):
|
||||
@@ -779,6 +868,7 @@ class Guard:
|
||||
if rotate_on_failure and self._should_rotate(node_id, reason):
|
||||
self._recover_quarantined(node, time.time(), rotate=True)
|
||||
return
|
||||
after_passive = self._is_passive_quarantine(state)
|
||||
updated = self.api.set_enabled(node_id, True)
|
||||
if updated != 1:
|
||||
log_event("restore_not_applied", node_id=node_id, node_name=node.get("name"), updated=updated)
|
||||
@@ -790,11 +880,29 @@ class Guard:
|
||||
"quarantined_until": 0.0,
|
||||
"disabled_by_guard": False,
|
||||
"last_reason": "",
|
||||
"quarantine_source": "",
|
||||
})
|
||||
node["enabled"] = True
|
||||
self._bump_statistic("actions", "restored")
|
||||
append_state_event(self.state, "node_restored", node_id=node_id, node_name=node.get("name"), reason="quality_probe_healthy")
|
||||
log_event("node_restored", node_id=node_id, node_name=node.get("name"), connectivity_status=connectivity_status)
|
||||
log_event(
|
||||
"node_restored",
|
||||
node_id=node_id,
|
||||
node_name=node.get("name"),
|
||||
connectivity_status=connectivity_status,
|
||||
reason="quality_probe_healthy",
|
||||
after_passive_hold=after_passive,
|
||||
expected_matched=bool(result.get("expectedMatched")),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _is_passive_quarantine(state: dict[str, Any]) -> bool:
|
||||
source = str(state.get("quarantine_source") or "")
|
||||
if source == "passive":
|
||||
return True
|
||||
if source == "active":
|
||||
return False
|
||||
return str(state.get("last_source") or "") == "passive"
|
||||
|
||||
def _probe_quarantined(self, node: dict[str, Any], now: float) -> None:
|
||||
node_id = str(node["id"])
|
||||
@@ -802,11 +910,15 @@ class Guard:
|
||||
if now < float(state.get("quarantined_until", 0.0)):
|
||||
return
|
||||
reason = str(state.get("last_reason") or "")
|
||||
passive = self._is_passive_quarantine(state)
|
||||
# Dual probe: user traffic isolates immediately; after the hold a
|
||||
# QUALITY_OK probe must come back healthy before restore. Passive
|
||||
# isolate already rotated, so only rotate again if the probe fails.
|
||||
self._recover_quarantined(
|
||||
node,
|
||||
now,
|
||||
rotate=self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=reason == "buffered_burst",
|
||||
rotate=(not passive) and self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=passive or reason == "buffered_burst",
|
||||
)
|
||||
|
||||
def _prepare_nodes(self, now: float) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str]]:
|
||||
@@ -860,15 +972,16 @@ class Guard:
|
||||
updated = self.api.set_enabled(node_id, False)
|
||||
if updated == 1:
|
||||
node["enabled"] = False
|
||||
state["quarantined_until"] = now + self.config.quarantine_seconds
|
||||
log_event("operator_reenable_requires_probe", node_id=node_id, node_name=node.get("name"))
|
||||
reason = str(state.get("last_reason") or "")
|
||||
self._recover_quarantined(
|
||||
node,
|
||||
now,
|
||||
rotate=self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=reason == "buffered_burst",
|
||||
)
|
||||
if now >= float(state.get("quarantined_until", 0.0)):
|
||||
reason = str(state.get("last_reason") or "")
|
||||
passive = self._is_passive_quarantine(state)
|
||||
self._recover_quarantined(
|
||||
node,
|
||||
now,
|
||||
rotate=(not passive) and self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=passive or reason == "buffered_burst",
|
||||
)
|
||||
skip_ids.add(node_id)
|
||||
continue
|
||||
state.update({
|
||||
@@ -964,6 +1077,7 @@ class Guard:
|
||||
})
|
||||
if classification == "healthy":
|
||||
state["passive_soft_strikes"] = 0
|
||||
state["passive_degrade_repeats"] = 0
|
||||
return
|
||||
if classification == "soft":
|
||||
state["passive_soft_strikes"] = int(state.get("passive_soft_strikes", 0)) + 1
|
||||
@@ -991,13 +1105,15 @@ class Guard:
|
||||
duration_ms=int(audit_value.get("durationMs") or 0),
|
||||
strikes=int(state.get("passive_soft_strikes", 0)),
|
||||
)
|
||||
if classification == "hard":
|
||||
self._quarantine(all_nodes, node, reason, now)
|
||||
return
|
||||
if self.config.fail_closed:
|
||||
self._quarantine(all_nodes, node, reason, now)
|
||||
return
|
||||
self._probe_active(all_nodes, node, now, trigger="passive_confirmation")
|
||||
log_event(
|
||||
"passive_immediate_quarantine",
|
||||
node_id=node_id,
|
||||
node_name=node.get("name"),
|
||||
classification=classification,
|
||||
reason=reason,
|
||||
output_tps=round(speed, 3),
|
||||
)
|
||||
self._quarantine(all_nodes, node, reason, now, recover_now=False)
|
||||
|
||||
def run_passive_cycle(self) -> None:
|
||||
now = time.time()
|
||||
|
||||
@@ -3,6 +3,7 @@ import json
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -36,14 +37,22 @@ def config(**overrides):
|
||||
class ClassificationTests(unittest.TestCase):
|
||||
def test_healthy_soft_and_hard_thresholds(self):
|
||||
cfg = config()
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 499}, cfg)[0], "healthy")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 500}, cfg)[0], "soft")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1000}, cfg)[0], "hard")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 499}, cfg)[0], "healthy")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 500}, cfg)[0], "soft")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1000}, cfg)[0], "hard")
|
||||
|
||||
def test_missing_marker_and_short_response_are_soft_failures(self):
|
||||
cfg = config()
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": False, "outputTokens": 100, "outputTokensPerSecond": 10}, cfg), ("soft", "expected_marker_missing"))
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 12, "outputTokensPerSecond": 10}, cfg), ("soft", "insufficient_output_tokens"))
|
||||
def test_missing_marker_is_hard_and_quality_ok_is_not_a_healthy_shortcut(self):
|
||||
cfg = config(fail_closed=True, min_generation_ms=1000)
|
||||
marker = {"expected_text": "QUALITY_OK", "match_mode": "last_line"}
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": False, "outputTokens": 100, "outputTokensPerSecond": 10}, cfg, marker), ("hard", "expected_marker_missing"))
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 12, "outputTokensPerSecond": 8000}, cfg, marker), ("soft", "insufficient_output_tokens"))
|
||||
self.assertEqual(quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 128, "reasoningTokens": 40, "outputTokensPerSecond": 8000, "generationMs": 50,
|
||||
}, cfg, marker), ("hard", "buffered_burst"))
|
||||
self.assertEqual(quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 128, "reasoningTokens": 40, "outputTokensPerSecond": 80, "generationMs": 1500,
|
||||
}, cfg, marker), ("healthy", "within_threshold"))
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 12, "outputTokensPerSecond": 10}, cfg, {"expected_text": ""}), ("soft", "insufficient_output_tokens"))
|
||||
|
||||
def test_passive_speed_matches_panel_and_includes_reasoning_tokens(self):
|
||||
cfg = config()
|
||||
@@ -55,6 +64,46 @@ class ClassificationTests(unittest.TestCase):
|
||||
self.assertEqual((classification, reason, output), ("hard", "hard_tps", 1050))
|
||||
self.assertEqual(speed, 10500)
|
||||
|
||||
def test_passive_missing_thinking_is_hard_even_at_normal_tps(self):
|
||||
cfg = config(fail_closed=True, min_generation_ms=1000)
|
||||
base = {
|
||||
"provider": "grok_build", "streaming": True, "statusCode": 200,
|
||||
"firstTokenMs": 2000, "durationMs": 4000, "outputTokens": 200,
|
||||
}
|
||||
self.assertEqual(
|
||||
quality_guard.classify_audit({**base, "reasoningTokens": 0}, cfg)[:2],
|
||||
("hard", "missing_thinking"),
|
||||
)
|
||||
classification, reason, speed, _ = quality_guard.classify_audit({**base, "reasoningTokens": 80}, cfg)
|
||||
self.assertEqual((classification, reason), ("healthy", "within_threshold"))
|
||||
self.assertAlmostEqual(speed, 100.0)
|
||||
short = {**base, "outputTokens": 50, "reasoningTokens": 0, "durationMs": 2500}
|
||||
self.assertEqual(quality_guard.classify_audit(short, cfg)[0], "healthy")
|
||||
|
||||
def test_probe_missing_thinking_is_hard(self):
|
||||
cfg = config()
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500, "reasoningTokens": 0,
|
||||
}, cfg),
|
||||
("hard", "missing_thinking"),
|
||||
)
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500, "reasoningTokens": 90,
|
||||
}, cfg)[0],
|
||||
"healthy",
|
||||
)
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500,
|
||||
}, cfg),
|
||||
("hard", "missing_thinking"),
|
||||
)
|
||||
|
||||
def test_passive_ignores_short_and_failed_requests(self):
|
||||
cfg = config()
|
||||
short = {"provider": "grok_build", "streaming": True, "statusCode": 200, "firstTokenMs": 100, "durationMs": 110, "outputTokens": 20, "reasoningTokens": 0}
|
||||
@@ -185,7 +234,7 @@ class FakeApi:
|
||||
def fixed_fallback_node_ids(self):
|
||||
return set(self.fixed_fallback_ids)
|
||||
|
||||
def quality_test(self, node_id):
|
||||
def quality_test(self, node_id, profile_id=""):
|
||||
self.quality_calls.append(node_id)
|
||||
value = self.results.pop(0)
|
||||
if isinstance(value, Exception):
|
||||
@@ -225,8 +274,8 @@ class GuardTests(unittest.TestCase):
|
||||
lock_file=Path(directory) / "lock",
|
||||
node_ids=("1",),
|
||||
)
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(self.nodes(), [bad, good])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_cycle()
|
||||
@@ -261,7 +310,7 @@ class GuardTests(unittest.TestCase):
|
||||
lock_file=Path(directory) / "lock",
|
||||
node_ids=("1", "2"),
|
||||
)
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(self.nodes(3), [good], fixed_fallback_ids={"1"})
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_active_cycle()
|
||||
@@ -304,7 +353,7 @@ class GuardTests(unittest.TestCase):
|
||||
self.assert_persisted = bool(persisted["nodes"][node_id]["disabled_by_guard"])
|
||||
return super().set_enabled(node_id, enabled)
|
||||
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
api = ObservingApi(self.nodes(3), [bad])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_active_cycle()
|
||||
@@ -326,7 +375,7 @@ class GuardTests(unittest.TestCase):
|
||||
self.enabled_calls.append((node_id, enabled))
|
||||
raise RuntimeError("backend unavailable")
|
||||
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
api = FailingApi(self.nodes(3), [bad])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_active_cycle()
|
||||
@@ -361,7 +410,7 @@ class GuardTests(unittest.TestCase):
|
||||
nodes = self.nodes(2)
|
||||
nodes[0]["enabled"] = False
|
||||
nodes[1]["enabled"] = False
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(nodes, [good])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
state = guard._state_for("2")
|
||||
@@ -379,7 +428,7 @@ class GuardTests(unittest.TestCase):
|
||||
node_ids=("1",),
|
||||
min_healthy_nodes=3,
|
||||
)
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200}
|
||||
api = FakeApi(self.nodes(3), [bad])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_cycle()
|
||||
@@ -398,7 +447,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -411,10 +460,10 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("1", False), ("1", True)])
|
||||
self.assertEqual(api.enabled_calls, [("1", False)])
|
||||
self.assertEqual(api.rotation_calls, [("1", "")])
|
||||
self.assertEqual(api.quality_calls, ["1"])
|
||||
self.assertFalse(guard.state["nodes"]["1"]["disabled_by_guard"])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["1"]["disabled_by_guard"])
|
||||
|
||||
def test_fail_closed_requires_consecutive_probe_errors_then_rotates(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
@@ -429,7 +478,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -503,7 +552,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -514,9 +563,10 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("1", False), ("1", True)])
|
||||
self.assertEqual(api.rotation_calls, [])
|
||||
self.assertEqual(api.quality_calls, ["1"])
|
||||
self.assertEqual(api.enabled_calls, [("1", False)])
|
||||
self.assertEqual(api.rotation_calls, [("1", "")])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["1"]["disabled_by_guard"])
|
||||
|
||||
def test_fail_closed_keeps_node_isolated_when_rotated_ip_probe_is_ambiguous(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
@@ -531,7 +581,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
ambiguous = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 50,
|
||||
}
|
||||
@@ -553,7 +603,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -572,7 +622,7 @@ class GuardTests(unittest.TestCase):
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",))
|
||||
nodes = self.nodes()
|
||||
nodes[0]["enabled"] = False
|
||||
api = FakeApi(nodes, [{"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}])
|
||||
api = FakeApi(nodes, [{"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}])
|
||||
api.connectivity_test = lambda _node_id: {"status": "unhealthy"}
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
state = guard._state_for("1")
|
||||
@@ -596,7 +646,7 @@ class GuardTests(unittest.TestCase):
|
||||
def test_passive_hard_signal_quarantines_immediately_and_ignores_guard_key(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive", node_ids=("2",))
|
||||
healthy = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
healthy = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(self.nodes(), [healthy], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("guard", "1", 1200, quality_probe=True), self.audit("user", "2", 1200)], "hasMore": False, "nextCursor": ""},
|
||||
@@ -611,32 +661,31 @@ class GuardTests(unittest.TestCase):
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_soft_strikes"], 0)
|
||||
self.assertEqual(guard.state["statistics"]["passive"]["total"], 1)
|
||||
self.assertEqual(guard.state["statistics"]["passive"]["hard"], 1)
|
||||
self.assertEqual(guard.state["nodes"]["2"]["quarantine_source"], "passive")
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_active_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False), ("2", True)])
|
||||
self.assertFalse(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
|
||||
def test_passive_soft_signal_still_requires_active_confirmation(self):
|
||||
def test_passive_soft_signal_quarantines_immediately_without_probe(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive")
|
||||
hard = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200}
|
||||
api = FakeApi(self.nodes(), [hard], [
|
||||
api = FakeApi(self.nodes(), [], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user", "2", 600)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
|
||||
def test_passive_signals_quarantine_only_after_consecutive_active_soft_confirmations(self):
|
||||
def test_passive_soft_signal_holds_until_quarantine_window(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive")
|
||||
soft = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 600}
|
||||
api = FakeApi(self.nodes(), [soft, soft], [
|
||||
api = FakeApi(self.nodes(), [], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user-1", "2", 600)], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user-2", "2", 600)], "hasMore": False, "nextCursor": ""},
|
||||
@@ -644,12 +693,12 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["active_soft_strikes"], 1)
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2", "2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
|
||||
def test_multiple_passive_hard_signals_only_quarantine_once(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
@@ -665,7 +714,100 @@ class GuardTests(unittest.TestCase):
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_soft_strikes"], 0)
|
||||
|
||||
def test_passive_confirmation_errors_do_not_quarantine(self):
|
||||
def test_passive_hold_restores_only_after_healthy_probe(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive")
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 80,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
api = FakeApi(self.nodes(), [good], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user", "2", 2500)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_degrade_repeats"], 1)
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False), ("2", True)])
|
||||
self.assertFalse(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["quarantine_source"], "")
|
||||
|
||||
def test_passive_hold_keeps_isolated_when_recovery_probe_is_unhealthy(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(
|
||||
state_file=Path(directory) / "state.json",
|
||||
lock_file=Path(directory) / "lock",
|
||||
mode="passive",
|
||||
fail_closed=True,
|
||||
)
|
||||
bad = {
|
||||
"expectedMatched": True,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 8000,
|
||||
"generationMs": 50,
|
||||
}
|
||||
api = FakeApi(self.nodes(), [bad], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user", "2", 2500)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["last_reason"], "buffered_burst")
|
||||
|
||||
def test_repeat_passive_degrade_lengthens_hold(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(
|
||||
state_file=Path(directory) / "state.json",
|
||||
lock_file=Path(directory) / "lock",
|
||||
mode="passive",
|
||||
quarantine_seconds=30,
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 80,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
api = FakeApi(self.nodes(), [good], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user-1", "2", 2500)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
first_hold = guard.state["nodes"]["2"]["quarantined_until"] - time.time()
|
||||
self.assertGreater(first_hold, 20)
|
||||
self.assertLess(first_hold, 40)
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertFalse(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
api.audit_pages.append({"items": [self.audit("user-2", "2", 2500)], "hasMore": False, "nextCursor": ""})
|
||||
before = time.time()
|
||||
guard.run_passive_cycle()
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_degrade_repeats"], 2)
|
||||
second_hold = guard.state["nodes"]["2"]["quarantined_until"] - before
|
||||
self.assertGreaterEqual(second_hold, 55)
|
||||
self.assertLess(second_hold, 70)
|
||||
|
||||
def test_passive_user_anomaly_quarantines_without_waiting_for_probe(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(
|
||||
state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock",
|
||||
@@ -678,8 +820,9 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["error_strikes"], 1)
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
|
||||
@staticmethod
|
||||
def audit(audit_id, node_id, output_tps, quality_probe=False):
|
||||
|
||||
Reference in new issue
Block a user