mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
fix: harden grouped routing queries and selection safety
This commit is contained in:
1 parent
a05e06a20c
commit
cd7d3cd3af
7 files changed
+159
-53
No files matched your search
@@ -20,8 +20,8 @@ import (
|
||||
|
||||
const defaultModelSyncWorkers = 25
|
||||
const syncFailurePersistTimeout = 5 * time.Second
|
||||
const maxModelCapabilitiesPerGroup = 5
|
||||
const maxModelBatchSize = repository.MaxPageSize * maxModelCapabilitiesPerGroup
|
||||
|
||||
var maxModelBatchSize = repository.MaxPageSize * len(modeldomain.Capabilities())
|
||||
|
||||
var (
|
||||
ErrInvalidFilter = errors.New("模型筛选条件无效")
|
||||
|
||||
@@ -24,6 +24,18 @@ const (
|
||||
CapabilityVideo Capability = "video"
|
||||
)
|
||||
|
||||
// Capabilities returns every persisted route capability. Callers use this as
|
||||
// the single source of truth for bounds that depend on the maximum group size.
|
||||
func Capabilities() []Capability {
|
||||
return []Capability{
|
||||
CapabilityResponses,
|
||||
CapabilityChat,
|
||||
CapabilityImage,
|
||||
CapabilityImageEdit,
|
||||
CapabilityVideo,
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
OriginCatalog Origin = "catalog"
|
||||
OriginDiscovered Origin = "discovered"
|
||||
@@ -49,8 +61,9 @@ type Route struct {
|
||||
}
|
||||
|
||||
// RouteGroup is the admin-facing projection of one logical model target.
|
||||
// Catalog capabilities share a group while manual routes remain independent
|
||||
// scheduling targets even when their visible names happen to match.
|
||||
// Managed catalog capabilities share a group. Manual routes remain independent
|
||||
// scheduling targets even when their visible names happen to match: neither a
|
||||
// display name nor an upstream model is a stable identity for account bindings.
|
||||
type RouteGroup struct {
|
||||
Routes []Route
|
||||
}
|
||||
|
||||
@@ -283,45 +283,26 @@ type modelRouteGroupRow struct {
|
||||
// routes. This keeps capability groups complete under filters and avoids the
|
||||
// admin UI fetching and annotating the entire route table.
|
||||
func (r *ModelRepository) ListGroups(ctx context.Context, input repository.ModelListQuery) ([]model.RouteGroup, int64, error) {
|
||||
manualRouteIDExpression := "CASE WHEN model_routes.origin = 'manual' THEN model_routes.id ELSE 0 END"
|
||||
routeIDsExpression := "GROUP_CONCAT(CAST(model_routes.id AS TEXT), ',')"
|
||||
if r.db.dialect == "postgres" {
|
||||
routeIDsExpression = "STRING_AGG(CAST(model_routes.id AS TEXT), ',' ORDER BY model_routes.id)"
|
||||
}
|
||||
enabledCountExpression := "SUM(CASE WHEN model_routes.enabled = TRUE THEN 1 ELSE 0 END)"
|
||||
groupColumns := "model_routes.provider, model_routes.public_id, model_routes.upstream_model, model_routes.origin, " + manualRouteIDExpression
|
||||
supportSortExpression := "0"
|
||||
if input.Page.Sort.Field == "accountSupport" {
|
||||
supportSortExpression = "MAX(" + modelSupportSortExpression + ")"
|
||||
}
|
||||
lastSyncedSortExpression := "NULL"
|
||||
if input.Page.Sort.Field == "lastSyncedAt" {
|
||||
lastSyncedSortExpression = "MAX(" + modelSyncedSortExpression + ")"
|
||||
}
|
||||
|
||||
buildQuery := func(includeMetrics bool) *gorm.DB {
|
||||
query := r.db.db.WithContext(ctx).Model(&modelRouteModel{})
|
||||
if includeMetrics {
|
||||
query = query.Select(fmt.Sprintf(`
|
||||
model_routes.provider,
|
||||
model_routes.public_id,
|
||||
model_routes.upstream_model,
|
||||
model_routes.origin,
|
||||
%s AS manual_route_id,
|
||||
%s AS route_ids,
|
||||
CASE
|
||||
WHEN %s = COUNT(*) THEN 0
|
||||
WHEN %s > 0 THEN 1
|
||||
ELSE 2
|
||||
END AS status_sort,
|
||||
%s AS support_sort,
|
||||
%s AS last_synced_sort,
|
||||
MAX(model_routes.created_at) AS created_sort
|
||||
`, manualRouteIDExpression, routeIDsExpression, enabledCountExpression, enabledCountExpression, supportSortExpression, lastSyncedSortExpression))
|
||||
} else {
|
||||
query = query.Select("model_routes.provider, model_routes.public_id, model_routes.upstream_model, model_routes.origin, " + manualRouteIDExpression + " AS manual_route_id")
|
||||
// Route-level metrics must be calculated before grouping. In particular,
|
||||
// PostgreSQL does not allow a correlated metric to reference model_routes.id
|
||||
// from inside a grouped SELECT when id is not itself a grouping key.
|
||||
buildRouteMetricsQuery := func(includeMetrics bool) *gorm.DB {
|
||||
columns := []string{
|
||||
"model_routes.id",
|
||||
"model_routes.provider",
|
||||
"model_routes.public_id",
|
||||
"model_routes.upstream_model",
|
||||
"model_routes.origin",
|
||||
"model_routes.enabled",
|
||||
"model_routes.created_at",
|
||||
}
|
||||
query = query.Group(groupColumns)
|
||||
if includeMetrics && input.Page.Sort.Field == "accountSupport" {
|
||||
columns = append(columns, modelSupportSortExpression+" AS support_sort")
|
||||
}
|
||||
if includeMetrics && input.Page.Sort.Field == "lastSyncedAt" {
|
||||
columns = append(columns, modelSyncedSortExpression+" AS last_synced_sort")
|
||||
}
|
||||
query := r.db.db.WithContext(ctx).Model(&modelRouteModel{}).Select(strings.Join(columns, ", "))
|
||||
if search := strings.TrimSpace(input.Page.Search); search != "" {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(model_routes.public_id) LIKE ? OR LOWER(model_routes.upstream_model) LIKE ?", pattern, pattern)
|
||||
@@ -329,6 +310,48 @@ func (r *ModelRepository) ListGroups(ctx context.Context, input repository.Model
|
||||
if input.Filter.Provider != "" {
|
||||
query = query.Where("model_routes.provider = ?", input.Filter.Provider)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
manualRouteIDExpression := "CASE WHEN route_metrics.origin = 'manual' THEN route_metrics.id ELSE 0 END"
|
||||
routeIDsExpression := "GROUP_CONCAT(CAST(route_metrics.id AS TEXT), ',')"
|
||||
if r.db.dialect == "postgres" {
|
||||
routeIDsExpression = "STRING_AGG(CAST(route_metrics.id AS TEXT), ',' ORDER BY route_metrics.id)"
|
||||
}
|
||||
enabledCountExpression := "SUM(CASE WHEN route_metrics.enabled = TRUE THEN 1 ELSE 0 END)"
|
||||
groupColumns := "route_metrics.provider, route_metrics.public_id, route_metrics.upstream_model, route_metrics.origin, " + manualRouteIDExpression
|
||||
supportSortExpression := "0"
|
||||
if input.Page.Sort.Field == "accountSupport" {
|
||||
supportSortExpression = "MAX(route_metrics.support_sort)"
|
||||
}
|
||||
lastSyncedSortExpression := "NULL"
|
||||
if input.Page.Sort.Field == "lastSyncedAt" {
|
||||
lastSyncedSortExpression = "MAX(route_metrics.last_synced_sort)"
|
||||
}
|
||||
|
||||
buildQuery := func(includeMetrics bool) *gorm.DB {
|
||||
query := r.db.db.WithContext(ctx).Table("(?) AS route_metrics", buildRouteMetricsQuery(includeMetrics))
|
||||
if includeMetrics {
|
||||
query = query.Select(fmt.Sprintf(`
|
||||
route_metrics.provider,
|
||||
route_metrics.public_id,
|
||||
route_metrics.upstream_model,
|
||||
route_metrics.origin,
|
||||
%s AS manual_route_id,
|
||||
%s AS route_ids,
|
||||
CASE
|
||||
WHEN %s = COUNT(*) THEN 0
|
||||
WHEN %s > 0 THEN 1
|
||||
ELSE 2
|
||||
END AS status_sort,
|
||||
%s AS group_support_sort,
|
||||
%s AS group_last_synced_sort,
|
||||
MAX(route_metrics.created_at) AS created_sort
|
||||
`, manualRouteIDExpression, routeIDsExpression, enabledCountExpression, enabledCountExpression, supportSortExpression, lastSyncedSortExpression))
|
||||
} else {
|
||||
query = query.Select("route_metrics.provider, route_metrics.public_id, route_metrics.upstream_model, route_metrics.origin, " + manualRouteIDExpression + " AS manual_route_id")
|
||||
}
|
||||
query = query.Group(groupColumns)
|
||||
if input.Filter.Enabled != nil {
|
||||
if *input.Filter.Enabled {
|
||||
query = query.Having(enabledCountExpression + " > 0")
|
||||
@@ -346,21 +369,28 @@ func (r *ModelRepository) ListGroups(ctx context.Context, input repository.Model
|
||||
|
||||
query := buildQuery(true)
|
||||
spec, direction := stableSortSpec(input.Page.Sort, map[string]sortSpec{
|
||||
"publicId": {expression: "LOWER(model_routes.public_id)"},
|
||||
"upstreamModel": {expression: "LOWER(model_routes.upstream_model)"},
|
||||
"publicId": {expression: "LOWER(route_metrics.public_id)"},
|
||||
"upstreamModel": {expression: "LOWER(route_metrics.upstream_model)"},
|
||||
"status": {expression: "status_sort"},
|
||||
"provider": {expression: "model_routes.provider"},
|
||||
"accountSupport": {expression: "support_sort", defaultDirection: repository.SortDescending},
|
||||
"lastSyncedAt": {expression: "last_synced_sort", nullsLast: true, defaultDirection: repository.SortDescending},
|
||||
"provider": {expression: "route_metrics.provider"},
|
||||
"accountSupport": {expression: "group_support_sort", defaultDirection: repository.SortDescending},
|
||||
"lastSyncedAt": {expression: "group_last_synced_sort", nullsLast: true, defaultDirection: repository.SortDescending},
|
||||
}, sortSpec{expression: "created_sort", defaultDirection: repository.SortDescending})
|
||||
if spec.nullsLast {
|
||||
query = query.Order("CASE WHEN " + spec.expression + " IS NULL THEN 1 ELSE 0 END ASC")
|
||||
// PostgreSQL permits a SELECT alias as a plain ORDER BY item, but not
|
||||
// inside another ORDER BY expression. Repeat the aggregate only for the
|
||||
// NULL discriminator and use the alias for the value ordering below.
|
||||
nullSortExpression := spec.expression
|
||||
if input.Page.Sort.Field == "lastSyncedAt" {
|
||||
nullSortExpression = lastSyncedSortExpression
|
||||
}
|
||||
query = query.Order("CASE WHEN " + nullSortExpression + " IS NULL THEN 1 ELSE 0 END ASC")
|
||||
}
|
||||
query = query.Order(spec.expression + " " + direction).
|
||||
Order("model_routes.provider ASC").
|
||||
Order("LOWER(model_routes.public_id) ASC").
|
||||
Order("LOWER(model_routes.upstream_model) ASC").
|
||||
Order("model_routes.origin ASC").
|
||||
Order("route_metrics.provider ASC").
|
||||
Order("LOWER(route_metrics.public_id) ASC").
|
||||
Order("LOWER(route_metrics.upstream_model) ASC").
|
||||
Order("route_metrics.origin ASC").
|
||||
Order("manual_route_id ASC")
|
||||
var groupRows []modelRouteGroupRow
|
||||
if err := query.Offset(input.Page.Offset).Limit(input.Page.Limit).Scan(&groupRows).Error; err != nil {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
func TestPostgresModelGroupsAggregateRouteMetricsBeforeGrouping(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_POSTGRES_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_POSTGRES_DSN is not configured")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
database, err := OpenPostgres(ctx, dsn, 5, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
accounts := NewAccountRepository(database)
|
||||
if _, _, err := accounts.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderConsole, Name: "model-group-postgres", SourceKey: "model-group-postgres",
|
||||
EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: account.AuthStatusActive,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
models := NewModelRepository(database)
|
||||
const publicID = "postgres-grouped-console-image"
|
||||
if err := models.UpsertRoutes(ctx, []model.Route{
|
||||
{PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Origin: model.OriginCatalog, Enabled: true},
|
||||
{PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Origin: model.OriginCatalog, Enabled: true},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, field := range []string{"accountSupport", "lastSyncedAt"} {
|
||||
values, total, err := models.ListGroups(ctx, repository.ModelListQuery{Page: repository.PageQuery{
|
||||
Limit: 20, Search: publicID, Sort: repository.SortQuery{Field: field, Direction: repository.SortDescending},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("sort PostgreSQL model groups by %s: %v", field, err)
|
||||
}
|
||||
if total != 1 || len(values) != 1 || len(values[0].Routes) != 2 {
|
||||
t.Fatalf("PostgreSQL group sorted by %s = %#v, total=%d", field, values, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ var schemaIndexes = []string{
|
||||
// manual rows may still share a public ID and form a route-target pool.
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS uidx_model_routes_managed_public_capability ON model_routes(public_id, capability) WHERE origin IN ('catalog', 'discovered')",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_routes_provider_upstream ON model_routes(provider, upstream_model)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_routes_grouping ON model_routes(provider, public_id, upstream_model, origin, id)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_routes_created_id ON model_routes(created_at DESC, id DESC)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_routes_enabled ON model_routes(enabled, public_id, id)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_route_aliases_route ON model_route_aliases(model_route_id, alias)",
|
||||
|
||||
@@ -70,7 +70,7 @@ func TestInitializeSchemaUpgradesProviderChecksForConsole(t *testing.T) {
|
||||
}
|
||||
assertSQLiteUniqueIndexes(t, database, "provider_accounts", "idx_provider_accounts_identity_key")
|
||||
assertSQLiteUniqueIndexes(t, database, "model_routes", "uidx_model_routes_managed_public_capability")
|
||||
assertSQLiteIndexes(t, database, "model_routes", "idx_model_routes_public_id_lookup", "idx_model_routes_provider_upstream")
|
||||
assertSQLiteIndexes(t, database, "model_routes", "idx_model_routes_public_id_lookup", "idx_model_routes_provider_upstream", "idx_model_routes_grouping")
|
||||
assertSQLiteMissingIndexes(t, database, "model_routes", "idx_model_routes_public_id")
|
||||
assertSQLiteMissingIndexes(t, database, "model_routes", "uidx_provider_upstream")
|
||||
assertTableColumns(t, database, "request_audits", []string{"first_token_ms"}, nil)
|
||||
|
||||
@@ -88,6 +88,7 @@ export function ModelsPage() {
|
||||
return updateModel(editing.id, { publicId: input.publicId, enabled: input.enabled, accountIds: input.accountIds });
|
||||
},
|
||||
onSuccess: () => {
|
||||
setSelected(new Set());
|
||||
void queryClient.invalidateQueries({ queryKey: ["models"] });
|
||||
setEditing(null);
|
||||
toast.success(t(editing === "new" ? "models.created" : "models.updated"));
|
||||
@@ -101,6 +102,7 @@ export function ModelsPage() {
|
||||
else await deleteModels(routes.map((route) => route.id));
|
||||
},
|
||||
onSuccess: () => {
|
||||
setSelected(new Set());
|
||||
void queryClient.invalidateQueries({ queryKey: ["models"] });
|
||||
setDeleting(null);
|
||||
setPage(1);
|
||||
@@ -135,6 +137,8 @@ export function ModelsPage() {
|
||||
const syncMutation = useMutation({
|
||||
mutationFn: syncModels,
|
||||
onSuccess: (result) => {
|
||||
setSelected(new Set());
|
||||
setPage(1);
|
||||
void queryClient.invalidateQueries({ queryKey: ["models"] });
|
||||
toast.success(t("models.synced", { count: result.synced }));
|
||||
},
|
||||
@@ -207,6 +211,7 @@ export function ModelsPage() {
|
||||
function changeSort(field: string, initialOrder: SortOrder): void {
|
||||
setSort((current) => nextTableSort(current, field, initialOrder));
|
||||
setPage(1);
|
||||
setSelected(new Set());
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
Reference in new issue
Block a user