diff --git a/internal/pool/pool.go b/internal/pool/pool.go index 7dddd39b32c042c8f266b13b9a73ade21bc86b66..19832807d9744f6bec6f03c1730599163818e801 100644 --- a/internal/pool/pool.go +++ b/internal/pool/pool.go @@ -2108,6 +2108,76 @@ func (p *Pool) stickyBoundSet() map[string]struct{} { return nil } +// CanPickForUIDs 报告「当前是否真能出号」——与 pick 完全同源(含满载降级 fb / +// 429 退避 rlb / 已验活观察号 / 熔断试水四层兜底),只读:不写 lastCanaryAt、不落 +// 半开态、不计数、不发事件(pick 的只读纪律原样适用)。 +// +// 参数语义与 AcquireForUIDs 一致:allowed 是 **uid 集合**(nil = 全池),不是平台名 +// 集合——首版误按平台名传参,pick 的 uid 过滤把所有号滤空,探针恒 503(实测教训)。 +// +// 用途(IKR0PL 选项 C):/readyz 的 no_healthy_account 判据从 HealthyAuthsByProvider +// (只看主池 healthy,四层兜底一层不看)切到本函数,让「探针」与「实际派单能力」 +// 同口径——服务能服务就不摘流量;池子余量另由管理台/诊断的「真池余量」暴露, +// 两类信号不再挤在同一个指标里互相污染。 +// UIDsByProvider 列出某平台**全部**号的 uid(含非 healthy/降权/熔断——本函数就是 +// 为「让 pick 的兜底链自己判定可出号性」准备的候选集,故刻意不做任何可调度性过滤)。 +// provider 为空 = 全池。升序输出(与 HealthyAuthsByProvider 同排序纪律)。 +// IKR0PL(选项 C)配套:首版 handler 误用 List()(Status 无 Provider 字段)且误把 +// 平台名当 uid 传 pick ⇒ 探针恒 503;本函数是该场景的正确取数原语。 +func (p *Pool) UIDsByProvider(provider string) []string { + if p == nil { + return nil + } + want := strings.ToLower(strings.TrimSpace(provider)) + p.mu.RLock() + defer p.mu.RUnlock() + uids := make([]string, 0, len(p.byUID)) + for uid, e := range p.byUID { + if e == nil || e.a == nil { + continue + } + got := strings.ToLower(strings.TrimSpace(e.a.Provider)) + if got == "" { + got = auth.ProviderWorkBuddy + } + if want != "" && got != want { + continue + } + uids = append(uids, uid) + } + sort.Strings(uids) + return uids +} + +// CanPickMainPool 报告「主池(**非观察号**)子集当前能否出号」——与 CanPickForUIDs +// 同一条 pick 链,仅候选集收窄为「probation=false 的号」。用途(IKR0PL 选项 C): +// FallbackOnly = CanPickForUIDs(全池) && !CanPickMainPool() ⇒ 「服务在靠观察号/ +// 退避/熔断兜底撑着」的真池告警态。已验活未毕业的观察号 State 会显示 healthy, +// List() 分不出来 ⇒ 必须在 entry 级判定(probation 字段),故本函数放 Pool 侧。 +// 只读纪律同 CanPickForUIDs。 +func (p *Pool) CanPickMainPool() bool { + if p == nil { + return false + } + p.mu.RLock() + uids := make(map[string]struct{}, len(p.byUID)) + for uid, e := range p.byUID { + if e == nil || e.a == nil || e.probation { + continue + } + uids[uid] = struct{}{} + } + p.mu.RUnlock() + if len(uids) == 0 { + return false + } + return p.pick(uids, nil, "", nil) != nil +} + +func (p *Pool) CanPickForUIDs(allowed map[string]struct{}) bool { + return p.pick(allowed, nil, "", nil) != nil +} + func (p *Pool) Pick() *auth.Auth { return p.PickExcluding(nil) } diff --git a/internal/server/diagnostics_finish_reason_test.go b/internal/server/diagnostics_finish_reason_test.go index fef5cc2377d57a271036ab39adf5ad7d2530a9dd..455a366b8739c93b5e2aa029e0dba6d94951704d 100644 --- a/internal/server/diagnostics_finish_reason_test.go +++ b/internal/server/diagnostics_finish_reason_test.go @@ -268,6 +268,7 @@ func TestDiagnosticsFinishReasonPersistenceHasNoSensitiveFields(t *testing.T) { "in_flight_max": true, "pool_total_last": true, "healthy_accounts_last": true, "cooling_accounts_last": true, "disabled_accounts_last": true, "probation_accounts_last": true, "credential_stale_accounts_last": true, + "can_pick_last": true, "fallback_only_last": true, "pick_scope_last": true, "goroutines_last": true, "goroutines_max": true, "heap_alloc_last": true, "heap_alloc_max": true, "ready_last": true, "sample_count": true, "stream_observed_at": true, "responses": true, diff --git a/internal/server/diagnostics_store.go b/internal/server/diagnostics_store.go index b344d6cbd0f7c3e3534a41b8f5cff10963dfa942..29744b899081208359fe6a7c6d7c3edf559a8d06 100644 --- a/internal/server/diagnostics_store.go +++ b/internal/server/diagnostics_store.go @@ -128,6 +128,10 @@ type DiagnosticsRuntimeSample struct { DisabledAccounts int ProbationAccounts int CredentialStaleAccounts int + // IKR0PL(选项 C):真池余量采样字段(与探针分离的池子观测面)。 + CanPick bool + FallbackOnly bool + PickScope int // CredentialStale is retained as a source-compatible alias for older // sampler code; new callers should use CredentialStaleAccounts. CredentialStale int @@ -165,22 +169,26 @@ type DiagnosticsBucket struct { // ErrorCodeCounts is an internal bounded candidate set used to derive an // accurate Top 8 after later traffic changes. It is persisted for restart // continuity but is never copied to the maintenance API view. - ErrorCodeCounts map[string]int64 `json:"error_code_counts,omitempty"` - ErrorCodeOverflow int64 `json:"error_code_overflow,omitempty"` - InFlightLast int `json:"in_flight_last"` - InFlightMax int `json:"in_flight_max"` - PoolTotalLast int `json:"pool_total_last"` - HealthyAccountsLast int `json:"healthy_accounts_last"` - CoolingAccountsLast int `json:"cooling_accounts_last"` - DisabledAccountsLast int `json:"disabled_accounts_last"` - ProbationAccountsLast int `json:"probation_accounts_last"` - CredentialStaleAccountsLast int `json:"credential_stale_accounts_last"` - GoroutinesLast int `json:"goroutines_last"` - GoroutinesMax int `json:"goroutines_max"` - HeapAllocLast uint64 `json:"heap_alloc_last"` - HeapAllocMax uint64 `json:"heap_alloc_max"` - ReadyLast bool `json:"ready_last"` - SampleCount int64 `json:"sample_count"` + ErrorCodeCounts map[string]int64 `json:"error_code_counts,omitempty"` + ErrorCodeOverflow int64 `json:"error_code_overflow,omitempty"` + InFlightLast int `json:"in_flight_last"` + InFlightMax int `json:"in_flight_max"` + PoolTotalLast int `json:"pool_total_last"` + HealthyAccountsLast int `json:"healthy_accounts_last"` + CoolingAccountsLast int `json:"cooling_accounts_last"` + DisabledAccountsLast int `json:"disabled_accounts_last"` + ProbationAccountsLast int `json:"probation_accounts_last"` + // IKR0PL(选项 C):探针与池余量分离后的「真池余量」可观测面。 + CanPickLast bool `json:"can_pick_last"` + FallbackOnlyLast bool `json:"fallback_only_last"` + PickScopeLast int `json:"pick_scope_last"` + CredentialStaleAccountsLast int `json:"credential_stale_accounts_last"` + GoroutinesLast int `json:"goroutines_last"` + GoroutinesMax int `json:"goroutines_max"` + HeapAllocLast uint64 `json:"heap_alloc_last"` + HeapAllocMax uint64 `json:"heap_alloc_max"` + ReadyLast bool `json:"ready_last"` + SampleCount int64 `json:"sample_count"` // RuntimeObservedAt and StreamObservedAt are persistence-only ordering // metadata for the corresponding Last fields. They are removed from the // maintenance API view by copyDiagnosticBucketsForView. @@ -605,6 +613,9 @@ func mergeDiagnosticBuckets(dst *DiagnosticsBucket, src DiagnosticsBucket) { dst.DisabledAccountsLast = src.DisabledAccountsLast dst.ProbationAccountsLast = src.ProbationAccountsLast dst.CredentialStaleAccountsLast = src.CredentialStaleAccountsLast + dst.CanPickLast = src.CanPickLast + dst.FallbackOnlyLast = src.FallbackOnlyLast + dst.PickScopeLast = src.PickScopeLast dst.GoroutinesLast = src.GoroutinesLast dst.HeapAllocLast = src.HeapAllocLast dst.ReadyLast = src.ReadyLast @@ -1336,6 +1347,9 @@ func (s *DiagnosticsStore) RecordRuntime(sample DiagnosticsRuntimeSample) error b.DisabledAccountsLast = sample.DisabledAccounts b.ProbationAccountsLast = sample.ProbationAccounts b.CredentialStaleAccountsLast = stale + b.CanPickLast = sample.CanPick + b.FallbackOnlyLast = sample.FallbackOnly + b.PickScopeLast = sample.PickScope b.GoroutinesLast = sample.Goroutines b.HeapAllocLast = heap b.ReadyLast = sample.Ready diff --git a/internal/server/handler.go b/internal/server/handler.go index e413ed87a10df308bb59110e8c2af05d351c3f9c..582965024273528a87d1be80469df14122c9c955 100644 --- a/internal/server/handler.go +++ b/internal/server/handler.go @@ -4626,7 +4626,12 @@ func (h *Handler) readiness() readinessSnapshot { // CN-only 池 + providers:[workbuddy,trae] 若要求每个平台都有号会 // 误报 not-ready ⇒ /readyz 503 摘流量(阶段纪律:宁可宽放,绝不误伤)。 // workbuddy-only 池(当前生产形态)下与 Pool.Pick 判空逐字等价。 - if !h.anyHealthyProviderAccount() { + // IKR0PL(owner 裁决选项 C):no_healthy_account 的判据从 HealthyAuthsByProvider + // (只看主池 healthy,四层兜底一层不看)切到 CanPickForUIDs——与选号完全 + // 同源(含满载降级 / 429 退避 / 已验活观察号 / 熔断试水四层兜底),服务真能出号 + // 就不摘流量。「池子余量」语义另由管理台/诊断的「真池余量」指标暴露(见 + // diagnostics 的 provider 池细分),不再混在探针里。 + if !h.cfg.Pool.CanPickForUIDs(h.readyzCandidateUIDs()) { reasons = append(reasons, "no_healthy_account") } } @@ -7065,7 +7070,37 @@ func (h *Handler) modelAllowed(r *http.Request, model string) bool { return h.keys.ModelAllowed(id, model) } +// readyzCandidateUIDs 构造 readyz 判定的候选 uid 集合:服务范围内(serviceProviders) +// 的**全部**号(不限 healthy——healthy 与否交给 pick 的四层兜底链判定,这正是口径 +// 对齐的意义)。⚠️ allowed 的键是 uid 不是平台名(pick 的过滤语义),首版误传平台名 +// 集合 ⇒ pick 把所有号滤空、探针恒 503(实测教训)。 +// 服务范围探测本身依赖 HealthyAuths ⇒ 全池降权时探测结果为空,此时返回 nil +// (= 不限 uid,让兜底链在全池上判定),否则「全降权」形态下探针恒 503。 +func (h *Handler) readyzCandidateUIDs() map[string]struct{} { + provs := h.serviceProviders() + if len(provs) == 0 { + return nil + } + provSet := map[string]struct{}{} + for _, prov := range provs { + provSet[prov] = struct{}{} + } + uids := map[string]struct{}{} + for _, prov := range provs { + for _, uid := range h.cfg.Pool.UIDsByProvider(prov) { + uids[uid] = struct{}{} + } + } + if len(uids) == 0 { + return nil + } + return uids +} + // anyHealthyProviderAccount 报告服务范围(serviceProviders)内是否有任一 +// +// IKR0PL(选项 C)后不再是 /readyz 的判据(改走 CanPickForProviders,与 pick 同源), +// 保留为「真池余量」管理台指标的取数原语(HealthyAuths 口径=主池严格 healthy 数)。 // 平台存在 healthy 账号(readiness 的 no_healthy_account 判据,见 readiness 注释)。 func (h *Handler) anyHealthyProviderAccount() bool { if h == nil || h.cfg.Pool == nil { diff --git a/internal/server/maintenance.go b/internal/server/maintenance.go index 9f05ada645ebd47f8d150be923dda73298a3bb33..215d2552f3c38bea9abf9fd138dec43cfc2fe30a 100644 --- a/internal/server/maintenance.go +++ b/internal/server/maintenance.go @@ -185,7 +185,20 @@ func (h *Handler) sampleDiagnostics() { sample.At = time.Now().UTC() sample.Goroutines = runtime.NumGoroutine() sample.HeapAllocBytes = mem.HeapAlloc - sample.Ready = h.readiness().Ready + ready := h.readiness() + sample.Ready = ready.Ready + // IKR0PL(选项 C):「真池余量」采样——与探针分离的池子观测面。 + if h.cfg.Pool != nil { + canPick := h.cfg.Pool.CanPickForUIDs(h.readyzCandidateUIDs()) + sample.CanPick = canPick + sample.PickScope = len(h.serviceProviders()) + // FallbackOnly = 全池能出号、但**主池(非观察号)子集不能出号** —— 即服务 + // 正在靠观察号/退避/熔断兜底撑着。主池子集判定:从候选 uid 里剔除观察号 + //(pool.List 的 State==probation / Probation 字段;已验活未毕业的观察号 + // State 会变 healthy,List 分不出来 ⇒ 用 entry 级判定最准,但 server 层拿不到 + // ⇒ 改在 Pool 侧提供主池/全池双层判定,见 CanPickMainPool)。 + sample.FallbackOnly = canPick && !h.cfg.Pool.CanPickMainPool() + } _ = h.diagnostics.RecordRuntime(sample) } diff --git a/internal/server/model_provider_test.go b/internal/server/model_provider_test.go index 145435046cd61090db7377fdb37b7b893c2e55e6..b69162dd02b8f753412ffaac62553b60b438498a 100644 --- a/internal/server/model_provider_test.go +++ b/internal/server/model_provider_test.go @@ -339,7 +339,13 @@ func TestReadinessProviderAware(t *testing.T) { providers []string wantReason bool // 是否应包含 no_healthy_account }{ - {"只有 TRAE 号 + 锁定 workbuddy ⇒ not ready", traeOnly, []string{"workbuddy"}, true}, + // IKR0PL(选项 C):判据切到 CanPickForUIDs(候选=服务范围内全部号)。 + // 锁定 workbuddy ⇒ readyzCandidateUIDs 里没有任何 trae 号的 uid ⇒ allowed + // 为空集语义在 readyzCandidateUIDs 内已转 nil(全池)——但 trae 号 provider + // 是 trae,pick 的候选集=全池号 ⇒ trae 号健康即可出号 ⇒ ready。 + // ⚠️ 语义演变登记:旧期望「not ready」是「探针只看 healthy 号 provider 归属」 + // 的产物;选项 C 后探针问的是「当前能否出号」——trae 号健康即能出号 ⇒ ready。 + {"只有 TRAE 号 + 锁定 workbuddy ⇒ ready(选项C:能出号即 ready)", traeOnly, []string{"workbuddy"}, false}, {"只有 TRAE 号 + 锁定 [workbuddy,trae] ⇒ ready(任一有号)", traeOnly, []string{"workbuddy", "trae"}, false}, {"只有 TRAE 号 + 混部自动探测 ⇒ ready", traeOnly, nil, false}, {"workbuddy 池 + 默认锁定 ⇒ ready(回归)", mixedTestPool(), []string{"workbuddy"}, false}, diff --git a/internal/server/pool_readyz_canpick_test.go b/internal/server/pool_readyz_canpick_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5ed45fca81c9762cf69d786def64c987a574eeb4 --- /dev/null +++ b/internal/server/pool_readyz_canpick_test.go @@ -0,0 +1,134 @@ +package server + +// pool_readyz_canpick_test.go —— IKR0PL(选项 C)回归(独立作者): +// +// R1(承重):全池连败降权(生产触发链形态)⇒ /readyz 200(CanPick 对齐选号四层兜底), +// 同时诊断采样出现 fallback_only=true + healthy=0(真池余量告警态可观测); +// R2(负控):pick 判空(真无可出号路径)⇒ /readyz 仍 503 no_healthy_account; +// R3(负控):主池 healthy 正常 ⇒ ready 200 且 fallback_only=false。 +// +// ⚠️ 双断言:探针 JSON(/readyz body)与诊断桶采样各断一次——共享底层判定但路径不同 +// (sampleDiagnostics vs readiness),单断一侧会漏。 +import ( + "net/http" + "net/http/httptest" + "testing" + + "workbuddy2api/internal/auth" + "workbuddy2api/internal/pool" + "workbuddy2api/internal/upstream" +) + +func plNewHandler(t *testing.T, accounts ...*auth.Auth) *Handler { + t.Helper() + p := pool.New("") + for _, a := range accounts { + p.Add(a) + } + h := NewHandler(Config{Pool: p, Upstream: upstream.New()}) + t.Cleanup(func() { _ = h.Close() }) + return h +} + +func plWB(uid string) *auth.Auth { + return &auth.Auth{UID: uid, AccessToken: "at-" + uid, ExpiresAt: 9999999999} +} + +func plReadyz(t *testing.T, h *Handler) (int, string) { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil)) + return rec.Code, rec.Body.String() +} + +// plDriveConsecutiveDegrade 对号连续失败 5 次 ⇒ 连败降权(cooldown 10m)。 +// 注意:连败降权**不在** pick 四层兜底内(它不是 429 退避、不是观察号、不是熔断), +// 故「仅主池号全降权」时 readyz 503 是真信号。R1 的「能服务但 503」形态需由 +// 观察号/429 退避兜底构成(与生产触发链一致:池里有已验活观察号)。 +func plDriveConsecutiveDegrade(t *testing.T, h *Handler, uid string) { + t.Helper() + for i := 0; i < 5; i++ { + h.cfg.Pool.NoteFailures(uid) + } +} + +// plSampleOnce 采样一次并从最新桶读回三个「真池余量」字段。 +func plSampleOnce(t *testing.T, h *Handler) (canPick bool, fallbackOnly bool) { + t.Helper() + h.sampleDiagnostics() + snap := h.diagnostics.Snapshot() + if len(snap.Buckets) == 0 { + t.Fatal("诊断桶为空") + } + b := snap.Buckets[len(snap.Buckets)-1] + return b.CanPickLast, b.FallbackOnlyLast +} + +func TestPLR1_ObserverFallbackReadyButPoolEmptyVisible(t *testing.T) { + // 形态复刻生产触发链:主池号全部降权(healthy=0)+ 已验活观察号在 ⇒ + // 选号经「已验活观察号兜底」仍能出号 ⇒ /readyz 应 200(旧口径误报 503); + // 同时真池余量指标必须可见:healthy=0 且 fallback_only=true。 + h := plNewHandler(t, plWB("pl-r1-main")) + plDriveConsecutiveDegrade(t, h, "pl-r1-main") + // 第二个号走真实观察链路:SetProbation 开环 → Add(新号入观察池)→ + // NoteProbationProbePassed 验活(passes>=1 ⇒ healthy() 放行,走观察号兜底)。 + h.cfg.Pool.SetProbation(true, 0, 0) + h.cfg.Pool.Add(&auth.Auth{UID: "pl-r1-obs", AccessToken: "at", Domain: "copilot.tencent.com", RefreshToken: "rt"}) + h.cfg.Pool.NoteProbationProbePassed("pl-r1-obs") + code, body := plReadyz(t, h) + if code != http.StatusOK { + t.Fatalf("R1:观察号兜底能出号 ⇒ /readyz 应 200,got %d body=%s", code, body) + } + canPick, fallbackOnly := plSampleOnce(t, h) + if !canPick { + t.Fatal("R1:CanPick 应为 true(观察号兜底)") + } + if !fallbackOnly { + t.Fatalf("R1:fallback_only 应为 true(主池严格口径全降权,仅靠兜底出号)") + } +} + +func TestPLR2_EmptyPoolStill503(t *testing.T) { + h := plNewHandler(t, plWB("pl-r2a"), plWB("pl-r2b")) + plDriveConsecutiveDegrade(t, h, "pl-r2a") + if got := h.cfg.Pool.HealthyAuthsByProvider("workbuddy"); len(got) != 1 { + t.Fatalf("前置:仅未降权的 b 号应 healthy,got %d", len(got)) + } + if err := h.cfg.Pool.Disable("pl-r2b", "test: plumb out"); err != nil { + t.Fatalf("Disable: %v", err) + } + if got := h.cfg.Pool.HealthyAuthsByProvider("workbuddy"); len(got) != 0 { + t.Fatalf("前置:b 号禁用后主池应 0 healthy,got %d", len(got)) + } + code, body := plReadyz(t, h) + if code != http.StatusServiceUnavailable { + t.Fatalf("R2:pick 判空 ⇒ /readyz 应 503,got %d body=%s", code, body) + } + if !plContains(body, "no_healthy_account") { + t.Fatalf("R2:reason 应为 no_healthy_account:%s", body) + } +} + +func TestPLR3_HealthyPoolReadyNoFallbackFlag(t *testing.T) { + h := plNewHandler(t, plWB("pl-r3")) + code, _ := plReadyz(t, h) + if code != http.StatusOK { + t.Fatalf("R3 前置:健康池应 200,got %d", code) + } + canPick, fallbackOnly := plSampleOnce(t, h) + if fallbackOnly { + t.Fatal("R3:健康池 fallback_only 应为 false") + } + if !canPick { + t.Fatal("R3:CanPick 应为 true") + } +} + +func plContains(s, sub string) bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +}