From c426b5cc76a43e0ff34f77ee5e68daeb9124db94 Mon Sep 17 00:00:00 2001 From: name <136912576+is7Qin@users.noreply.github.com> Date: Wed, 19 Aug 2026 04:16:34 +0800 Subject: [PATCH] fix(scheduler): repair support decision publication shadow --- .../service/support_decision_builder.go | 91 +++- .../service/support_decision_legacy_oracle.go | 264 +++++++--- .../service/support_decision_review_test.go | 473 +++++++++++++++++- 3 files changed, 722 insertions(+), 106 deletions(-) diff --git a/backend/internal/service/support_decision_builder.go b/backend/internal/service/support_decision_builder.go index e83814c71e0a..d78e59d7939e 100644 --- a/backend/internal/service/support_decision_builder.go +++ b/backend/internal/service/support_decision_builder.go @@ -379,6 +379,18 @@ func buildSupportDecisionScopeContext(ctx context.Context, scope *supportDecisio } } } + channelExact, channelWildcard, channelCatchAll, err := supportDecisionChannelModelPatternsContext(ctx, scope) + if err != nil { + return supportDecisionTemporaryScope{}, err + } + if openAI { + for _, model := range channelExact { + exactSet[model] = struct{}{} + } + for _, prefix := range channelWildcard { + wildcardSet[prefix] = struct{}{} + } + } if len(exactSet) > SupportDecisionExactLimit { return supportDecisionTemporaryScope{}, fmt.Errorf("scope %+v has %d exact keys; limit is %d", scope.key, len(exactSet), SupportDecisionExactLimit) } @@ -448,7 +460,7 @@ func buildSupportDecisionScopeContext(ctx context.Context, scope *supportDecisio return supportDecisionTemporaryScope{}, err } // Terminal wildcard mappings have a constant target under the frozen mapper. - probe := prefix + "__support_decision_probe__" + probe := supportDecisionWildcardProbe(prefix, exactSet, wildcardSet, built.hot) profile, err := evaluateSupportDecisionModelContext(ctx, scope, probe, coordinateCount, wsConfig) if err != nil { return supportDecisionTemporaryScope{}, err @@ -461,14 +473,13 @@ func buildSupportDecisionScopeContext(ctx context.Context, scope *supportDecisio built.wildcard[prefix] = rule } } - channelExact, channelWildcard, channelCatchAll, err := supportDecisionChannelModelPatternsContext(ctx, scope) - if err != nil { - return supportDecisionTemporaryScope{}, err - } built.channelExact = channelExact built.channelWildcard = channelWildcard built.channelCatchAll = channelCatchAll - wildcardCount := len(built.wildcard) + len(built.channelWildcard) + wildcardCount := len(built.wildcard) + if !openAI { + wildcardCount += len(built.channelWildcard) + } if built.catchAll != nil { wildcardCount++ } @@ -478,8 +489,12 @@ func buildSupportDecisionScopeContext(ctx context.Context, scope *supportDecisio if wildcardCount > SupportDecisionWildcardLimit { return supportDecisionTemporaryScope{}, fmt.Errorf("scope %+v has %d wildcard rules; limit is %d", scope.key, wildcardCount, SupportDecisionWildcardLimit) } - if len(built.exact)+len(built.channelExact) > SupportDecisionExactLimit { - return supportDecisionTemporaryScope{}, fmt.Errorf("scope %+v has %d exact keys; limit is %d", scope.key, len(built.exact)+len(built.channelExact), SupportDecisionExactLimit) + exactCount := len(built.exact) + if !openAI { + exactCount += len(built.channelExact) + } + if exactCount > SupportDecisionExactLimit { + return supportDecisionTemporaryScope{}, fmt.Errorf("scope %+v has %d exact keys; limit is %d", scope.key, exactCount, SupportDecisionExactLimit) } hasChannelPolicy := built.channelCatchAll || len(built.channelExact) > 0 || len(built.channelWildcard) > 0 built.fallback, err = evaluateSupportDecisionWithoutModelContext(ctx, scope, coordinateCount, wsConfig, false, hasChannelPolicy) @@ -607,6 +622,37 @@ func sortedStringSet(values map[string]struct{}) []string { return result } +// supportDecisionWildcardProbe selects a reachable model for one wildcard rule. +// It avoids exact/hot models and longer wildcard prefixes while staying within +// the wire model limit; an unreachable rule only needs a valid bounded label. +func supportDecisionWildcardProbe(prefix string, exact map[string]struct{}, wildcard map[string]struct{}, hot map[string]supportDecisionProfile) string { + blocked := &supportDecisionPrefixTrie{} + for other := range wildcard { + if other == prefix || len(other) <= len(prefix) || !strings.HasPrefix(other, prefix) { + continue + } + blocked.insert(strings.TrimPrefix(other, prefix)) + } + minLength := len(prefix) + if minLength == 0 { + minLength = 1 + } + pointBlocked := func(model string) bool { + if _, exists := exact[model]; exists { + return true + } + _, exists := hot[model] + return exists + } + if witness, ok := supportDecisionShadowComplement(blocked, prefix, minLength, pointBlocked); ok { + return witness + } + if prefix != "" { + return prefix + } + return "\x00" +} + func supportDecisionScopeHasBedrock(scope *supportDecisionBuildScope) bool { result, _ := supportDecisionScopeHasBedrockContext(context.Background(), scope) return result @@ -729,7 +775,13 @@ func supportDecisionRuleTargetContext(ctx context.Context, scope *supportDecisio } } // Multiple accounts may map the same source differently. The aggregate profile - // already folds those identities, so retain a deterministic non-secret label. + // already folds those identities, so retain a deterministic bounded label. + if len(probe) > SupportDecisionMaxModelBytes { + if mappingKey != "" { + return mappingKey, nil + } + return "\x00", nil + } return probe, nil } @@ -841,6 +893,7 @@ func evaluateSupportDecisionWithoutModelContext(ctx context.Context, scope *supp query.RequiresPrivacy = coordinate&1 != 0 query.ThinkingEnabled = coordinate&2 != 0 } + otherwiseEligible := false for _, account := range scope.accounts { if err := ctx.Err(); err != nil { return supportDecisionProfile{}, err @@ -854,13 +907,16 @@ func evaluateSupportDecisionWithoutModelContext(ctx context.Context, scope *supp } if supportDecisionAccountSupportsEveryModel(scope, account) { setBit(profile.SupportBits, coordinate) + otherwiseEligible = false break } if supportDecisionAccountEligibleWithoutModel(scope, account, query, wsConfig, channelAllowed, hasChannelPolicy) { - setBit(profile.EligibleBits, coordinate) - break + otherwiseEligible = true } } + if !bitSet(profile.SupportBits, coordinate) && otherwiseEligible { + setBit(profile.EligibleBits, coordinate) + } } return profile, nil } @@ -964,6 +1020,9 @@ func supportDecisionUpstreamRestricted(channel *SupportDecisionChannel, platform } func supportDecisionChannelAllowsModel(channel *SupportDecisionChannel, platform, model string) bool { + if channel == nil { + return false + } model = strings.ToLower(model) alias := claudePricingRevisionAlias(model) for _, pricing := range channel.PricingModels { @@ -1172,7 +1231,10 @@ func supportDecisionSerializedFallbackSize(scope *supportDecisionScopeTable, glo } func validateSupportDecisionScopeBudgets(scope *supportDecisionScopeTable, globalStrings []string) error { - wildcardCount := len(scope.Wildcard) + len(scope.ChannelWildcard) + wildcardCount := len(scope.Wildcard) + if !scope.OpenAI { + wildcardCount += len(scope.ChannelWildcard) + } if scope.CatchAll != nil { wildcardCount++ } @@ -1182,7 +1244,10 @@ func validateSupportDecisionScopeBudgets(scope *supportDecisionScopeTable, globa if wildcardCount > SupportDecisionWildcardLimit { return fmt.Errorf("scope %+v has %d wildcard rules; limit is %d", scope.Key, wildcardCount, SupportDecisionWildcardLimit) } - exactCount := len(scope.ExactWire) + len(scope.ChannelExact) + exactCount := len(scope.ExactWire) + if !scope.OpenAI { + exactCount += len(scope.ChannelExact) + } if exactCount > SupportDecisionExactLimit { return fmt.Errorf("scope %+v has %d exact keys; limit is %d", scope.Key, exactCount, SupportDecisionExactLimit) } diff --git a/backend/internal/service/support_decision_legacy_oracle.go b/backend/internal/service/support_decision_legacy_oracle.go index d8d6c3c8d266..743b5da444fb 100644 --- a/backend/internal/service/support_decision_legacy_oracle.go +++ b/backend/internal/service/support_decision_legacy_oracle.go @@ -113,9 +113,10 @@ type supportDecisionLegacyAccountFact struct { } type supportDecisionLegacyCompiledProfile struct { - supported bool - eligibleFixed []byte - eligibleRequested []byte + supported bool + eligibleFixed []byte + eligibleRequested []byte + eligibleCompactRequested []byte } type supportDecisionLegacyMappingEvent struct { @@ -125,8 +126,10 @@ type supportDecisionLegacyMappingEvent struct { } type supportDecisionLegacyMappingState struct { - event supportDecisionLegacyMappingEvent - active bool + ordinary supportDecisionLegacyMappingEvent + compact supportDecisionLegacyMappingEvent + ordinaryActive bool + compactActive bool } type supportDecisionLegacyTrie struct { @@ -146,7 +149,6 @@ type supportDecisionLegacyScopeOracle struct { openAISupportAll bool openAISupportCodex bool openAIChannelRestricted bool - openAIEligible []byte openAIRoot *supportDecisionLegacyTrie } @@ -247,7 +249,6 @@ func supportDecisionLegacyImageBits(account *Account) uint8 { func (o *supportDecisionLegacyScopeOracle) buildOpenAIIndex(ctx context.Context) error { byteCount := (supportDecisionOpenAICoordinateCount + 7) / 8 - o.openAIEligible = make([]byte, byteCount) o.openAIChannelRestricted = o.channel != nil && o.channel.Status == StatusActive && o.channel.RestrictModels && o.channel.BillingModelSource == BillingModelSourceUpstream o.openAIRoot = &supportDecisionLegacyTrie{} for i := range o.accounts { @@ -263,7 +264,6 @@ func (o *supportDecisionLegacyScopeOracle) buildOpenAIIndex(ctx context.Context) supportDecisionCountShadowOperation(ctx) if supportDecisionLegacyOpenAIEligibleWithoutModel(fact, decodeOpenAICoordinate(coordinate)) { setBit(fact.eligible, coordinate) - setBit(o.openAIEligible, coordinate) } } switch { @@ -279,6 +279,12 @@ func (o *supportDecisionLegacyScopeOracle) buildOpenAIIndex(ctx context.Context) o.openAIRoot.insertWildcard(wildcard.prefix, supportDecisionLegacyMappingEvent{account: i, target: wildcard.target}) } } + for model, target := range fact.compactExact { + o.openAIRoot.insert(model, supportDecisionLegacyMappingEvent{account: i, target: target, compact: true}) + } + for _, wildcard := range fact.compactWildcards { + o.openAIRoot.insertWildcard(wildcard.prefix, supportDecisionLegacyMappingEvent{account: i, target: wildcard.target, compact: true}) + } } return o.openAIRoot.compile(ctx, o) } @@ -334,28 +340,169 @@ func supportDecisionLegacyOrBits(dst, src []byte) { } } -func supportDecisionLegacyClearBits(dst []byte) { - for i := range dst { - dst[i] = 0 +// supportDecisionLegacyProfileAccumulator aggregates account contributions while +// traversing the bounded mapping trie, so each shadow witness remains O(model length). +type supportDecisionLegacyProfileAccumulator struct { + supported int + fixedCount []int + requestedCount []int + compactRequestedCount []int + fixed []byte + requested []byte + compactRequested []byte +} + +func newSupportDecisionLegacyProfileAccumulator() *supportDecisionLegacyProfileAccumulator { + byteCount := (supportDecisionOpenAICoordinateCount + 7) / 8 + return &supportDecisionLegacyProfileAccumulator{ + fixedCount: make([]int, supportDecisionOpenAICoordinateCount), + requestedCount: make([]int, supportDecisionOpenAICoordinateCount), + compactRequestedCount: make([]int, supportDecisionOpenAICoordinateCount), + fixed: make([]byte, byteCount), + requested: make([]byte, byteCount), + compactRequested: make([]byte, byteCount), } } +func (a *supportDecisionLegacyProfileAccumulator) change(bits []byte, counts []int, coordinate, delta int) { + counts[coordinate] += delta + if counts[coordinate] > 0 { + setBit(bits, coordinate) + return + } + bits[coordinate>>3] &^= 1 << uint(coordinate&7) +} + +func (a *supportDecisionLegacyProfileAccumulator) adjust(oracle *supportDecisionLegacyScopeOracle, account int, state supportDecisionLegacyMappingState, delta int) { + fact := &oracle.accounts[account] + if !fact.account.IsOpenAI() { + return + } + + ordinaryValid := true + if state.ordinaryActive && fact.account.IsOpenAIOAuth() { + _, ordinaryValid = normalizeKnownCodexModel(strings.TrimSpace(state.ordinary.target)) + } + ordinaryInvalid := state.ordinaryActive && !ordinaryValid + if state.ordinaryActive && !ordinaryInvalid { + a.supported += delta + } + + if !oracle.openAIChannelRestricted { + if !state.ordinaryActive || ordinaryInvalid { + for coordinate := 0; coordinate < supportDecisionOpenAICoordinateCount; coordinate++ { + if bitSet(fact.eligible, coordinate) { + a.change(a.fixed, a.fixedCount, coordinate, delta) + } + } + } + return + } + + // A present ordinary mapping fixes the upstream target even when OAuth + // rejects that target as unsupported. Requested-dependent masks apply only + // when no ordinary mapping is active at the current trie path. + ordinaryFixed := state.ordinaryActive + ordinaryAllowed := false + compactFixed := false + compactAllowed := false + if state.ordinaryActive { + ordinaryAllowed = supportDecisionChannelAllowsModel(oracle.channel, oracle.key.Platform, state.ordinary.target) + compactTarget := state.ordinary.target + if mapped, matched := supportDecisionLegacyResolve(fact.compactExact, fact.compactWildcards, compactTarget); matched { + compactTarget = mapped + } + compactFixed = true + compactAllowed = supportDecisionChannelAllowsModel(oracle.channel, oracle.key.Platform, compactTarget) + } else if state.compactActive { + compactFixed = true + compactAllowed = supportDecisionChannelAllowsModel(oracle.channel, oracle.key.Platform, state.compact.target) + } + + for coordinate := 0; coordinate < supportDecisionOpenAICoordinateCount; coordinate++ { + if !bitSet(fact.eligible, coordinate) { + continue + } + if decodeOpenAICoordinate(coordinate).RequireCompact { + switch { + case compactFixed && compactAllowed: + a.change(a.fixed, a.fixedCount, coordinate, delta) + case !compactFixed: + a.change(a.compactRequested, a.compactRequestedCount, coordinate, delta) + } + continue + } + if ordinaryFixed && ordinaryAllowed { + a.change(a.fixed, a.fixedCount, coordinate, delta) + } else if !ordinaryFixed { + a.change(a.requested, a.requestedCount, coordinate, delta) + } + } +} + +func (a *supportDecisionLegacyProfileAccumulator) profile() supportDecisionLegacyCompiledProfile { + return supportDecisionLegacyCompiledProfile{ + supported: a.supported > 0, + eligibleFixed: cloneSupportDecisionBits(a.fixed), + eligibleRequested: cloneSupportDecisionBits(a.requested), + eligibleCompactRequested: cloneSupportDecisionBits(a.compactRequested), + } +} + +func applySupportDecisionLegacyMappingEvent(state supportDecisionLegacyMappingState, event supportDecisionLegacyMappingEvent) supportDecisionLegacyMappingState { + if event.compact { + state.compact = event + state.compactActive = true + } else { + state.ordinary = event + state.ordinaryActive = true + } + return state +} + func (n *supportDecisionLegacyTrie) compile(ctx context.Context, oracle *supportDecisionLegacyScopeOracle) error { states := make([]supportDecisionLegacyMappingState, len(oracle.accounts)) + aggregate := newSupportDecisionLegacyProfileAccumulator() + for account := range states { + aggregate.adjust(oracle, account, states[account], 1) + } + var walk func(*supportDecisionLegacyTrie) error walk = func(node *supportDecisionLegacyTrie) error { if err := ctx.Err(); err != nil { return err } - changed := make([]supportDecisionLegacyMappingState, 0, len(node.wildcards)) - for _, event := range node.wildcards { - changed = append(changed, states[event.account]) - states[event.account] = supportDecisionLegacyMappingState{event: event, active: true} + wildcardPrevious := make([]supportDecisionLegacyMappingState, len(node.wildcards)) + for i, event := range node.wildcards { + if err := ctx.Err(); err != nil { + return err + } + wildcardPrevious[i] = states[event.account] + aggregate.adjust(oracle, event.account, wildcardPrevious[i], -1) + states[event.account] = applySupportDecisionLegacyMappingEvent(wildcardPrevious[i], event) + aggregate.adjust(oracle, event.account, states[event.account], 1) + } + node.wildcard = aggregate.profile() + + exactPrevious := make([]supportDecisionLegacyMappingState, len(node.exacts)) + for i, event := range node.exacts { + if err := ctx.Err(); err != nil { + return err + } + exactPrevious[i] = states[event.account] + aggregate.adjust(oracle, event.account, exactPrevious[i], -1) + states[event.account] = applySupportDecisionLegacyMappingEvent(exactPrevious[i], event) + aggregate.adjust(oracle, event.account, states[event.account], 1) } - node.wildcard = oracle.compileOpenAIStates(states, nil) if len(node.exacts) > 0 { node.exact = new(supportDecisionLegacyCompiledProfile) - *node.exact = oracle.compileOpenAIStates(states, node.exacts) + *node.exact = aggregate.profile() + } + for i := len(node.exacts) - 1; i >= 0; i-- { + event := node.exacts[i] + aggregate.adjust(oracle, event.account, states[event.account], -1) + states[event.account] = exactPrevious[i] + aggregate.adjust(oracle, event.account, states[event.account], 1) } for _, child := range node.children { if err := walk(child); err != nil { @@ -363,74 +510,31 @@ func (n *supportDecisionLegacyTrie) compile(ctx context.Context, oracle *support } } for i := len(node.wildcards) - 1; i >= 0; i-- { - states[node.wildcards[i].account] = changed[i] + event := node.wildcards[i] + aggregate.adjust(oracle, event.account, states[event.account], -1) + states[event.account] = wildcardPrevious[i] + aggregate.adjust(oracle, event.account, states[event.account], 1) } return nil } return walk(n) } -func (o *supportDecisionLegacyScopeOracle) compileOpenAIStates(states []supportDecisionLegacyMappingState, exact []supportDecisionLegacyMappingEvent) supportDecisionLegacyCompiledProfile { - byteCount := (supportDecisionOpenAICoordinateCount + 7) / 8 - profile := supportDecisionLegacyCompiledProfile{eligibleFixed: make([]byte, byteCount), eligibleRequested: make([]byte, byteCount)} - for i := range states { - if states[i].active { - o.applyOpenAIEvent(&profile, states[i].event) - } - } - for _, event := range exact { - o.applyOpenAIEvent(&profile, event) - } - return profile -} - -func (o *supportDecisionLegacyScopeOracle) applyOpenAIEvent(profile *supportDecisionLegacyCompiledProfile, event supportDecisionLegacyMappingEvent) { - fact := &o.accounts[event.account] - if event.compact { - return - } - if fact.account.IsOpenAIOAuth() { - if _, known := normalizeKnownCodexModel(strings.TrimSpace(event.target)); !known { - return - } - } - profile.supported = true - if o.channel == nil || o.channel.Status != StatusActive || !o.channel.RestrictModels || o.channel.BillingModelSource != BillingModelSourceUpstream { - return - } - if supportDecisionChannelAllowsModel(o.channel, o.key.Platform, event.target) { - supportDecisionLegacyOrBits(profile.eligibleFixed, fact.eligible) - return - } - // Compact routing can turn the ordinary target into a channel-allowed model. - // It depends only on the ordinary target, so precompute the finite coordinate mask. - compact := event.target - if mapped, matched := supportDecisionLegacyResolve(fact.compactExact, fact.compactWildcards, compact); matched { - compact = mapped - } - if compact != "" && supportDecisionChannelAllowsModel(o.channel, o.key.Platform, compact) { - for coordinate := 0; coordinate < supportDecisionOpenAICoordinateCount; coordinate++ { - if decodeOpenAICoordinate(coordinate).RequireCompact && fact.eligible[coordinate>>3]&(1< 0 { + profile = node.wildcard + } if i == len(model)-1 && node.exact != nil { profile = *node.exact } @@ -440,6 +544,11 @@ func (o *supportDecisionLegacyScopeOracle) openAIProfile(model string) supportDe profile.supported = true } } + if !profile.supported && o.openAIChannelRestricted && supportDecisionChannelAllowsModel(o.channel, o.key.Platform, model) { + profile.eligibleFixed = cloneSupportDecisionBits(profile.eligibleFixed) + supportDecisionLegacyOrBits(profile.eligibleFixed, profile.eligibleRequested) + supportDecisionLegacyOrBits(profile.eligibleFixed, profile.eligibleCompactRequested) + } return profile } @@ -452,6 +561,12 @@ func (o *supportDecisionLegacyScopeOracle) profile(ctx context.Context, model st if err := ctx.Err(); err != nil { return supportDecisionProfile{}, err } + if o.openAISupportAll { + for coordinate := 0; coordinate < coordinateCount; coordinate++ { + setBit(profile.SupportBits, coordinate) + } + return profile, nil + } compiled := o.openAIProfile(model) if compiled.supported { for coordinate := 0; coordinate < coordinateCount; coordinate++ { @@ -460,6 +575,17 @@ func (o *supportDecisionLegacyScopeOracle) profile(ctx context.Context, model st return profile, nil } copy(profile.EligibleBits, compiled.eligibleFixed) + if o.openAIChannelRestricted && supportDecisionChannelAllowsModel(o.channel, o.key.Platform, model) { + for coordinate := 0; coordinate < coordinateCount; coordinate++ { + requested := compiled.eligibleRequested + if decodeOpenAICoordinate(coordinate).RequireCompact { + requested = compiled.eligibleCompactRequested + } + if bitSet(requested, coordinate) { + setBit(profile.EligibleBits, coordinate) + } + } + } return profile, nil } for i := range o.accounts { @@ -665,6 +791,8 @@ func legacyPureOpenAIModelSupportMissContext(ctx context.Context, input legacyOp continue } // Model support deliberately precedes all later eligibility predicates. + fact := supportDecisionLegacyAccountFact{account: *account, modelMapping: account.GetModelMapping()} + fact.modelExact, fact.modelWildcards = supportDecisionLegacyMappingIndex(fact.modelMapping) if account.IsModelSupported(input.RequestedModel) { return false, nil } diff --git a/backend/internal/service/support_decision_review_test.go b/backend/internal/service/support_decision_review_test.go index 6dae1052bc0c..7c94a5173ef3 100644 --- a/backend/internal/service/support_decision_review_test.go +++ b/backend/internal/service/support_decision_review_test.go @@ -33,6 +33,420 @@ func TestSupportDecisionShadowExercisesReachableOverlappingWildcardParent(t *tes require.ErrorIs(t, err, ErrSupportDecisionShadowMismatch) } +func TestSupportDecisionBuilderWildcardProbeDoesNotReuseExactBoundaryProfile(t *testing.T) { + prefix := strings.Repeat("p", SupportDecisionMaxModelBytes-1) + snapshot := supportDecisionTestSnapshot([]Account{{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "model_mapping": map[string]any{ + prefix: "gpt-5.4", + prefix + "*": "private-upstream-model", + }, + }, + }}, PlatformOpenAI, nil) + options := SupportDecisionBuildOptions{Generation: 27} + table := buildSupportDecisionTestTable(t, snapshot, options) + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: prefix + "\x00", + } + require.Equal(t, SupportDecisionPureMiss, table.Lookup(query)) + _, err := VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionBuilderKeepsCompactOnlyMappingsOutOfOrdinarySupport(t *testing.T) { + account := Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "compact_model_mapping": map[string]any{ + "unknown-model": "gpt-5.4", + }, + }, + } + snapshot := supportDecisionTestSnapshot([]Account{account}, PlatformOpenAI, nil) + options := SupportDecisionBuildOptions{Generation: 28} + table := buildSupportDecisionTestTable(t, snapshot, options) + oracle := supportDecisionScopeOracleForReview(t, snapshot, options) + for _, requireCompact := range []bool{false, true} { + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: "unknown-model", + RequireCompact: requireCompact, + } + direct, err := oracle.lookup(context.Background(), query) + require.NoError(t, err) + compiled, err := oracle.profile(context.Background(), query.RequestedModel, supportDecisionOpenAICoordinateCount) + require.NoError(t, err) + coordinate := 0 + if requireCompact { + coordinate = 4 + } + require.Equal(t, SupportDecisionPureMiss, direct) + require.Equal(t, direct, table.Lookup(query)) + require.Equal(t, direct, profileResult(compiled, coordinate)) + } + _, err := VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionShadowAcceptsUnsupportedOpenAIModelsAlongMappingPath(t *testing.T) { + const mappingModel = "gpt-5.4" + for _, requestedModel := range []string{"gpt-5", "gpt-5.4-preview"} { + t.Run(requestedModel, func(t *testing.T) { + snapshot := supportDecisionTestSnapshot([]Account{{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{mappingModel: mappingModel}, + }, + }}, PlatformOpenAI, []string{requestedModel}) + options := SupportDecisionBuildOptions{Generation: 28} + table := buildSupportDecisionTestTable(t, snapshot, options) + + require.Equal(t, SupportDecisionPureMiss, table.Lookup(SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: requestedModel, + })) + _, err := VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) + }) + } +} + +func TestSupportDecisionShadowAcceptsUnsupportedOpenAIModelWithOverlappingWildcards(t *testing.T) { + const requestedModel = "gpt-5.4" + snapshot := supportDecisionTestSnapshot([]Account{{ + ID: 1, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"gpt-*": "upstream"}, + }, + }, { + ID: 2, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "model_mapping": map[string]any{"gpt-5*": "private-upstream-model"}, + }, + }}, PlatformOpenAI, []string{requestedModel}) + options := SupportDecisionBuildOptions{Generation: 29} + table := buildSupportDecisionTestTable(t, snapshot, options) + + require.Equal(t, SupportDecisionNotPureMiss, table.Lookup(SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: requestedModel, + })) + _, err := VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionShadowAcceptsUnsupportedOpenAIModelsWithChannelPolicy(t *testing.T) { + const requestedModel = "gpt-5" + snapshot := supportDecisionTestSnapshot([]Account{{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"gpt-5.4": "upstream-5.4"}, + }, + }}, PlatformOpenAI, []string{requestedModel}) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{requestedModel}, + }}, + }} + options := SupportDecisionBuildOptions{Generation: 30} + table := buildSupportDecisionTestTable(t, snapshot, options) + scopes, err := collectSupportDecisionScopesContext(context.Background(), snapshot, options.HotModels) + require.NoError(t, err) + var scope *supportDecisionBuildScope + for i := range scopes { + if scopes[i].key == (supportDecisionScopeKey{Platform: PlatformOpenAI, GroupID: 42}) { + scope = &scopes[i] + break + } + } + require.NotNil(t, scope) + oracle, err := newSupportDecisionLegacyScopeOracle(context.Background(), scope, options.OpenAIWS) + require.NoError(t, err) + + for _, model := range []string{requestedModel, "\x00"} { + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: model, + } + compiled, profileErr := oracle.profile(context.Background(), model, supportDecisionOpenAICoordinateCount) + require.NoError(t, profileErr) + direct, lookupErr := oracle.lookup(context.Background(), query) + require.NoError(t, lookupErr) + require.Equal(t, table.Lookup(query), direct, "direct oracle model %q", model) + require.Equal(t, direct, profileResult(compiled, 0), "compiled oracle model %q", model) + } + + _, err = VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionShadowRejectsUnsupportedOpenAIModelDeniedByChannel(t *testing.T) { + const requestedModel = "missing" + account := Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"other": "ordinary-target"}, + }, + } + snapshot := supportDecisionTestSnapshot([]Account{account}, PlatformOpenAI, []string{requestedModel}) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{"allowed-only"}, + }}, + }} + options := SupportDecisionBuildOptions{Generation: 31} + table := buildSupportDecisionTestTable(t, snapshot, options) + oracle := supportDecisionScopeOracleForReview(t, snapshot, options) + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: requestedModel, + } + compiled, err := oracle.profile(context.Background(), requestedModel, supportDecisionOpenAICoordinateCount) + require.NoError(t, err) + direct, err := oracle.lookup(context.Background(), query) + require.NoError(t, err) + require.Equal(t, SupportDecisionNotPureMiss, table.Lookup(query)) + require.Equal(t, table.Lookup(query), direct) + require.Equal(t, direct, profileResult(compiled, 0)) + + _, err = VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionShadowAcceptsUnsupportedOpenAICompactChannelMapping(t *testing.T) { + const requestedModel = "missing" + account := Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"other": "ordinary-target"}, + "compact_model_mapping": map[string]any{"*": "compact-target"}, + }, + Extra: map[string]any{"openai_compact_mode": OpenAICompactModeForceOn}, + } + snapshot := supportDecisionTestSnapshot([]Account{account}, PlatformOpenAI, []string{requestedModel}) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{"compact-target"}, + }}, + }} + options := SupportDecisionBuildOptions{Generation: 32} + table := buildSupportDecisionTestTable(t, snapshot, options) + scope := supportDecisionScopeOracleForReview(t, snapshot, options) + + for _, compact := range []bool{false, true} { + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: requestedModel, + RequireCompact: compact, + } + compiled, err := scope.profile(context.Background(), requestedModel, supportDecisionOpenAICoordinateCount) + require.NoError(t, err) + direct, err := scope.lookup(context.Background(), query) + require.NoError(t, err) + coordinate := 0 + if compact { + coordinate = 4 + } + require.Equal(t, table.Lookup(query), direct) + require.Equal(t, direct, profileResult(compiled, coordinate), "compact=%v", compact) + } + + _, err := VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionShadowRejectsUnsupportedOpenAICompactTargetDeniedByChannel(t *testing.T) { + const requestedModel = "missing" + account := Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"other": "ordinary-target"}, + "compact_model_mapping": map[string]any{"*": "denied-compact-target"}, + }, + Extra: map[string]any{"openai_compact_mode": OpenAICompactModeForceOn}, + } + snapshot := supportDecisionTestSnapshot([]Account{account}, PlatformOpenAI, []string{requestedModel}) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{requestedModel}, + }}, + }} + options := SupportDecisionBuildOptions{Generation: 34} + table := buildSupportDecisionTestTable(t, snapshot, options) + oracle := supportDecisionScopeOracleForReview(t, snapshot, options) + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: requestedModel, + RequireCompact: true, + } + compiled, err := oracle.profile(context.Background(), requestedModel, supportDecisionOpenAICoordinateCount) + require.NoError(t, err) + direct, err := oracle.lookup(context.Background(), query) + require.NoError(t, err) + require.Equal(t, SupportDecisionNotPureMiss, table.Lookup(query)) + require.Equal(t, table.Lookup(query), direct) + require.Equal(t, direct, profileResult(compiled, 4)) + + _, err = VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionBuilderPreservesRequestedChannelEligibilityUnderWildcard(t *testing.T) { + const requestedModel = "gpt-5" + snapshot := supportDecisionTestSnapshot([]Account{{ + ID: 1, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "model_mapping": map[string]any{ + "gpt-*": "gpt-5.4", + "gpt-5*": "compact-target", + }, + }, + }, { + ID: 2, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"foo-*": "allowed"}, + }, + }}, PlatformOpenAI, nil) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{requestedModel}, + }}, + }} + options := SupportDecisionBuildOptions{Generation: 36} + table := buildSupportDecisionTestTable(t, snapshot, options) + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: requestedModel, + } + require.Equal(t, SupportDecisionPureMiss, table.Lookup(query)) + _, err := VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionBuilderChannelProfilePreservesLaterSupportingAccount(t *testing.T) { + snapshot := supportDecisionTestSnapshot([]Account{{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"foo-*": "compact-target"}, + }, + }, { + Platform: PlatformOpenAI, + Type: AccountTypeSetupToken, + Credentials: map[string]any{ + "compact_model_mapping": map[string]any{"known": "gpt-5.2-codex"}, + }, + }}, PlatformOpenAI, nil) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{"*"}, + }}, + }} + options := SupportDecisionBuildOptions{Generation: 37} + table := buildSupportDecisionTestTable(t, snapshot, options) + query := SupportDecisionQuery{ + Scope: SupportDecisionScope{Platform: PlatformOpenAI, GroupID: 42}, + RequestedModel: "missing", + } + require.Equal(t, SupportDecisionNotPureMiss, table.Lookup(query)) + _, err := VerifySupportDecisionShadow(context.Background(), snapshot, options, table) + require.NoError(t, err) +} + +func TestSupportDecisionLegacyOracleProfilesRemainImmutableAcrossLookups(t *testing.T) { + const requestedModel = "allowed" + snapshot := supportDecisionTestSnapshot([]Account{{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"other": "ordinary-target"}, + }, + }}, PlatformOpenAI, []string{requestedModel}) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{requestedModel}, + }}, + }} + oracle := supportDecisionScopeOracleForReview(t, snapshot, SupportDecisionBuildOptions{Generation: 35}) + + first, err := oracle.profile(context.Background(), requestedModel, supportDecisionOpenAICoordinateCount) + require.NoError(t, err) + require.Equal(t, SupportDecisionPureMiss, profileResult(first, 0)) + second, err := oracle.profile(context.Background(), "\x00", supportDecisionOpenAICoordinateCount) + require.NoError(t, err) + require.Equal(t, SupportDecisionNotPureMiss, profileResult(second, 0)) + third, err := oracle.profile(context.Background(), requestedModel, supportDecisionOpenAICoordinateCount) + require.NoError(t, err) + require.Equal(t, SupportDecisionPureMiss, profileResult(third, 0)) +} + +func supportDecisionScopeOracleForReview(t *testing.T, snapshot *SupportDecisionConstructionSnapshot, options SupportDecisionBuildOptions) *supportDecisionLegacyScopeOracle { + t.Helper() + scopes, err := collectSupportDecisionScopesContext(context.Background(), snapshot, options.HotModels) + require.NoError(t, err) + for i := range scopes { + if scopes[i].key == (supportDecisionScopeKey{Platform: PlatformOpenAI, GroupID: 42}) { + oracle, err := newSupportDecisionLegacyScopeOracle(context.Background(), &scopes[i], options.OpenAIWS) + require.NoError(t, err) + return oracle + } + } + require.FailNow(t, "OpenAI group scope not found") + return nil +} + func TestSupportDecisionShadowDetectsPublishedBranchCorruption(t *testing.T) { channel := SupportDecisionChannel{Status: StatusActive, RestrictModels: true, BillingModelSource: BillingModelSourceUpstream, GroupIDs: []int64{42}, PricingModels: []SupportDecisionPricingModels{{Platform: PlatformAnthropic, Models: []string{"DIRECT", "claude-sonnet-4.5*"}}}} snapshot := supportDecisionTestSnapshot([]Account{{Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"direct": "direct", "claude-sonnet-4-5-20250929": "claude-sonnet-4-5-20250929", "wild-*": "wild-target", "*": "catch-target"}}}}, PlatformAnthropic, nil) @@ -237,34 +651,43 @@ func TestSupportDecisionShadowLegacyOracleWorkIsAggregated(t *testing.T) { require.LessOrEqual(t, operations, maximum, "oracle work must not multiply accounts by model witnesses") } -func TestSupportDecisionLegacyOracleRejectsUnknownOAuthMappingTargets(t *testing.T) { - snapshot := supportDecisionTestSnapshot([]Account{{ - Platform: PlatformOpenAI, - Type: AccountTypeOAuth, - Credentials: map[string]any{"model_mapping": map[string]any{ - "known": "gpt-5.2-codex", - "unknown": "private-upstream-model", - }}, - }}, PlatformOpenAI, nil) - scopes, err := collectSupportDecisionScopesContext(context.Background(), snapshot, config.SupportDecisionHotModelsConfig{}) - require.NoError(t, err) - var scope *supportDecisionBuildScope - for i := range scopes { - if scopes[i].key == (supportDecisionScopeKey{Platform: PlatformOpenAI, GroupID: 42}) { - scope = &scopes[i] - break +func TestSupportDecisionShadowLegacyOracleCompactChannelWorkIsAggregated(t *testing.T) { + mapping := make(map[string]any, 16) + for i := 0; i < 16; i++ { + mapping[fmt.Sprintf("model-%03d", i)] = "gpt-5.2-codex" + } + accounts := make([]Account, 8) + for i := range accounts { + accounts[i] = Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "model_mapping": mapping, + "compact_model_mapping": map[string]any{"*": "compact-target"}, + }, + Extra: map[string]any{"openai_compact_mode": OpenAICompactModeForceOn}, } } - require.NotNil(t, scope) - oracle, err := newSupportDecisionLegacyScopeOracle(context.Background(), scope, config.GatewayOpenAIWSConfig{}) - require.NoError(t, err) - - known, err := oracle.profile(context.Background(), "known", supportDecisionOpenAICoordinateCount) - require.NoError(t, err) - unknown, err := oracle.profile(context.Background(), "unknown", supportDecisionOpenAICoordinateCount) + snapshot := supportDecisionTestSnapshot(accounts, PlatformOpenAI, nil) + snapshot.Channels = []SupportDecisionChannel{{ + Status: StatusActive, + GroupIDs: []int64{42}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + PricingModels: []SupportDecisionPricingModels{{ + Platform: PlatformOpenAI, + Models: []string{"compact-target"}, + }}, + }} + options := SupportDecisionBuildOptions{Generation: 33} + table := buildSupportDecisionTestTable(t, snapshot, options) + var operations uint64 + ctx := context.WithValue(context.Background(), supportDecisionShadowOperationCounterKey{}, &operations) + checks, err := VerifySupportDecisionShadow(ctx, snapshot, options, table) require.NoError(t, err) - require.Equal(t, SupportDecisionNotPureMiss, profileResult(known, 0)) - require.Equal(t, SupportDecisionNotPureMiss, profileResult(unknown, 0)) + require.Positive(t, checks) + maximum := uint64(len(accounts)*(supportDecisionOpenAICoordinateCount+2) + 4096) + require.LessOrEqual(t, operations, maximum, "compact channel work must not multiply accounts by model witnesses") } func TestSupportDecisionLegacyUpstreamRestrictionChainsCompactMapping(t *testing.T) {