mochengqian commented on code in PR #953: URL: https://github.com/apache/dubbo-go-pixiu/pull/953#discussion_r3487249217
########## pkg/filter/mcp/mcpserver/router/composite.go: ########## @@ -0,0 +1,597 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package router + +import ( + "context" + "encoding/json" + "fmt" + "hash/fnv" + "io" + "sort" + "strconv" + "time" +) + +import ( + "github.com/apache/dubbo-go-pixiu/pkg/model" +) + +// Fallback strategies. +const ( + DefaultFallback = FallbackFailClosed + FallbackBundleDefault = "bundle_default" + FallbackFailClosed = "fail_closed" +) + +// CompositeSelector runs the deterministic selection pipeline: +// +// policy -> workflow -> progressive +// +// Each stage is optional; a nil stage is skipped. Results are cached per session +// in the SessionPlanStore and reused while the metadata/config version is stable. +type CompositeSelector struct { + policy *PolicyFilter + workflow *WorkflowSelector + progressive *ProgressiveGate + bundles *WorkflowSelector + + store *SessionPlanStore + log *DecisionLogger + + routerID string + fallback string + defaultBundle string + configHash string + progressiveHash string +} + +// CompositeOptions configures a CompositeSelector. The builder populates it. +type CompositeOptions struct { + Policy *PolicyFilter + Workflow *WorkflowSelector + Progressive *ProgressiveGate + Bundles *WorkflowSelector + Store *SessionPlanStore + Log *DecisionLogger + Fallback string + DefaultBundle string + ConfigHash string + RouterID string +} + +// NewCompositeSelector assembles the pipeline from validated options. +func NewCompositeSelector(opts CompositeOptions) (*CompositeSelector, error) { + if opts.Store == nil { + return nil, fmt.Errorf("router session plan store is nil") + } + fallback := opts.Fallback + if fallback == "" { + fallback = DefaultFallback + } + if err := validateFallback(fallback); err != nil { + return nil, err + } + log := opts.Log + if log == nil { + log = NewDecisionLogger(0, false) + } + return &CompositeSelector{ + policy: opts.Policy, + workflow: opts.Workflow, + progressive: opts.Progressive, + bundles: opts.Bundles, + store: opts.Store, + log: log, + routerID: opts.RouterID, + fallback: fallback, + defaultBundle: opts.DefaultBundle, + configHash: opts.ConfigHash, + progressiveHash: progressiveConfigHash(opts.Progressive), + }, nil +} + +type selectionPipeline struct { + tools []model.ToolConfig + policyAllowed []model.ToolConfig + traces []DecisionTrace + stageCounts map[string]StageCount + outcome string + expanded bool +} + +func newSelectionPipeline(candidates []model.ToolConfig) *selectionPipeline { + return &selectionPipeline{ + tools: candidates, + policyAllowed: candidates, + stageCounts: make(map[string]StageCount), + outcome: SelectionOutcomeSelected, + } +} + +// Select runs the pipeline, reusing a cached plan when the version is unchanged. +func (c *CompositeSelector) Select(_ context.Context, sc SelectionContext, candidates []model.ToolConfig) (*SelectionPlan, error) { + start := time.Now() + identityHash, err := identityFingerprint(sc) + if err != nil { + return nil, err + } + version := c.version(candidates, identityHash, sc.SessionID, sc.CatalogVersion) + key := c.planKey(sc.SessionID) + + if cached, ok := c.cachedSelectionPlan(key, version, candidates, start); ok { + return cached, nil + } + + plan := c.computeSelectionPlan(key, identityHash, sc, candidates, version) + plan, err = c.storeSelectionPlan(key, plan, sc) + if err != nil { + recordFallback("plan_persistence_failed") + return nil, err + } + + result := "ok" + if outcomeAllowsFallback(plan.Outcome) { + result = "fallback" + recordFallback(plan.Outcome) + } + + c.recordSelectionResult(result, plan, candidates, start) + c.log.Log(sc, plan, len(candidates)) + + return plan, nil +} + +func (c *CompositeSelector) cachedSelectionPlan(key PlanKey, version string, candidates []model.ToolConfig, start time.Time) (*SelectionPlan, bool) { + cached, ok := c.store.Get(key) + if !ok || cached.Version != version { + return nil, false + } + elapsedMS := float64(time.Since(start).Microseconds()) / 1000.0 + recordSelection("cached", cached.Mode, len(candidates), len(cached.ToolNames), elapsedMS) + return cached, true +} + +func (c *CompositeSelector) computeSelectionPlan(key PlanKey, identityHash string, sc SelectionContext, candidates []model.ToolConfig, version string) *SelectionPlan { + pipeline := c.runSelectionPipeline(key, identityHash, sc, candidates) + if outcomeAllowsFallback(pipeline.outcome) { + return c.applyFallback(sc, pipeline.policyAllowed, version, pipeline.traces, pipeline.stageCounts, pipeline.outcome) + } + return c.newSelectionPlan(sc, candidates, version, identityHash, pipeline) +} + +func (c *CompositeSelector) runSelectionPipeline(key PlanKey, identityHash string, sc SelectionContext, candidates []model.ToolConfig) *selectionPipeline { + pipeline := newSelectionPipeline(candidates) + pipeline.applyPolicy(c.policy, sc) + pipeline.applyWorkflow(c.workflow, sc) + pipeline.applyProgressive(c.progressive, c.store, key, identityHash, c.progressiveHash) + pipeline.finalizeOutcome() + return pipeline +} + +func (p *selectionPipeline) applyPolicy(policy *PolicyFilter, sc SelectionContext) { + if policy == nil { + return + } + input := len(p.tools) + var traces []DecisionTrace + p.tools, traces = policy.Filter(p.tools, sc) + recordStageCount(p.stageCounts, StagePolicy, input, len(p.tools)) + p.policyAllowed = p.tools + p.traces = append(p.traces, traces...) + if input > 0 && len(p.tools) == 0 { + p.outcome = SelectionOutcomeExplicitDeny + } +} + +func (p *selectionPipeline) applyWorkflow(workflow *WorkflowSelector, sc SelectionContext) { + if !p.selected() || workflow == nil { + return + } + input := len(p.tools) + result := workflow.filter(p.tools, sc) + p.tools = result.tools + recordStageCount(p.stageCounts, StageWorkflow, input, len(p.tools)) + p.traces = append(p.traces, result.traces...) + if !result.matched && workflow.hasMatchableWorkflows() { + p.outcome = SelectionOutcomeNoMatch + return + } + if input > 0 && len(p.tools) == 0 { + p.outcome = SelectionOutcomeEmptyByConfiguration + } +} + +func (p *selectionPipeline) applyProgressive(progressive *ProgressiveGate, store *SessionPlanStore, key PlanKey, identityHash, progressiveHash string) { + if !p.selected() || progressive == nil { + return + } + input := len(p.tools) + var traces []DecisionTrace + _, p.expanded = store.CallState(key, identityHash, progressiveHash) + p.tools, traces = progressive.Apply(p.tools, p.expanded) + recordStageCount(p.stageCounts, StageProgressive, input, len(p.tools)) + p.traces = append(p.traces, traces...) + if input > 0 && len(p.tools) == 0 { + p.outcome = SelectionOutcomeEmptyByConfiguration + } +} + +func (p *selectionPipeline) finalizeOutcome() { + if p.selected() && len(p.tools) == 0 { + p.outcome = SelectionOutcomeNoMatch + } +} + +func (p *selectionPipeline) selected() bool { + return p.outcome == SelectionOutcomeSelected +} + +func (c *CompositeSelector) newSelectionPlan(sc SelectionContext, candidates []model.ToolConfig, version, identityHash string, pipeline *selectionPipeline) *SelectionPlan { + plan := &SelectionPlan{ + SessionID: sc.SessionID, + ToolNames: toolNames(pipeline.tools), + VisibleToolNames: visibleToolNames(pipeline.tools), + Mode: ModeSelected, + Outcome: pipeline.outcome, + StageCounts: pipeline.stageCounts, + Reasons: pipeline.traces, + Version: version, + CreatedAt: time.Now().UnixNano(), + IdentityHash: identityHash, + ProgressiveHash: c.progressiveHash, + ConfigHash: c.configHash, + CatalogVersion: c.catalogVersion(candidates, sc.CatalogVersion), + Expanded: pipeline.expanded, + } + plan.toolSet = toolNameSet(plan.ToolNames) + return plan +} + +func (c *CompositeSelector) storeSelectionPlan(key PlanKey, plan *SelectionPlan, sc SelectionContext) (*SelectionPlan, error) { + if err := c.store.Set(key, plan, sc); err != nil { + return nil, err + } + if stored, ok := c.store.Get(key); ok { Review Comment: fixed -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
