diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index bd384dd9..c00deb56 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -666,7 +666,9 @@ func (a *Application) logPerformanceMetrics() { "subsystem", sample.Labels.Subsystem, "operation", sample.Labels.Operation, "provider", sample.Labels.Provider, + "plane", sample.Labels.Plane, "stage", sample.Labels.Stage, + "ordinal", sample.Labels.Ordinal, "outcome", sample.Labels.Outcome, "count", sample.Count, "total", sample.Total, diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index a26fbb60..bdc135e8 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -519,6 +519,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string if !ok { return nil, ErrNoAvailableAccount } + physicalCallCtx := infraegress.WithPhysicalCallTrace(ctx, string(route.Provider), string(operation)) supportsStoredResponses := s.providers.SupportsStoredResponses(route.Provider) if input.PreviousResponseID != "" && !supportsStoredResponses { return nil, ErrResponseStateUnsupported @@ -553,7 +554,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string started := time.Now() responseStartedAt = started lease.markSelectorUpstreamStarted() - response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, ReasoningReplayKey: reasoningReplayKey, AllowClientToolCacheRoute: input.AllowClientToolCacheRoute, GrokTurnIndex: input.GrokTurnIndex, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)}) + response, err := adapter.ForwardResponse(physicalCallCtx, provider.ResponseResourceRequest{Credential: credential, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, ReasoningReplayKey: reasoningReplayKey, AllowClientToolCacheRoute: input.AllowClientToolCacheRoute, GrokTurnIndex: input.GrokTurnIndex, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)}) err = failureAttempts.captureResponse(credential, started, response, err) timing.markUpstream(time.Since(started)) return response, err @@ -1084,6 +1085,11 @@ func (s *Service) forwardOwnedResponse(ctx context.Context, input ResourceInput, if !ok { return nil, ErrResponseAccountUnavailable } + operation := "response_get" + if method == http.MethodDelete { + operation = "response_delete" + } + physicalCallCtx := infraegress.WithPhysicalCallTrace(ctx, string(ownership.Provider), operation) lease, err := s.selector.AcquirePinned(ctx, ownership.Provider, ownership.AccountID, "", "", false) if err != nil { return nil, fmt.Errorf("%w: %w", ErrResponseAccountUnavailable, err) @@ -1097,7 +1103,7 @@ func (s *Service) forwardOwnedResponse(ctx context.Context, input ResourceInput, if input.RawQuery != "" { path += "?" + input.RawQuery } - response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Method: method, Path: path}) + response, err := adapter.ForwardResponse(physicalCallCtx, provider.ResponseResourceRequest{Credential: credential, Method: method, Path: path}) if err != nil { if isSSOCredentialRejected(err, credential) { s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider)) @@ -1124,7 +1130,7 @@ func (s *Service) forwardOwnedResponse(ctx context.Context, input ResourceInput, lease.Release() return nil, refreshErr } - response, err = adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: refreshed, Method: method, Path: path}) + response, err = adapter.ForwardResponse(physicalCallCtx, provider.ResponseResourceRequest{Credential: refreshed, Method: method, Path: path}) credential = refreshed if err != nil { lease.Release() diff --git a/backend/internal/infra/egress/manager.go b/backend/internal/infra/egress/manager.go index 298f7972..e4764e23 100644 --- a/backend/internal/infra/egress/manager.go +++ b/backend/internal/infra/egress/manager.go @@ -14,6 +14,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" application "github.com/chenyme/grok2api/backend/internal/application/egress" @@ -29,6 +30,7 @@ const nodeSnapshotTTL = time.Second const proxyPoolRetryLimit = 2 const clientCacheIdleTTL = 30 * time.Minute const clientCacheCleanupInterval = time.Minute +const clientCacheTouchInterval = time.Minute const maxCachedClients = 4096 const clearanceLockGrace = 30 * time.Second const clearanceCacheCleanupInterval = time.Minute @@ -69,6 +71,7 @@ func (l *Lease) Do(request *http.Request) (*http.Response, error) { return nil, errors.New("出口客户端未初始化") } response, err := l.do(request) + recordPhysicalCall(request.Context(), response, err) if err == nil && response != nil && response.StatusCode == http.StatusForbidden && l.clearanceManager != nil && l.clearanceKey != "" { l.clearanceManager.invalidateClearanceKey(l.clearanceKey, l.client) } @@ -84,9 +87,11 @@ func (l *Lease) Release() { type Manager struct { repository repository.EgressRepository cipher *security.Cipher - mu sync.Mutex + nodeMu sync.RWMutex + clientMu sync.RWMutex + clearanceMu sync.Mutex clients map[clientCacheKey]cachedClient - inflight map[uint64]int + inflight sync.Map nodes map[domain.Scope]cachedNodeSnapshot healthyNodes map[uint64]time.Time nodeVersions map[domain.Scope]uint64 @@ -144,8 +149,8 @@ type cachedNodeSnapshot struct { func NewManager(repository repository.EgressRepository, cipher *security.Cipher) *Manager { return &Manager{ repository: repository, cipher: cipher, - clients: make(map[clientCacheKey]cachedClient), inflight: make(map[uint64]int), - nodes: make(map[domain.Scope]cachedNodeSnapshot), healthyNodes: make(map[uint64]time.Time), + clients: make(map[clientCacheKey]cachedClient), + nodes: make(map[domain.Scope]cachedNodeSnapshot), healthyNodes: make(map[uint64]time.Time), nodeVersions: make(map[domain.Scope]uint64), clientVersions: make(map[uint64]uint64), clearances: make(map[string]clearanceState), newBuildClient: newBuildRequestClient, newBrowserClient: newBrowserClient, solver: flaresolverrSolver{}, @@ -157,24 +162,26 @@ func NewManager(repository repository.EgressRepository, cipher *security.Cipher) // nodes. Account-bound Resin clearances remain process-local because they must // never be persisted into the node-wide cookie fields. func (m *Manager) SetClearanceLock(value repository.DistributedLock) { - m.mu.Lock() + m.clearanceMu.Lock() m.clearanceLock = value - m.mu.Unlock() + m.clearanceMu.Unlock() } func (m *Manager) UpdateClearanceConfig(value ClearanceConfig) { value.Mode = strings.TrimSpace(value.Mode) value.FlareSolverrURL = strings.TrimSpace(value.FlareSolverrURL) value.TargetURL = strings.TrimRight(strings.TrimSpace(value.TargetURL), "/") - m.mu.Lock() + m.clearanceMu.Lock() previous := m.clearanceConfig m.clearanceConfig = value configurationChanged := previous.Mode != value.Mode || previous.FlareSolverrURL != value.FlareSolverrURL || previous.TargetURL != value.TargetURL if configurationChanged { m.clearanceVersion++ + m.clientMu.Lock() m.invalidateAllClientVersionsLocked() + m.clientMu.Unlock() } - m.mu.Unlock() + m.clearanceMu.Unlock() } func (m *Manager) Acquire(ctx context.Context, scope domain.Scope, affinity string) (*Lease, error) { @@ -431,23 +438,37 @@ func (m *Manager) leaseForNode(ctx context.Context, scope domain.Scope, affinity if err != nil { return nil, false, err } - m.mu.Lock() - m.inflight[selected.ID]++ - m.mu.Unlock() + m.incrementInflight(selected.ID) recordSelection(ctx, Selection{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, Proxied: proxyURL != ""}) var once sync.Once return &Lease{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client.client, browser: client.browser, sticky: sticky, proxyPool: proxyPool, clearanceKey: clearanceKey, clearanceManager: m, release: func() { once.Do(func() { - m.mu.Lock() - m.inflight[selected.ID]-- - if m.inflight[selected.ID] <= 0 { - delete(m.inflight, selected.ID) - } - m.mu.Unlock() + m.decrementInflight(selected.ID) }) }}, true, nil } +func (m *Manager) inflightCounter(nodeID uint64) *atomic.Int64 { + // Counters remain address-stable for the manager lifetime so a concurrent + // release can never decrement a replacement counter after an ABA deletion. + if value, ok := m.inflight.Load(nodeID); ok { + return value.(*atomic.Int64) + } + candidate := &atomic.Int64{} + actual, _ := m.inflight.LoadOrStore(nodeID, candidate) + return actual.(*atomic.Int64) +} + +func (m *Manager) incrementInflight(nodeID uint64) { + m.inflightCounter(nodeID).Add(1) +} + +func (m *Manager) decrementInflight(nodeID uint64) { + if value, ok := m.inflight.Load(nodeID); ok { + value.(*atomic.Int64).Add(-1) + } +} + func clearanceCacheKey(nodeID uint64, proxyURL string, sticky bool) string { if nodeID == 0 { return "direct" @@ -492,34 +513,37 @@ func normalizeProxyAccount(value string) string { func (m *Manager) listNodes(ctx context.Context, scope domain.Scope, now time.Time) ([]domain.Node, error) { for { - m.mu.Lock() + m.nodeMu.RLock() if snapshot, ok := m.nodes[scope]; ok && now.Before(snapshot.expiresAt) { - values := append([]domain.Node(nil), snapshot.values...) - m.mu.Unlock() + // Node snapshots are replaced with a copied slice and treated as immutable + // by callers. Returning the shared read-only slice avoids a per-request copy. + values := snapshot.values + m.nodeMu.RUnlock() return values, nil } - m.mu.Unlock() + m.nodeMu.RUnlock() loaded, err, _ := m.nodeLoads.Do(string(scope), func() (any, error) { checkTime := time.Now().UTC() - m.mu.Lock() + m.nodeMu.RLock() if snapshot, ok := m.nodes[scope]; ok && checkTime.Before(snapshot.expiresAt) { - values := append([]domain.Node(nil), snapshot.values...) - m.mu.Unlock() + values := snapshot.values + m.nodeMu.RUnlock() return values, nil } version := m.nodeVersions[scope] - m.mu.Unlock() + m.nodeMu.RUnlock() values, err := m.repository.ListEgressNodes(ctx, scope, repository.SortQuery{}) if err != nil { return nil, err } - m.mu.Lock() + m.nodeMu.Lock() if m.nodeVersions[scope] != version { - m.mu.Unlock() + m.nodeMu.Unlock() return nil, errNodeSnapshotInvalidated } m.replaceNodeSnapshotLocked(scope, values, checkTime.Add(nodeSnapshotTTL)) - m.mu.Unlock() + values = m.nodes[scope].values + m.nodeMu.Unlock() return values, nil }) if err != nil { @@ -529,12 +553,12 @@ func (m *Manager) listNodes(ctx context.Context, scope domain.Scope, now time.Ti } return nil, err } - return append([]domain.Node(nil), loaded.([]domain.Node)...), nil + return loaded.([]domain.Node), nil } } func (m *Manager) invalidateNodes(scope domain.Scope) { - m.mu.Lock() + m.nodeMu.Lock() m.nodeVersions[scope]++ snapshot, ok := m.nodes[scope] if ok { @@ -543,7 +567,7 @@ func (m *Manager) invalidateNodes(scope domain.Scope) { for _, node := range snapshot.values { delete(m.healthyNodes, node.ID) } - m.mu.Unlock() + m.nodeMu.Unlock() } func (m *Manager) replaceNodeSnapshotLocked(scope domain.Scope, values []domain.Node, expiresAt time.Time) { @@ -587,17 +611,25 @@ func (m *Manager) selectNode(nodes []domain.Node, affinity string) domain.Node { } return selected } - m.mu.Lock() - defer m.mu.Unlock() best := nodes[0] + bestCurrent := m.inflightCount(best.ID) for _, node := range nodes[1:] { - if m.inflight[node.ID] < m.inflight[best.ID] || (m.inflight[node.ID] == m.inflight[best.ID] && node.Health > best.Health) { + current := m.inflightCount(node.ID) + if current < bestCurrent || (current == bestCurrent && node.Health > best.Health) { best = node + bestCurrent = current } } return best } +func (m *Manager) inflightCount(nodeID uint64) int64 { + if value, ok := m.inflight.Load(nodeID); ok { + return value.(*atomic.Int64).Load() + } + return 0 +} + func (m *Manager) clientFor(id uint64, scope domain.Scope, proxyURL, userAgent, cookies string, sticky bool) (cachedClient, error) { clientKind := "browser" if scope == domain.ScopeBuild { @@ -612,16 +644,25 @@ func (m *Manager) clientFor(id uint64, scope domain.Scope, proxyURL, userAgent, loadKey := strconv.FormatUint(key.nodeID, 10) + "\x00" + string(key.scope) + "\x00" + key.fingerprint for attempt := 0; attempt < clientCreationRetryLimit; attempt++ { now := time.Now().UTC() - m.mu.Lock() + m.clientMu.RLock() + cached, cachedOK := m.clients[key] + cleanupDue := m.lastClientCleanup.IsZero() || now.Sub(m.lastClientCleanup) >= clientCacheCleanupInterval + touchDue := cachedOK && (cached.lastUsed.IsZero() || now.Sub(cached.lastUsed) >= clientCacheTouchInterval) + m.clientMu.RUnlock() + if cachedOK && !cleanupDue && !touchDue { + return cached, nil + } + + m.clientMu.Lock() stale := m.cleanupClientCacheLocked(now) if cached, ok := m.clients[key]; ok { cached.lastUsed = now m.clients[key] = cached - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(stale) return cached, nil } - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(stale) loaded, err, _ := m.clientLoads.Do(loadKey, func() (any, error) { @@ -640,17 +681,17 @@ func (m *Manager) clientFor(id uint64, scope domain.Scope, proxyURL, userAgent, func (m *Manager) createAndCacheClient(key clientCacheKey, id uint64, scope domain.Scope, proxyURL, userAgent string, sticky bool) (cachedClient, error) { now := time.Now().UTC() - m.mu.Lock() + m.clientMu.Lock() stale := m.cleanupClientCacheLocked(now) if cached, ok := m.clients[key]; ok { cached.lastUsed = now m.clients[key] = cached - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(stale) return cached, nil } version := m.clientVersionLocked(id) - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(stale) value, err := m.buildCachedClient(scope, proxyURL, userAgent) @@ -659,17 +700,17 @@ func (m *Manager) createAndCacheClient(key clientCacheKey, id uint64, scope doma } value.lastUsed = time.Now().UTC() - m.mu.Lock() + m.clientMu.Lock() stale = m.cleanupClientCacheLocked(value.lastUsed) if cached, ok := m.clients[key]; ok { cached.lastUsed = value.lastUsed m.clients[key] = cached - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(append(stale, value.client)) return cached, nil } if m.clientVersionLocked(id) != version { - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(append(stale, value.client)) return cachedClient{}, errClientCacheInvalidated } @@ -682,7 +723,7 @@ func (m *Manager) createAndCacheClient(key clientCacheKey, id uint64, scope doma } stale = append(stale, m.ensureClientCacheCapacityLocked()...) m.clients[key] = value - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(stale) return value, nil } @@ -791,15 +832,17 @@ func (m *Manager) Feedback(ctx context.Context, nodeID uint64, status int, trans func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, nodeID uint64, status int, transportErr error) { if nodeID == 0 { if transportErr != nil || (scope != domain.ScopeBuild && status == http.StatusForbidden) { - m.mu.Lock() + m.clearanceMu.Lock() if isGrokWebScope(scope) && status == http.StatusForbidden && m.clearanceConfig.Mode == "flaresolverr" { state := m.clearances["direct"] state.invalid = true state.used = true m.clearances["direct"] = state } + m.clearanceMu.Unlock() + m.clientMu.Lock() stale := m.invalidateClientForScopeLocked(0, scope) - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(stale) } return @@ -813,9 +856,9 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node return } if succeeded && nodeIsHealthy(value) { - m.mu.Lock() + m.nodeMu.Lock() m.healthyNodes[nodeID] = time.Now().UTC().Add(nodeSnapshotTTL) - m.mu.Unlock() + m.nodeMu.Unlock() return } now := time.Now().UTC() @@ -845,7 +888,7 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node value.Health = max(0.05, value.Health*0.7) value.CooldownUntil = nil value.LastError = "anti-bot rejection" - m.mu.Lock() + m.clearanceMu.Lock() if isGrokWebScope(scope) && m.clearanceConfig.Mode == "flaresolverr" { key := clearanceCacheKey(nodeID, "", false) state := m.clearances[key] @@ -853,8 +896,10 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node state.used = true m.clearances[key] = state } + m.clearanceMu.Unlock() + m.clientMu.Lock() stale = m.invalidateClientLocked(nodeID) - m.mu.Unlock() + m.clientMu.Unlock() case transportErr != nil: if m.isProxyPoolNode(value) { return @@ -865,9 +910,9 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node until := now.Add(cooldown) value.CooldownUntil = &until value.LastError = "transport error" - m.mu.Lock() + m.clientMu.Lock() stale = m.invalidateClientLocked(nodeID) - m.mu.Unlock() + m.clientMu.Unlock() default: // An HTTP status describes the upstream response, not the health of the // configured proxy endpoint. Account routing handles upstream failures. @@ -886,13 +931,13 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node } func (m *Manager) cachedNodeIsHealthy(nodeID uint64) bool { - m.mu.Lock() + m.nodeMu.Lock() validUntil, ok := m.healthyNodes[nodeID] healthy := ok && time.Now().UTC().Before(validUntil) if ok && !healthy { delete(m.healthyNodes, nodeID) } - m.mu.Unlock() + m.nodeMu.Unlock() return healthy } @@ -901,13 +946,13 @@ func nodeIsHealthy(value domain.Node) bool { } func (m *Manager) clearanceMode() string { - m.mu.Lock() - defer m.mu.Unlock() + m.clearanceMu.Lock() + defer m.clearanceMu.Unlock() return m.clearanceConfig.Mode } func (m *Manager) ensureClearance(ctx context.Context, node domain.Node, proxyURL, existingCookies, existingUserAgent, key string, persist bool) (string, string, error) { - m.mu.Lock() + m.clearanceMu.Lock() cfg := m.clearanceConfig version := m.clearanceVersion interval := clearanceRefreshInterval(cfg) @@ -945,7 +990,7 @@ func (m *Manager) ensureClearance(ctx context.Context, node domain.Node, proxyUR state.lastUsedAt = now m.clearances[key] = state cookies, userAgent := state.cookies, state.userAgent - m.mu.Unlock() + m.clearanceMu.Unlock() return cookies, userAgent, nil } fallbackAllowed := known && !state.invalid && state.cookies != "" && @@ -956,10 +1001,10 @@ func (m *Manager) ensureClearance(ctx context.Context, node domain.Node, proxyUR m.clearances[key] = state } if cfg.Mode != "flaresolverr" { - m.mu.Unlock() + m.clearanceMu.Unlock() return existingCookies, existingUserAgent, nil } - m.mu.Unlock() + m.clearanceMu.Unlock() result, err, _ := m.clearanceLoads.Do(key, func() (any, error) { return m.refreshNode(ctx, node, proxyURL, key, persist, false, !fallbackAllowed) @@ -975,12 +1020,12 @@ func (m *Manager) ensureClearance(ctx context.Context, node domain.Node, proxyUR } func (m *Manager) refreshNode(ctx context.Context, node domain.Node, proxyURL, key string, persist, force, waitForPeer bool) (clearanceSolution, error) { - m.mu.Lock() + m.clearanceMu.Lock() cfg := m.clearanceConfig solveVersion := m.clearanceVersion solver := m.solver lock := m.clearanceLock - m.mu.Unlock() + m.clearanceMu.Unlock() if cfg.Mode != "flaresolverr" { return clearanceSolution{}, errors.New("FlareSolverr Clearance 未启用") } @@ -1092,7 +1137,7 @@ func (m *Manager) loadPersistedClearance(ctx context.Context, nodeID uint64, fin } func (m *Manager) cacheClearance(key string, solution clearanceSolution, refreshedAt time.Time, version uint64, fingerprint, bindingFingerprint string, interval time.Duration) { - m.mu.Lock() + m.clearanceMu.Lock() now := time.Now().UTC() m.cleanupClearanceCacheLocked(now, interval) if _, exists := m.clearances[key]; !exists { @@ -1102,7 +1147,7 @@ func (m *Manager) cacheClearance(key string, solution clearanceSolution, refresh cookies: solution.Cookies, userAgent: solution.UserAgent, refreshedAt: refreshedAt, used: true, version: version, fingerprint: fingerprint, bindingFingerprint: bindingFingerprint, lastUsedAt: now, } - m.mu.Unlock() + m.clearanceMu.Unlock() } func (m *Manager) cleanupClearanceCacheLocked(now time.Time, interval time.Duration) { @@ -1223,7 +1268,7 @@ func (m *Manager) RefreshClearance(ctx context.Context, nodeID uint64) error { } func (m *Manager) InvalidateClearance(nodeID uint64) { - m.mu.Lock() + m.clearanceMu.Lock() prefix := "node:" + strconv.FormatUint(nodeID, 10) if nodeID == 0 { prefix = "direct" @@ -1235,8 +1280,10 @@ func (m *Manager) InvalidateClearance(nodeID uint64) { m.clearances[key] = state } } + m.clearanceMu.Unlock() + m.clientMu.Lock() stale := m.invalidateClientLocked(nodeID) - m.mu.Unlock() + m.clientMu.Unlock() closeRequestClients(stale) } @@ -1245,7 +1292,9 @@ func (m *Manager) InvalidateClearance(nodeID uint64) { // last-known-good cookie as invalid; ensureClearance will still verify its // binding before using it as a solver-failure fallback. func (m *Manager) ForgetClearance(nodeID uint64) { - m.mu.Lock() + m.clearanceMu.Lock() + m.nodeMu.Lock() + m.clientMu.Lock() prefix := "node:" + strconv.FormatUint(nodeID, 10) if nodeID == 0 { prefix = "direct" @@ -1258,31 +1307,40 @@ func (m *Manager) ForgetClearance(nodeID uint64) { // Node mutations are rare administration operations. Clearing the small // one-second snapshots prevents a just-edited proxy from being used once // more before its scope cache expires. + if m.nodeVersions == nil { + m.nodeVersions = make(map[domain.Scope]uint64) + } + for _, scope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} { + m.nodeVersions[scope]++ + } clear(m.nodes) + clear(m.healthyNodes) stale := m.invalidateClientLocked(nodeID) - m.mu.Unlock() + m.clientMu.Unlock() + m.nodeMu.Unlock() + m.clearanceMu.Unlock() closeRequestClients(stale) } func (m *Manager) invalidateClearanceKey(key string, client requestClient) { - m.mu.Lock() + m.clearanceMu.Lock() state := m.clearances[key] state.invalid = true state.used = true state.lastUsedAt = time.Now().UTC() m.clearances[key] = state - m.mu.Unlock() + m.clearanceMu.Unlock() if client != nil { client.CloseIdleConnections() } } func (m *Manager) RefreshDueClearances(ctx context.Context, force bool) error { - m.mu.Lock() + m.clearanceMu.Lock() cfg := m.clearanceConfig direct := m.clearances["direct"] version := m.clearanceVersion - m.mu.Unlock() + m.clearanceMu.Unlock() if cfg.Mode != "flaresolverr" { return nil } @@ -1314,10 +1372,10 @@ func (m *Manager) RefreshDueClearances(ctx context.Context, force bool) error { refreshErrors = append(refreshErrors, normalizeErr) continue } - m.mu.Lock() + m.clearanceMu.Lock() key := clearanceCacheKey(node.ID, proxyURL, false) state, known := m.clearances[key] - m.mu.Unlock() + m.clearanceMu.Unlock() fingerprint := clearanceFingerprint(cfg, proxyURL) memoryFresh := known && !state.invalid && state.version == version && state.fingerprint == fingerprint && now.Sub(state.refreshedAt) < interval persistedFresh := node.ClearanceRefreshedAt != nil && node.ClearanceFingerprint == fingerprint && now.Sub(*node.ClearanceRefreshedAt) < interval diff --git a/backend/internal/infra/egress/manager_test.go b/backend/internal/infra/egress/manager_test.go index 6f95bf99..6fdf60f3 100644 --- a/backend/internal/infra/egress/manager_test.go +++ b/backend/internal/infra/egress/manager_test.go @@ -62,11 +62,11 @@ func TestClientCacheEvictsIdleEntriesAndEnforcesCapacity(t *testing.T) { func TestClientVersionTombstonesRemainBounded(t *testing.T) { manager := NewManager(egressRepositoryTestStub{}, nil) - manager.mu.Lock() + manager.clientMu.Lock() for nodeID := uint64(1); nodeID <= maxClientVersionEntries+256; nodeID++ { manager.invalidateClientVersionLocked(nodeID) } - manager.mu.Unlock() + manager.clientMu.Unlock() if len(manager.clientVersions) > maxClientVersionEntries { t.Fatalf("client version tombstones = %d, limit = %d", len(manager.clientVersions), maxClientVersionEntries) } @@ -107,6 +107,87 @@ func TestClientCreationDoesNotHoldManagerLock(t *testing.T) { } } +func TestSelectNodeUsesAtomicInflightCounters(t *testing.T) { + manager := NewManager(egressRepositoryTestStub{}, nil) + nodes := []domain.Node{{ID: 1, Health: 1}, {ID: 2, Health: 1}} + manager.incrementInflight(1) + if selected := manager.selectNode(nodes, ""); selected.ID != 2 { + t.Fatalf("selected node = %d, want 2", selected.ID) + } + manager.decrementInflight(1) + if selected := manager.selectNode(nodes, ""); selected.ID != 1 { + t.Fatalf("selected node after release = %d, want stable node 1", selected.ID) + } +} + +func TestInflightCountersRemainBalancedConcurrently(t *testing.T) { + manager := NewManager(egressRepositoryTestStub{}, nil) + const workers = 64 + const iterations = 1000 + var wait sync.WaitGroup + for range workers { + wait.Add(1) + go func() { + defer wait.Done() + for range iterations { + manager.incrementInflight(1) + manager.decrementInflight(1) + } + }() + } + wait.Wait() + if value := manager.inflightCount(1); value != 0 { + t.Fatalf("inflight count = %d, want 0", value) + } +} + +func TestClientCacheCoalescesLastUsedWrites(t *testing.T) { + manager := NewManager(egressRepositoryTestStub{}, nil) + client := &scriptedRequestClient{} + manager.newBuildClient = func(string) (requestClient, error) { return client, nil } + if _, err := manager.clientFor(1, domain.ScopeBuild, "", "", "", false); err != nil { + t.Fatal(err) + } + + base := time.Now().UTC() + var key clientCacheKey + manager.clientMu.Lock() + for candidate, value := range manager.clients { + key = candidate + value.lastUsed = base + manager.clients[candidate] = value + } + manager.lastClientCleanup = base + manager.clientMu.Unlock() + + if _, err := manager.clientFor(1, domain.ScopeBuild, "", "", "", false); err != nil { + t.Fatal(err) + } + manager.clientMu.RLock() + untouched := manager.clients[key].lastUsed + manager.clientMu.RUnlock() + if !untouched.Equal(base) { + t.Fatalf("fresh cache hit rewrote lastUsed: got %s want %s", untouched, base) + } + + stale := base.Add(-clientCacheTouchInterval - time.Second) + manager.clientMu.Lock() + value := manager.clients[key] + value.lastUsed = stale + manager.clients[key] = value + manager.lastClientCleanup = time.Now().UTC() + manager.clientMu.Unlock() + if _, err := manager.clientFor(1, domain.ScopeBuild, "", "", "", false); err != nil { + t.Fatal(err) + } + manager.clientMu.RLock() + refreshed := manager.clients[key].lastUsed + manager.clientMu.RUnlock() + if !refreshed.After(stale) { + t.Fatalf("stale cache hit did not refresh lastUsed: got %s, stale %s", refreshed, stale) + } +} + func TestClientCreationDiscardsInvalidatedResult(t *testing.T) { manager := NewManager(egressRepositoryTestStub{}, nil) firstStarted := make(chan struct{}) @@ -690,9 +771,9 @@ func TestExpiredHealthySnapshotRechecksRepositoryOnSuccess(t *testing.T) { if _, err := manager.listNodes(context.Background(), domain.ScopeBuild, time.Now().UTC()); err != nil { t.Fatal(err) } - manager.mu.Lock() + manager.nodeMu.Lock() manager.healthyNodes[1] = time.Now().UTC().Add(-time.Second) - manager.mu.Unlock() + manager.nodeMu.Unlock() repository.node = domain.Node{ID: 1, Name: "recovering", Scope: domain.ScopeBuild, Enabled: true, Health: 0.8, FailureCount: 1, LastError: "transport error"} manager.FeedbackForScope(context.Background(), domain.ScopeBuild, 1, http.StatusOK, nil) @@ -712,11 +793,11 @@ func TestNodeSnapshotReplacementRemovesRetiredHealthState(t *testing.T) { t.Fatal("initial node was not cached as healthy") } repository.node = domain.Node{ID: 2, Name: "replacement", Scope: domain.ScopeBuild, Enabled: true, Health: 1} - manager.mu.Lock() + manager.nodeMu.Lock() snapshot := manager.nodes[domain.ScopeBuild] snapshot.expiresAt = now.Add(-time.Second) manager.nodes[domain.ScopeBuild] = snapshot - manager.mu.Unlock() + manager.nodeMu.Unlock() if _, err := manager.listNodes(context.Background(), domain.ScopeBuild, now); err != nil { t.Fatal(err) } @@ -770,6 +851,51 @@ func TestConcurrentFailurePreventsStaleHealthySnapshotInstall(t *testing.T) { } } +func TestForgetClearancePreventsStaleNodeSnapshotInstall(t *testing.T) { + repository := &blockingEgressRepository{ + node: domain.Node{ID: 1, Name: "before", Scope: domain.ScopeBuild, Enabled: true, Health: 1}, + listStarted: make(chan struct{}), + listRelease: make(chan struct{}), + } + manager := NewManager(repository, nil) + loaded := make(chan []domain.Node, 1) + loadErrors := make(chan error, 1) + go func() { + values, err := manager.listNodes(context.Background(), domain.ScopeBuild, time.Now().UTC()) + if err != nil { + loadErrors <- err + return + } + loaded <- values + }() + <-repository.listStarted + if _, err := repository.UpdateEgressNode(context.Background(), domain.Node{ID: 2, Name: "after", Scope: domain.ScopeBuild, Enabled: true, Health: 1}); err != nil { + t.Fatal(err) + } + manager.ForgetClearance(1) + close(repository.listRelease) + + select { + case err := <-loadErrors: + t.Fatal(err) + case values := <-loaded: + if len(values) != 1 || values[0].Name != "after" { + t.Fatalf("stale node snapshot returned after administrative invalidation: %#v", values) + } + case <-time.After(time.Second): + t.Fatal("node list did not complete") + } + + manager.nodeMu.RLock() + snapshot := manager.nodes[domain.ScopeBuild] + _, staleHealthy := manager.healthyNodes[1] + _, currentHealthy := manager.healthyNodes[2] + manager.nodeMu.RUnlock() + if len(snapshot.values) != 1 || snapshot.values[0].Name != "after" || staleHealthy || !currentHealthy { + t.Fatalf("runtime node state was not replaced cleanly: snapshot=%#v staleHealthy=%v currentHealthy=%v", snapshot, staleHealthy, currentHealthy) + } +} + func TestProxyPoolTransportFailureDoesNotCreateGlobalCooldown(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { @@ -1246,8 +1372,8 @@ func TestEgressNodeSnapshotAvoidsRepeatedRepositoryReads(t *testing.T) { type egressRepositoryTestStub struct{ nodes []domain.Node } func managerHasClientForNode(manager *Manager, nodeID uint64) bool { - manager.mu.Lock() - defer manager.mu.Unlock() + manager.clientMu.Lock() + defer manager.clientMu.Unlock() for key := range manager.clients { if key.nodeID == nodeID { return true @@ -1377,6 +1503,40 @@ func (s egressRepositoryTestStub) GetEgressNode(_ context.Context, id uint64) (d } return domain.Node{}, errors.New("not found") } + +func BenchmarkManagerAcquireCachedBuild(b *testing.B) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + b.Fatal(err) + } + node := domain.Node{ID: 1, Name: "build", Scope: domain.ScopeBuild, Enabled: true, Health: 1} + manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{node}}, cipher) + manager.newBuildClient = func(string) (requestClient, error) { + return &scriptedRequestClient{do: func(int, *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }}, nil + } + lease, err := manager.Acquire(context.Background(), domain.ScopeBuild, "") + if err != nil { + b.Fatal(err) + } + lease.Release() + manager.nodeMu.Lock() + manager.nodes[domain.ScopeBuild] = cachedNodeSnapshot{values: []domain.Node{node}, expiresAt: time.Now().Add(time.Hour)} + manager.nodeMu.Unlock() + + b.ReportAllocs() + b.RunParallel(func(worker *testing.PB) { + for worker.Next() { + lease, acquireErr := manager.Acquire(context.Background(), domain.ScopeBuild, "") + if acquireErr != nil { + b.Error(acquireErr) + continue + } + lease.Release() + } + }) +} func (egressRepositoryTestStub) CreateEgressNode(context.Context, domain.Node) (domain.Node, error) { return domain.Node{}, errors.New("unsupported") } diff --git a/backend/internal/infra/egress/physical_calls.go b/backend/internal/infra/egress/physical_calls.go new file mode 100644 index 00000000..73a70870 --- /dev/null +++ b/backend/internal/infra/egress/physical_calls.go @@ -0,0 +1,175 @@ +package egress + +import ( + "context" + "net/http" + "strconv" + "strings" + "sync/atomic" + + "github.com/chenyme/grok2api/backend/internal/pkg/perfmetrics" +) + +type physicalCallTrace struct { + provider string + operation string + ordinal atomic.Uint64 +} + +type physicalCallContext struct { + trace *physicalCallTrace + plane string + stage string +} + +type physicalCallContextKey struct{} + +// WithPhysicalCallTrace starts observe-only physical-call accounting for one +// downstream request. It does not impose a retry budget or alter transport. +func WithPhysicalCallTrace(ctx context.Context, provider, operation string) context.Context { + if ctx == nil { + return ctx + } + if current := physicalCallFromContext(ctx); current.trace != nil { + return ctx + } + provider = normalizePhysicalProvider(provider) + value := physicalCallContext{ + trace: &physicalCallTrace{provider: provider, operation: normalizePhysicalOperation(operation)}, + plane: defaultPhysicalPlane(provider), + stage: "primary", + } + return context.WithValue(ctx, physicalCallContextKey{}, value) +} + +// WithPhysicalCallPlane annotates a bounded upstream plane while preserving +// the request-wide ordinal and current stage. +func WithPhysicalCallPlane(ctx context.Context, plane string) context.Context { + value := physicalCallFromContext(ctx) + if value.trace == nil { + return ctx + } + value.plane = normalizePhysicalPlane(plane) + return context.WithValue(ctx, physicalCallContextKey{}, value) +} + +// WithPhysicalCallStage annotates an internal retry or preparation stage while +// preserving the request-wide ordinal and upstream plane. +func WithPhysicalCallStage(ctx context.Context, stage string) context.Context { + value := physicalCallFromContext(ctx) + if value.trace == nil { + return ctx + } + value.stage = normalizePhysicalStage(stage) + return context.WithValue(ctx, physicalCallContextKey{}, value) +} + +func recordPhysicalCall(ctx context.Context, response *http.Response, err error) { + value := physicalCallFromContext(ctx) + if value.trace == nil { + return + } + ordinal := value.trace.ordinal.Add(1) + perfmetrics.Default.Inc("upstream_physical_call_total", perfmetrics.Labels{ + Subsystem: "upstream", + Operation: value.trace.operation, + Provider: value.trace.provider, + Plane: value.plane, + Stage: value.stage, + Ordinal: physicalOrdinalBucket(ordinal), + Outcome: physicalCallOutcome(response, err), + }) +} + +// RecordDirectPhysicalCall records a transport call that intentionally bypasses +// the managed egress lease because no Build node is configured. +func RecordDirectPhysicalCall(ctx context.Context, response *http.Response, err error) { + recordPhysicalCall(ctx, response, err) +} + +func physicalCallFromContext(ctx context.Context) physicalCallContext { + if ctx == nil { + return physicalCallContext{} + } + value, _ := ctx.Value(physicalCallContextKey{}).(physicalCallContext) + return value +} + +func normalizePhysicalProvider(value string) string { + switch strings.TrimSpace(value) { + case "grok_build", "grok_web", "grok_console": + return strings.TrimSpace(value) + default: + return "unknown" + } +} + +func normalizePhysicalOperation(value string) string { + switch strings.TrimSpace(value) { + case "responses", "chat", "messages", "compaction", "response_get", "response_delete": + return strings.TrimSpace(value) + case "responses_compact": + return "compaction" + default: + return "other" + } +} + +func defaultPhysicalPlane(provider string) string { + switch provider { + case "grok_build": + return "build" + case "grok_web": + return "web" + case "grok_console": + return "console" + default: + return "unknown" + } +} + +func normalizePhysicalPlane(value string) string { + switch strings.TrimSpace(value) { + case "build", "xai", "web", "console": + return strings.TrimSpace(value) + default: + return "unknown" + } +} + +func normalizePhysicalStage(value string) string { + switch strings.TrimSpace(value) { + case "primary", "plane_fallback", "reasoning_replay", "reasoning_session_reset", "compaction", "compaction_retry", "anti_bot_retry", "statsig_meta": + return strings.TrimSpace(value) + default: + return "other" + } +} + +func physicalOrdinalBucket(value uint64) string { + if value >= 5 { + return "5_plus" + } + return strconv.FormatUint(value, 10) +} + +func physicalCallOutcome(response *http.Response, err error) string { + if err != nil { + return "transport_error" + } + if response == nil { + return "empty_response" + } + switch { + case response.StatusCode >= 200 && response.StatusCode < 300: + return "success" + case response.StatusCode >= 300 && response.StatusCode < 400: + return "redirect" + case response.StatusCode >= 400 && response.StatusCode < 500: + return "client_error" + case response.StatusCode >= 500 && response.StatusCode < 600: + return "server_error" + default: + return "other" + } +} diff --git a/backend/internal/infra/egress/physical_calls_test.go b/backend/internal/infra/egress/physical_calls_test.go new file mode 100644 index 00000000..86efd11d --- /dev/null +++ b/backend/internal/infra/egress/physical_calls_test.go @@ -0,0 +1,103 @@ +package egress + +import ( + "context" + "errors" + "net/http" + "testing" + + "github.com/chenyme/grok2api/backend/internal/pkg/perfmetrics" +) + +func TestPhysicalCallTraceRecordsPlaneStageOrdinalAndOutcome(t *testing.T) { + registry := perfmetrics.NewRegistry() + previous := perfmetrics.Default + perfmetrics.Default = registry + t.Cleanup(func() { perfmetrics.Default = previous }) + + ctx := WithPhysicalCallTrace(context.Background(), "grok_build", "responses") + recordPhysicalCall(ctx, &http.Response{StatusCode: http.StatusForbidden}, nil) + fallbackCtx := WithPhysicalCallPlane(WithPhysicalCallStage(ctx, "plane_fallback"), "xai") + recordPhysicalCall(fallbackCtx, &http.Response{StatusCode: http.StatusOK}, nil) + recordPhysicalCall(WithPhysicalCallStage(ctx, "reasoning_replay"), nil, errors.New("connection reset")) + + samples := registry.CollectAndReset() + assertPhysicalCallMetric(t, samples, "grok_build", "build", "primary", "1", "client_error") + assertPhysicalCallMetric(t, samples, "grok_build", "xai", "plane_fallback", "2", "success") + assertPhysicalCallMetric(t, samples, "grok_build", "build", "reasoning_replay", "3", "transport_error") +} + +func TestPhysicalCallTraceNormalizesCompactionOperation(t *testing.T) { + registry := perfmetrics.NewRegistry() + previous := perfmetrics.Default + perfmetrics.Default = registry + t.Cleanup(func() { perfmetrics.Default = previous }) + + ctx := WithPhysicalCallTrace(context.Background(), "grok_build", "compaction") + recordPhysicalCall(ctx, &http.Response{StatusCode: http.StatusOK}, nil) + legacyCtx := WithPhysicalCallTrace(context.Background(), "grok_build", "responses_compact") + recordPhysicalCall(legacyCtx, &http.Response{StatusCode: http.StatusOK}, nil) + + samples := registry.CollectAndReset() + var count uint64 + for _, sample := range samples { + if sample.Name == "upstream_physical_call_total" && sample.Labels.Operation == "compaction" { + count += sample.Count + } + if sample.Name == "upstream_physical_call_total" && sample.Labels.Operation == "other" { + t.Fatalf("compaction was classified as other: %#v", sample) + } + } + if count != 2 { + t.Fatalf("normalized compaction count = %d, want 2: %#v", count, samples) + } +} + +func TestProxyPoolConnectionRetriesCountAsOneProviderCall(t *testing.T) { + registry := perfmetrics.NewRegistry() + previous := perfmetrics.Default + perfmetrics.Default = registry + t.Cleanup(func() { perfmetrics.Default = previous }) + + client := &scriptedRequestClient{do: func(call int, _ *http.Request) (*http.Response, error) { + if call == 1 { + return nil, errors.New("proxyconnect tcp: connection refused") + } + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }} + lease := &Lease{client: client, proxyPool: true} + ctx := WithPhysicalCallTrace(context.Background(), "grok_web", "messages") + request, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://grok.com/rest/app-chat", http.NoBody) + if err != nil { + t.Fatal(err) + } + response, err := lease.Do(request) + if err != nil || response.StatusCode != http.StatusOK || client.calls != 2 { + t.Fatalf("response=%#v calls=%d err=%v", response, client.calls, err) + } + samples := registry.CollectAndReset() + assertPhysicalCallMetric(t, samples, "grok_web", "web", "primary", "1", "success") + var total uint64 + for _, sample := range samples { + if sample.Name == "upstream_physical_call_total" { + total += sample.Count + } + } + if total != 1 { + t.Fatalf("physical call count = %d, want 1: %#v", total, samples) + } +} + +func assertPhysicalCallMetric(t *testing.T, samples []perfmetrics.Sample, provider, plane, stage, ordinal, outcome string) { + t.Helper() + for _, sample := range samples { + labels := sample.Labels + if sample.Name == "upstream_physical_call_total" && labels.Provider == provider && labels.Plane == plane && labels.Stage == stage && labels.Ordinal == ordinal && labels.Outcome == outcome { + if sample.Count != 1 || sample.Total != 1 { + t.Fatalf("physical call sample = %#v", sample) + } + return + } + } + t.Fatalf("physical call metric not found: %#v", samples) +} diff --git a/backend/internal/infra/persistence/relational/selector_segmented_integration_test.go b/backend/internal/infra/persistence/relational/selector_segmented_integration_test.go index f3783725..72db8f32 100644 --- a/backend/internal/infra/persistence/relational/selector_segmented_integration_test.go +++ b/backend/internal/infra/persistence/relational/selector_segmented_integration_test.go @@ -38,7 +38,11 @@ func TestPostgresRedisSegmentedSelectorIntegration(t *testing.T) { if err != nil { t.Fatal(err) } - defer database.Close() + t.Cleanup(func() { + if err := database.Close(); err != nil { + t.Errorf("close PostgreSQL integration database: %v", err) + } + }) if err := database.InitializeSchema(ctx); err != nil { t.Fatal(err) } diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 3d6e1122..1d74a64b 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -212,7 +212,8 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response fallbackBase := a.fallbackBaseURL() if fallbackBase != "" && !strings.EqualFold(fallbackBase, base) { fallbackBody, fallbackReplayKey := a.applyReasoningReplay(ctx, request, replayBaseBody, fallbackBase) - fallbackResp, fallbackURL, fallbackErr := a.doResponseRequest(ctx, request, accessToken, fallbackBody, fallbackBase) + fallbackCtx := infraegress.WithPhysicalCallStage(ctx, "plane_fallback") + fallbackResp, fallbackURL, fallbackErr := a.doResponseRequest(fallbackCtx, request, accessToken, fallbackBody, fallbackBase) if fallbackErr == nil { fallbackErr = normalizeGzipResponse(fallbackResp) } @@ -369,6 +370,11 @@ func (a *Adapter) doResponseRequest(ctx context.Context, request provider.Respon bodyReader = bytes.NewReader(body) } requestCtx := infraegress.WithCredential(ctx, request.Credential) + plane := "build" + if fallback := a.fallbackBaseURL(); fallback != "" && strings.EqualFold(strings.TrimRight(base, "/"), fallback) { + plane = "xai" + } + requestCtx = infraegress.WithPhysicalCallPlane(requestCtx, plane) req, err := http.NewRequestWithContext(requestCtx, request.Method, a.urlWithBase(base, request.Path), bodyReader) if err != nil { return nil, "", err diff --git a/backend/internal/infra/provider/cli/egress.go b/backend/internal/infra/provider/cli/egress.go index b46e1cdd..b73a8e3f 100644 --- a/backend/internal/infra/provider/cli/egress.go +++ b/backend/internal/infra/provider/cli/egress.go @@ -24,7 +24,9 @@ func (t *egressTransport) RoundTrip(request *http.Request) (*http.Response, erro return nil, err } if !configured { - return t.fallback.RoundTrip(request) + response, requestErr := t.fallback.RoundTrip(request) + infraegress.RecordDirectPhysicalCall(request.Context(), response, requestErr) + return response, requestErr } if lease.UserAgent != "" { request.Header.Set("User-Agent", lease.UserAgent) diff --git a/backend/internal/infra/provider/cli/responses_compaction_forward.go b/backend/internal/infra/provider/cli/responses_compaction_forward.go index 62baa973..93e2e518 100644 --- a/backend/internal/infra/provider/cli/responses_compaction_forward.go +++ b/backend/internal/infra/provider/cli/responses_compaction_forward.go @@ -15,6 +15,7 @@ import ( "github.com/google/uuid" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" ) @@ -68,7 +69,12 @@ func (a *Adapter) forwardGatewayCompactionWithPolicy( var lastErr error for attempt := 1; attempt <= maxAttempts; attempt++ { - resp, reqURL, err := a.doResponseRequest(ctx, upstreamRequest, accessToken, body, base) + stage := "compaction" + if attempt > 1 { + stage = "compaction_retry" + } + attemptCtx := infraegress.WithPhysicalCallStage(ctx, stage) + resp, reqURL, err := a.doResponseRequest(attemptCtx, upstreamRequest, accessToken, body, base) if err != nil { lastErr = err if attempt < maxAttempts && waitGatewayCompactionRetry(ctx, retryDelay) { @@ -86,7 +92,8 @@ func (a *Adapter) forwardGatewayCompactionWithPolicy( primaryResp := cloneBufferedResponse(resp, primaryBody, primaryTruncated) fallbackBase := a.fallbackBaseURL() if fallbackBase != "" && !strings.EqualFold(fallbackBase, base) { - fallbackResp, fallbackURL, fallbackErr := a.doResponseRequest(ctx, upstreamRequest, accessToken, body, fallbackBase) + fallbackCtx := infraegress.WithPhysicalCallStage(attemptCtx, "plane_fallback") + fallbackResp, fallbackURL, fallbackErr := a.doResponseRequest(fallbackCtx, upstreamRequest, accessToken, body, fallbackBase) if fallbackErr == nil && isHTTPSuccess(fallbackResp.StatusCode) { a.activateBuildAPIFallback(ctx, &request.Credential) resp, reqURL, base = fallbackResp, fallbackURL, fallbackBase diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go index cde1161d..e0527dce 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go @@ -7,6 +7,7 @@ import ( "net/http" "strings" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/security" ) @@ -154,11 +155,13 @@ func (a *Adapter) recoverReasoningDecodeFailure( func (a *Adapter) retryReasoningRecovery(ctx context.Context, request provider.ResponseResourceRequest, accessToken string, body []byte, base string, resetSession bool) (*http.Response, string, error) { retryRequest := request retryRequest.IdempotencyID, _ = security.NewOpaqueToken(18) + stage := "reasoning_replay" if resetSession { retryRequest.PromptCacheKey = "" retryRequest.GrokTurnIndex = "" + stage = "reasoning_session_reset" } - return a.doResponseRequest(ctx, retryRequest, accessToken, body, base) + return a.doResponseRequest(infraegress.WithPhysicalCallStage(ctx, stage), retryRequest, accessToken, body, base) } func responseHasReasoningDecodeFailure(response *http.Response) (bool, error) { diff --git a/backend/internal/infra/provider/web/chat.go b/backend/internal/infra/provider/web/chat.go index 3e556af1..29adfac2 100644 --- a/backend/internal/infra/provider/web/chat.go +++ b/backend/internal/infra/provider/web/chat.go @@ -165,7 +165,11 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response var parsed parsedChat var previous *inferencedomain.WebResponseState for attempt := 0; attempt < 2; attempt++ { - upstream, lease, currentPrevious, statsigTarget, openErr := a.openChat(ctx, request.Credential, input.PreviousResponseID, spec, normalized) + attemptCtx := ctx + if attempt > 0 { + attemptCtx = infraegress.WithPhysicalCallStage(ctx, "anti_bot_retry") + } + upstream, lease, currentPrevious, statsigTarget, openErr := a.openChat(attemptCtx, request.Credential, input.PreviousResponseID, spec, normalized) if openErr != nil { if errors.Is(openErr, errInvalidChatAttachment) || errors.Is(openErr, errInvalidChatImage) || errors.Is(openErr, errInvalidChatFile) { code := "invalid_attachment_input" diff --git a/backend/internal/infra/provider/web/statsig.go b/backend/internal/infra/provider/web/statsig.go index 1de90a95..3f3e85fd 100644 --- a/backend/internal/infra/provider/web/statsig.go +++ b/backend/internal/infra/provider/web/statsig.go @@ -272,7 +272,7 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease * if lease == nil { return "", fmt.Errorf("Statsig 获取缺少出口租约") } - requestCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + requestCtx, cancel := context.WithTimeout(infraegress.WithPhysicalCallStage(ctx, "statsig_meta"), 15*time.Second) defer cancel() request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/index", nil) if err != nil { diff --git a/backend/internal/pkg/perfmetrics/registry.go b/backend/internal/pkg/perfmetrics/registry.go index 67baa744..de845a5a 100644 --- a/backend/internal/pkg/perfmetrics/registry.go +++ b/backend/internal/pkg/perfmetrics/registry.go @@ -13,7 +13,9 @@ type Labels struct { Subsystem string Operation string Provider string + Plane string Stage string + Ordinal string Outcome string } @@ -48,7 +50,9 @@ type registryShard struct { } type Registry struct { - shards [registryShardCount]registryShard + shards [registryShardCount]registryShard + dynamicMu sync.RWMutex + dynamicGauges map[metricKey]func() int64 } func NewRegistry() *Registry { @@ -56,6 +60,7 @@ func NewRegistry() *Registry { for index := range registry.shards { registry.shards[index].values = make(map[metricKey]metricValue) } + registry.dynamicGauges = make(map[metricKey]func() int64) return registry } @@ -100,6 +105,22 @@ func (r *Registry) SetGauge(name string, labels Labels, value int64) { shard.mu.Unlock() } +// RegisterDynamicGauge exposes a bounded gauge whose value is read only when +// metrics are collected. The callback must be non-blocking and side-effect +// free; it is intended for atomic runtime state such as active request bytes. +func (r *Registry) RegisterDynamicGauge(name string, labels Labels, read func() int64) { + if r == nil || name == "" || read == nil { + return + } + key := metricKey{name: name, labels: labels} + r.dynamicMu.Lock() + if r.dynamicGauges == nil { + r.dynamicGauges = make(map[metricKey]func() int64) + } + r.dynamicGauges[key] = read + r.dynamicMu.Unlock() +} + // CollectAndReset returns interval counters while retaining the latest gauge // values for the next collection window. func (r *Registry) CollectAndReset() []Sample { @@ -127,6 +148,27 @@ func (r *Registry) CollectAndReset() []Sample { } shard.mu.Unlock() } + r.dynamicMu.RLock() + dynamic := make(map[metricKey]func() int64, len(r.dynamicGauges)) + for key, read := range r.dynamicGauges { + dynamic[key] = read + } + r.dynamicMu.RUnlock() + for key, read := range dynamic { + value := Sample{Name: key.name, Labels: key.labels, Gauge: read(), HasGauge: true} + found := false + for index := range result { + if result[index].Name == key.name && result[index].Labels == key.labels { + result[index].Gauge = value.Gauge + result[index].HasGauge = true + found = true + break + } + } + if !found { + result = append(result, value) + } + } sort.Slice(result, func(i, j int) bool { if result[i].Name != result[j].Name { return result[i].Name < result[j].Name @@ -142,7 +184,9 @@ func (r *Registry) shard(key metricKey) *registryShard { hash = hashMetricString(hash, key.labels.Subsystem) hash = hashMetricString(hash, key.labels.Operation) hash = hashMetricString(hash, key.labels.Provider) + hash = hashMetricString(hash, key.labels.Plane) hash = hashMetricString(hash, key.labels.Stage) + hash = hashMetricString(hash, key.labels.Ordinal) hash = hashMetricString(hash, key.labels.Outcome) return &r.shards[hash%registryShardCount] } @@ -157,5 +201,5 @@ func hashMetricString(hash uint64, value string) uint64 { } func labelsKey(value Labels) string { - return value.Subsystem + "\x00" + value.Operation + "\x00" + value.Provider + "\x00" + value.Stage + "\x00" + value.Outcome + return value.Subsystem + "\x00" + value.Operation + "\x00" + value.Provider + "\x00" + value.Plane + "\x00" + value.Stage + "\x00" + value.Ordinal + "\x00" + value.Outcome } diff --git a/backend/internal/pkg/perfmetrics/registry_test.go b/backend/internal/pkg/perfmetrics/registry_test.go index e848cfc1..eff86d55 100644 --- a/backend/internal/pkg/perfmetrics/registry_test.go +++ b/backend/internal/pkg/perfmetrics/registry_test.go @@ -25,6 +25,23 @@ func TestCollectAndResetRetainsGaugeAndClearsIntervalCounters(t *testing.T) { } } +func TestCollectAndResetReadsDynamicGaugeAtCollectionTime(t *testing.T) { + registry := NewRegistry() + labels := Labels{Subsystem: "http"} + var value int64 = 7 + registry.RegisterDynamicGauge("active_bytes", labels, func() int64 { return value }) + + first := registry.CollectAndReset() + if len(first) != 1 || !first[0].HasGauge || first[0].Gauge != 7 { + t.Fatalf("first dynamic gauge sample = %#v", first) + } + value = 11 + second := registry.CollectAndReset() + if len(second) != 1 || !second[0].HasGauge || second[0].Gauge != 11 { + t.Fatalf("second dynamic gauge sample = %#v", second) + } +} + func BenchmarkRegistryParallel(b *testing.B) { registry := NewRegistry() labels := Labels{Subsystem: "gateway", Operation: "responses", Provider: "grok_build", Stage: "upstream", Outcome: "success"} diff --git a/backend/internal/transport/http/middleware/body_memory.go b/backend/internal/transport/http/middleware/body_memory.go new file mode 100644 index 00000000..baab60a9 --- /dev/null +++ b/backend/internal/transport/http/middleware/body_memory.go @@ -0,0 +1,102 @@ +package middleware + +import ( + "io" + "net/http" + "strings" + "sync/atomic" + + "github.com/chenyme/grok2api/backend/internal/pkg/perfmetrics" + "github.com/gin-gonic/gin" +) + +type bodyMemoryObserver struct { + active atomic.Int64 + registry *perfmetrics.Registry +} + +type observedRequestBody struct { + io.ReadCloser + observer *bodyMemoryObserver + read atomic.Int64 + peak atomic.Int64 +} + +// ObserveBodyMemory records request-body pressure without delaying or +// rejecting requests. The tracked bytes remain active until the handler +// returns because JSON handlers retain their decoded body for that lifetime. +func ObserveBodyMemory() gin.HandlerFunc { + return newBodyMemoryObserver().Middleware() +} + +func newBodyMemoryObserver() *bodyMemoryObserver { + registry := perfmetrics.Default + observer := &bodyMemoryObserver{registry: registry} + registry.RegisterDynamicGauge("http_request_body_active_bytes", perfmetrics.Labels{Subsystem: "http"}, observer.active.Load) + return observer +} + +func (o *bodyMemoryObserver) Middleware() gin.HandlerFunc { + return func(c *gin.Context) { + if c.Request.Body == nil || c.Request.Body == http.NoBody { + c.Next() + return + } + mode := "unknown_length" + if c.Request.ContentLength >= 0 { + mode = "known_length" + } + operation := inferenceBodyOperation(c.Request.URL.Path) + labels := perfmetrics.Labels{Subsystem: "http", Operation: operation, Stage: mode} + if c.Request.ContentLength > 0 { + o.registry.Add("http_request_body_declared_bytes", labels, c.Request.ContentLength) + } + body := &observedRequestBody{ReadCloser: c.Request.Body, observer: o} + c.Request.Body = body + defer func() { + read := body.read.Load() + o.active.Add(-read) + o.registry.Inc("http_request_body_total", labels) + o.registry.Add("http_request_body_read_bytes", labels, read) + o.registry.Add("http_request_body_active_peak_bytes", labels, body.peak.Load()) + }() + c.Next() + } +} + +func (b *observedRequestBody) Read(buffer []byte) (int, error) { + read, err := b.ReadCloser.Read(buffer) + if read <= 0 { + return read, err + } + b.read.Add(int64(read)) + current := b.observer.active.Add(int64(read)) + for { + peak := b.peak.Load() + if current <= peak || b.peak.CompareAndSwap(peak, current) { + break + } + } + return read, err +} + +func inferenceBodyOperation(path string) string { + switch strings.TrimSuffix(path, "/") { + case "/v1/responses": + return "responses" + case "/v1/responses/compact": + return "responses_compact" + case "/v1/chat/completions": + return "chat" + case "/v1/messages": + return "messages" + case "/v1/images/generations": + return "image_generation" + case "/v1/images/edits": + return "image_edit" + case "/v1/videos/generations": + return "video_generation" + default: + return "other" + } +} diff --git a/backend/internal/transport/http/middleware/request_test.go b/backend/internal/transport/http/middleware/request_test.go index 0ab7bf02..711c3305 100644 --- a/backend/internal/transport/http/middleware/request_test.go +++ b/backend/internal/transport/http/middleware/request_test.go @@ -6,7 +6,9 @@ import ( "net/http/httptest" "strings" "testing" + "time" + "github.com/chenyme/grok2api/backend/internal/pkg/perfmetrics" "github.com/gin-gonic/gin" ) @@ -45,6 +47,170 @@ func TestMaxBodyBytesLimitsAllRequestBodies(t *testing.T) { } } +func TestObserveBodyMemoryRecordsActualAndDeclaredBytes(t *testing.T) { + registry := perfmetrics.NewRegistry() + previous := perfmetrics.Default + perfmetrics.Default = registry + t.Cleanup(func() { perfmetrics.Default = previous }) + + gin.SetMode(gin.TestMode) + router := gin.New() + router.Use(ObserveBodyMemory()) + router.POST("/v1/responses", func(c *gin.Context) { + if _, err := io.ReadAll(c.Request.Body); err != nil { + c.Status(http.StatusBadRequest) + return + } + c.Status(http.StatusNoContent) + }) + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader("12345")) + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if response.Code != http.StatusNoContent { + t.Fatalf("status = %d", response.Code) + } + + samples := registry.CollectAndReset() + assertBodyMetric(t, samples, "http_request_body_total", "responses", "known_length", 1, 1, 1) + assertBodyMetric(t, samples, "http_request_body_declared_bytes", "responses", "known_length", 1, 5, 5) + assertBodyMetric(t, samples, "http_request_body_read_bytes", "responses", "known_length", 1, 5, 5) + assertBodyMetric(t, samples, "http_request_body_active_peak_bytes", "responses", "known_length", 1, 5, 5) + assertBodyGauge(t, samples, "http_request_body_active_bytes", 0) +} + +func TestObserveBodyMemoryMeasuresConcurrentRetention(t *testing.T) { + registry := perfmetrics.NewRegistry() + previous := perfmetrics.Default + perfmetrics.Default = registry + t.Cleanup(func() { perfmetrics.Default = previous }) + + gin.SetMode(gin.TestMode) + started := make(chan struct{}, 2) + release := make(chan struct{}) + router := gin.New() + router.Use(newBodyMemoryObserver().Middleware()) + router.POST("/v1/messages", func(c *gin.Context) { + _, _ = io.ReadAll(c.Request.Body) + started <- struct{}{} + <-release + c.Status(http.StatusNoContent) + }) + + done := make(chan struct{}, 2) + for range 2 { + go func() { + response := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader("1234")) + router.ServeHTTP(response, request) + if response.Code != http.StatusNoContent { + t.Errorf("status = %d", response.Code) + } + done <- struct{}{} + }() + } + for range 2 { + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("request did not retain its body") + } + } + activeSamples := registry.CollectAndReset() + assertBodyGauge(t, activeSamples, "http_request_body_active_bytes", 8) + close(release) + for range 2 { + <-done + } + + samples := registry.CollectAndReset() + assertBodyMetric(t, samples, "http_request_body_active_peak_bytes", "messages", "known_length", 2, 12, 8) + assertBodyGauge(t, samples, "http_request_body_active_bytes", 0) +} + +func TestObserveBodyMemoryReleasesPressureAfterRecoveredPanic(t *testing.T) { + registry := perfmetrics.NewRegistry() + previous := perfmetrics.Default + perfmetrics.Default = registry + t.Cleanup(func() { perfmetrics.Default = previous }) + + gin.SetMode(gin.TestMode) + observer := newBodyMemoryObserver() + router := gin.New() + router.Use(gin.Recovery(), observer.Middleware()) + router.POST("/v1/responses", func(c *gin.Context) { + _, _ = io.ReadAll(c.Request.Body) + panic("boom") + }) + response := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader("12345")) + router.ServeHTTP(response, request) + if response.Code != http.StatusInternalServerError { + t.Fatalf("status = %d", response.Code) + } + if current := observer.active.Load(); current != 0 { + t.Fatalf("active body bytes after recovered panic = %d", current) + } + + samples := registry.CollectAndReset() + assertBodyMetric(t, samples, "http_request_body_total", "responses", "known_length", 1, 1, 1) + assertBodyMetric(t, samples, "http_request_body_read_bytes", "responses", "known_length", 1, 5, 5) + assertBodyGauge(t, samples, "http_request_body_active_bytes", 0) +} + +func assertBodyMetric(t *testing.T, samples []perfmetrics.Sample, name, operation, stage string, count uint64, total, maximum int64) { + t.Helper() + for _, sample := range samples { + if sample.Name == name && sample.Labels.Operation == operation && sample.Labels.Stage == stage { + if sample.Count != count || sample.Total != total || sample.Maximum != maximum { + t.Fatalf("%s sample = %#v", name, sample) + } + return + } + } + t.Fatalf("metric %s/%s/%s not found: %#v", name, operation, stage, samples) +} + +func assertBodyGauge(t *testing.T, samples []perfmetrics.Sample, name string, value int64) { + t.Helper() + for _, sample := range samples { + if sample.Name == name { + if !sample.HasGauge || sample.Gauge != value { + t.Fatalf("%s gauge = %#v", name, sample) + } + return + } + } + t.Fatalf("gauge %s not found: %#v", name, samples) +} + +func BenchmarkRequestBodyObservation(b *testing.B) { + payload := strings.Repeat("x", 4<<10) + for _, observed := range []bool{false, true} { + name := "plain" + if observed { + name = "observed" + } + b.Run(name, func(b *testing.B) { + gin.SetMode(gin.TestMode) + router := gin.New() + if observed { + router.Use(ObserveBodyMemory()) + } + router.POST("/v1/responses", func(c *gin.Context) { + _, _ = io.Copy(io.Discard, c.Request.Body) + c.Status(http.StatusNoContent) + }) + b.ReportAllocs() + b.RunParallel(func(worker *testing.PB) { + for worker.Next() { + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(payload)) + router.ServeHTTP(httptest.NewRecorder(), request) + } + }) + }) + } +} + func TestSecurityHeaders(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() diff --git a/backend/internal/transport/http/server.go b/backend/internal/transport/http/server.go index b74c5413..09ab1d87 100644 --- a/backend/internal/transport/http/server.go +++ b/backend/internal/transport/http/server.go @@ -158,6 +158,7 @@ func New(deps Dependencies) *gin.Engine { v1 := router.Group("/v1") v1.Use(deps.ConcurrencyGate.Middleware()) + v1.Use(middleware.ObserveBodyMemory()) if deps.TrafficReady != nil { v1.Use(func(c *gin.Context) { if deps.TrafficReady() {