feat: pass IndexConfig to repositories with scalability options

This commit is contained in:
ochan.kwon
2026-04-16 15:12:42 +09:00
committed by lyingbug
parent 7bd36bf954
commit 927d3debff
14 changed files with 673 additions and 69 deletions
+190 -5
View File
@@ -4,6 +4,8 @@ import (
"database/sql/driver"
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"time"
@@ -201,11 +203,19 @@ func (c ConnectionConfig) MaskSensitiveFields() ConnectionConfig {
// IndexConfig holds optional index/collection configuration for the vector store.
// If empty, engine-specific defaults are used.
type IndexConfig struct {
// --- Existing fields ---
IndexName string `yaml:"index_name" json:"index_name,omitempty"` // ES, OpenSearch
NumberOfShards int `yaml:"number_of_shards" json:"number_of_shards,omitempty"` // ES, OpenSearch
NumberOfReplicas int `yaml:"number_of_replicas" json:"number_of_replicas,omitempty"` // ES, OpenSearch
CollectionPrefix string `yaml:"collection_prefix" json:"collection_prefix,omitempty"` // Qdrant
CollectionPrefix string `yaml:"collection_prefix" json:"collection_prefix,omitempty"` // Qdrant, Weaviate
CollectionName string `yaml:"collection_name" json:"collection_name,omitempty"` // Milvus
// --- Scalability fields ---
ShardNumber int `yaml:"shard_number" json:"shard_number,omitempty"` // Qdrant: number of shards per collection
ReplicationFactor int `yaml:"replication_factor" json:"replication_factor,omitempty"` // Qdrant, Weaviate: number of replicas
ShardsNum int `yaml:"shards_num" json:"shards_num,omitempty"` // Milvus: number of shards per collection (CreateCollection)
ReplicaNumber int `yaml:"replica_number" json:"replica_number,omitempty"` // Milvus: in-memory replica count (LoadCollection)
DesiredShardCount int `yaml:"desired_shard_count" json:"desired_shard_count,omitempty"` // Weaviate: number of shards per collection
}
// Value implements the driver.Valuer interface.
@@ -248,12 +258,181 @@ func (c IndexConfig) GetIndexNameOrDefault(engineType RetrieverEngineType) strin
if c.CollectionPrefix != "" {
return c.CollectionPrefix
}
return "WeKnora"
return "Weknora_embeddings"
default:
return c.IndexName
}
}
// ---------------------------------------------------------------------------
// IndexConfig — getter helpers (pointer receiver for nil safety)
// ---------------------------------------------------------------------------
// GetNumberOfShards returns the configured number_of_shards, or def if unset/zero.
func (c *IndexConfig) GetNumberOfShards(def int) int {
if c != nil && c.NumberOfShards > 0 {
return c.NumberOfShards
}
return def
}
// GetNumberOfReplicas returns the configured number_of_replicas, or def if unset/zero.
// Note: 0 replicas cannot be distinguished from "not set" because the int field with
// json:"omitempty" omits zero values. If zero-replica support is needed in the future,
// change the field type to *int. Currently 0 is treated as "use server default".
func (c *IndexConfig) GetNumberOfReplicas(def int) int {
if c != nil && c.NumberOfReplicas > 0 {
return c.NumberOfReplicas
}
return def
}
// GetShardNumber returns the configured shard_number (Qdrant), or def if unset/zero.
func (c *IndexConfig) GetShardNumber(def int) int {
if c != nil && c.ShardNumber > 0 {
return c.ShardNumber
}
return def
}
// GetReplicationFactor returns the configured replication_factor (Qdrant, Weaviate), or def if unset/zero.
func (c *IndexConfig) GetReplicationFactor(def int) int {
if c != nil && c.ReplicationFactor > 0 {
return c.ReplicationFactor
}
return def
}
// GetShardsNum returns the configured shards_num (Milvus), or def if unset/zero.
func (c *IndexConfig) GetShardsNum(def int) int {
if c != nil && c.ShardsNum > 0 {
return c.ShardsNum
}
return def
}
// GetReplicaNumber returns the configured replica_number (Milvus in-memory replicas), or def if unset/zero.
// Milvus replicas are set at LoadCollection time, not CreateCollection.
// They control how many query nodes hold the data in memory for read HA/throughput.
func (c *IndexConfig) GetReplicaNumber(def int) int {
if c != nil && c.ReplicaNumber > 0 {
return c.ReplicaNumber
}
return def
}
// GetDesiredShardCount returns the configured desired_shard_count (Weaviate), or def if unset/zero.
func (c *IndexConfig) GetDesiredShardCount(def int) int {
if c != nil && c.DesiredShardCount > 0 {
return c.DesiredShardCount
}
return def
}
// ---------------------------------------------------------------------------
// IndexConfig — resolve helpers (for Repository layer, with env var fallback)
// ---------------------------------------------------------------------------
// ResolveIndexName returns the index name from IndexConfig, falling back to env var and then default.
// Used by Repository constructors. For service-layer duplicate checking, use GetIndexNameOrDefault instead.
func ResolveIndexName(ic *IndexConfig, envKey, defaultVal string) string {
if ic != nil && ic.IndexName != "" {
return ic.IndexName
}
if v := os.Getenv(envKey); v != "" {
return v
}
return defaultVal
}
// ResolveCollectionName returns the collection name from IndexConfig, falling back to env var and then default.
// Priority: CollectionPrefix > CollectionName > env var > defaultVal.
// CollectionPrefix is checked first because Qdrant/Weaviate use it as the base name.
// CollectionName (Milvus) is checked second. If both are set, CollectionPrefix wins —
// this is safe because each VectorStore has a single engine type, so only one field is relevant.
func ResolveCollectionName(ic *IndexConfig, envKey, defaultVal string) string {
if ic != nil {
if ic.CollectionPrefix != "" {
return ic.CollectionPrefix
}
if ic.CollectionName != "" {
return ic.CollectionName
}
}
if v := os.Getenv(envKey); v != "" {
return v
}
return defaultVal
}
// OptionalUint32 converts int to *uint32 for Qdrant SDK.
// Returns nil for values <= 0, which tells Qdrant to use its server default.
func OptionalUint32(v int) *uint32 {
if v <= 0 {
return nil
}
u := uint32(v)
return &u
}
// ---------------------------------------------------------------------------
// IndexConfig — validation
// ---------------------------------------------------------------------------
const (
// maxShards is the upper bound for shard-related configuration values.
maxShards = 64
// maxReplicas is the upper bound for replication-related configuration values.
maxReplicas = 10
)
// validIndexNamePattern restricts index/collection names to safe characters.
// Must start with a letter, followed by alphanumeric, underscore, or hyphen. Max 128 chars.
var validIndexNamePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_-]{0,127}$`)
// ValidateIndexConfig checks IndexConfig fields for safe values.
// Call this from the service layer before persisting a VectorStore.
func ValidateIndexConfig(ic IndexConfig) error {
// Validate string fields (index/collection names)
if ic.IndexName != "" && !validIndexNamePattern.MatchString(ic.IndexName) {
return errors.NewValidationError(
"index_name must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)")
}
if ic.CollectionPrefix != "" && !validIndexNamePattern.MatchString(ic.CollectionPrefix) {
return errors.NewValidationError(
"collection_prefix must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)")
}
if ic.CollectionName != "" && !validIndexNamePattern.MatchString(ic.CollectionName) {
return errors.NewValidationError(
"collection_name must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)")
}
// Validate numeric fields (shards/replicas) — must be within safe bounds
if ic.NumberOfShards < 0 || ic.NumberOfShards > maxShards {
return errors.NewValidationError(fmt.Sprintf("number_of_shards must be between 0 and %d", maxShards))
}
if ic.NumberOfReplicas < 0 || ic.NumberOfReplicas > maxReplicas {
return errors.NewValidationError(fmt.Sprintf("number_of_replicas must be between 0 and %d", maxReplicas))
}
if ic.ShardNumber < 0 || ic.ShardNumber > maxShards {
return errors.NewValidationError(fmt.Sprintf("shard_number must be between 0 and %d", maxShards))
}
if ic.ReplicationFactor < 0 || ic.ReplicationFactor > maxReplicas {
return errors.NewValidationError(fmt.Sprintf("replication_factor must be between 0 and %d", maxReplicas))
}
if ic.ShardsNum < 0 || ic.ShardsNum > maxShards {
return errors.NewValidationError(fmt.Sprintf("shards_num must be between 0 and %d", maxShards))
}
if ic.ReplicaNumber < 0 || ic.ReplicaNumber > maxReplicas {
return errors.NewValidationError(fmt.Sprintf("replica_number must be between 0 and %d", maxReplicas))
}
if ic.DesiredShardCount < 0 || ic.DesiredShardCount > maxShards {
return errors.NewValidationError(fmt.Sprintf("desired_shard_count must be between 0 and %d", maxShards))
}
return nil
}
// ---------------------------------------------------------------------------
// VectorStoreResponse — API response DTO
// ---------------------------------------------------------------------------
@@ -339,7 +518,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo {
{Name: "use_tls", Type: "boolean", Required: false, Default: false},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings"},
{Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Prefix"},
{Name: "shard_number", Type: "number", Required: false, Default: 1, Description: "Shard Number"},
{Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"},
},
},
{
@@ -351,7 +532,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo {
{Name: "password", Type: "string", Required: false, Sensitive: true},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings"},
{Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Name"},
{Name: "shards_num", Type: "number", Required: false, Default: 1, Description: "Shards (write parallelism)"},
{Name: "replica_number", Type: "number", Required: false, Default: 1, Description: "In-memory Replicas (read HA)"},
},
},
{
@@ -364,7 +547,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo {
{Name: "api_key", Type: "string", Required: false, Sensitive: true},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_prefix", Type: "string", Required: false, Default: "WeKnora"},
{Name: "collection_prefix", Type: "string", Required: false, Default: "Weknora_embeddings", Description: "Collection Prefix"},
{Name: "desired_shard_count", Type: "number", Required: false, Default: 1, Description: "Shard Count"},
{Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"},
},
},
{
+299 -1
View File
@@ -622,7 +622,7 @@ func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) {
name: "weaviate default",
config: IndexConfig{},
engineType: WeaviateRetrieverEngineType,
expected: "WeKnora",
expected: "Weknora_embeddings",
},
// Postgres (no index config)
{
@@ -645,3 +645,301 @@ func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) {
})
}
}
// ---------------------------------------------------------------------------
// IndexConfig — getter helpers
// ---------------------------------------------------------------------------
func TestIndexConfig_GetterHelpers(t *testing.T) {
t.Run("nil receiver returns default", func(t *testing.T) {
var ic *IndexConfig
assert.Equal(t, 5, ic.GetNumberOfShards(5))
assert.Equal(t, -1, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 0, ic.GetShardNumber(0))
assert.Equal(t, 0, ic.GetReplicationFactor(0))
assert.Equal(t, 1, ic.GetShardsNum(1))
assert.Equal(t, 0, ic.GetReplicaNumber(0))
assert.Equal(t, 0, ic.GetDesiredShardCount(0))
})
t.Run("zero value returns default", func(t *testing.T) {
ic := &IndexConfig{}
assert.Equal(t, 5, ic.GetNumberOfShards(5))
assert.Equal(t, -1, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 0, ic.GetShardNumber(0))
assert.Equal(t, 0, ic.GetReplicationFactor(0))
assert.Equal(t, 1, ic.GetShardsNum(1))
assert.Equal(t, 0, ic.GetReplicaNumber(0))
assert.Equal(t, 0, ic.GetDesiredShardCount(0))
})
t.Run("positive value overrides default", func(t *testing.T) {
ic := &IndexConfig{
NumberOfShards: 3,
NumberOfReplicas: 2,
ShardNumber: 4,
ReplicationFactor: 3,
ShardsNum: 5,
ReplicaNumber: 2,
DesiredShardCount: 3,
}
assert.Equal(t, 3, ic.GetNumberOfShards(1))
assert.Equal(t, 2, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 4, ic.GetShardNumber(0))
assert.Equal(t, 3, ic.GetReplicationFactor(0))
assert.Equal(t, 5, ic.GetShardsNum(1))
assert.Equal(t, 2, ic.GetReplicaNumber(0))
assert.Equal(t, 3, ic.GetDesiredShardCount(0))
})
t.Run("negative value returns default (treated as unset)", func(t *testing.T) {
ic := &IndexConfig{
NumberOfShards: -1,
NumberOfReplicas: -1,
ShardNumber: -5,
ReplicationFactor: -1,
ShardsNum: -1,
ReplicaNumber: -1,
DesiredShardCount: -1,
}
assert.Equal(t, 1, ic.GetNumberOfShards(1))
assert.Equal(t, -1, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 0, ic.GetShardNumber(0))
assert.Equal(t, 0, ic.GetReplicationFactor(0))
assert.Equal(t, 1, ic.GetShardsNum(1))
assert.Equal(t, 0, ic.GetReplicaNumber(0))
assert.Equal(t, 0, ic.GetDesiredShardCount(0))
})
}
// ---------------------------------------------------------------------------
// IndexConfig — resolve helpers
// ---------------------------------------------------------------------------
func TestResolveIndexName(t *testing.T) {
t.Run("nil IndexConfig falls back to env var", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "env_index")
assert.Equal(t, "env_index", ResolveIndexName(nil, "ELASTICSEARCH_INDEX", "default"))
})
t.Run("nil IndexConfig falls back to default when env empty", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "")
assert.Equal(t, "xwrag_default", ResolveIndexName(nil, "ELASTICSEARCH_INDEX", "xwrag_default"))
})
t.Run("IndexConfig value takes precedence over env var", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "env_index")
ic := &IndexConfig{IndexName: "custom_index"}
assert.Equal(t, "custom_index", ResolveIndexName(ic, "ELASTICSEARCH_INDEX", "default"))
})
t.Run("empty IndexConfig.IndexName falls back to env var", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "env_index")
ic := &IndexConfig{}
assert.Equal(t, "env_index", ResolveIndexName(ic, "ELASTICSEARCH_INDEX", "default"))
})
}
func TestResolveCollectionName(t *testing.T) {
t.Run("nil IndexConfig falls back to env var", func(t *testing.T) {
t.Setenv("QDRANT_COLLECTION", "env_collection")
assert.Equal(t, "env_collection", ResolveCollectionName(nil, "QDRANT_COLLECTION", "default"))
})
t.Run("CollectionPrefix takes precedence over CollectionName", func(t *testing.T) {
ic := &IndexConfig{CollectionPrefix: "prefix_name", CollectionName: "full_name"}
assert.Equal(t, "prefix_name", ResolveCollectionName(ic, "QDRANT_COLLECTION", "default"))
})
t.Run("CollectionName used when CollectionPrefix empty", func(t *testing.T) {
ic := &IndexConfig{CollectionName: "full_name"}
assert.Equal(t, "full_name", ResolveCollectionName(ic, "MILVUS_COLLECTION", "default"))
})
t.Run("empty IndexConfig falls back to default", func(t *testing.T) {
t.Setenv("QDRANT_COLLECTION", "")
ic := &IndexConfig{}
assert.Equal(t, "weknora_embeddings", ResolveCollectionName(ic, "QDRANT_COLLECTION", "weknora_embeddings"))
})
}
// ---------------------------------------------------------------------------
// OptionalUint32
// ---------------------------------------------------------------------------
func TestOptionalUint32(t *testing.T) {
t.Run("zero returns nil", func(t *testing.T) {
assert.Nil(t, OptionalUint32(0))
})
t.Run("negative returns nil", func(t *testing.T) {
assert.Nil(t, OptionalUint32(-1))
assert.Nil(t, OptionalUint32(-100))
})
t.Run("positive returns pointer to uint32", func(t *testing.T) {
result := OptionalUint32(3)
require.NotNil(t, result)
assert.Equal(t, uint32(3), *result)
})
t.Run("large positive value", func(t *testing.T) {
result := OptionalUint32(64)
require.NotNil(t, result)
assert.Equal(t, uint32(64), *result)
})
}
// ---------------------------------------------------------------------------
// ValidateIndexConfig
// ---------------------------------------------------------------------------
func TestValidateIndexConfig(t *testing.T) {
t.Run("empty config is valid", func(t *testing.T) {
assert.NoError(t, ValidateIndexConfig(IndexConfig{}))
})
t.Run("valid config with all fields", func(t *testing.T) {
ic := IndexConfig{
IndexName: "my_index",
NumberOfShards: 3,
NumberOfReplicas: 1,
CollectionPrefix: "my_collection",
ShardNumber: 4,
ReplicationFactor: 2,
ShardsNum: 2,
ReplicaNumber: 3,
DesiredShardCount: 2,
}
assert.NoError(t, ValidateIndexConfig(ic))
})
// --- Name validation ---
t.Run("index_name with special chars rejected", func(t *testing.T) {
ic := IndexConfig{IndexName: "my index*"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "index_name")
})
t.Run("index_name starting with number rejected", func(t *testing.T) {
ic := IndexConfig{IndexName: "123abc"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
})
t.Run("collection_prefix with slash rejected", func(t *testing.T) {
ic := IndexConfig{CollectionPrefix: "path/to/collection"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "collection_prefix")
})
t.Run("collection_name with dot rejected", func(t *testing.T) {
ic := IndexConfig{CollectionName: "my.collection"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "collection_name")
})
t.Run("valid names with underscore and hyphen", func(t *testing.T) {
ic := IndexConfig{
IndexName: "my_index-v2",
CollectionPrefix: "Weknora_embeddings",
CollectionName: "custom-collection-name",
}
assert.NoError(t, ValidateIndexConfig(ic))
})
// --- Numeric bounds ---
t.Run("number_of_shards exceeds max", func(t *testing.T) {
ic := IndexConfig{NumberOfShards: 100}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "number_of_shards")
})
t.Run("negative number_of_shards rejected", func(t *testing.T) {
ic := IndexConfig{NumberOfShards: -1}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "number_of_shards")
})
t.Run("replication_factor exceeds max", func(t *testing.T) {
ic := IndexConfig{ReplicationFactor: 50}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "replication_factor")
})
t.Run("shard_number at max boundary is valid", func(t *testing.T) {
ic := IndexConfig{ShardNumber: 64}
assert.NoError(t, ValidateIndexConfig(ic))
})
t.Run("replication_factor at max boundary is valid", func(t *testing.T) {
ic := IndexConfig{ReplicationFactor: 10}
assert.NoError(t, ValidateIndexConfig(ic))
})
t.Run("shards_num exceeds max", func(t *testing.T) {
ic := IndexConfig{ShardsNum: 999}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "shards_num")
})
t.Run("replica_number exceeds max", func(t *testing.T) {
ic := IndexConfig{ReplicaNumber: 50}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "replica_number")
})
t.Run("desired_shard_count exceeds max", func(t *testing.T) {
ic := IndexConfig{DesiredShardCount: 100}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "desired_shard_count")
})
}
// ---------------------------------------------------------------------------
// IndexConfig — scalability fields round-trip
// ---------------------------------------------------------------------------
func TestIndexConfig_ScalabilityFieldsRoundTrip(t *testing.T) {
t.Run("scalability fields serialize and deserialize", func(t *testing.T) {
original := IndexConfig{
IndexName: "my_index",
NumberOfShards: 3,
NumberOfReplicas: 1,
CollectionPrefix: "my_prefix",
ShardNumber: 4,
ReplicationFactor: 2,
ShardsNum: 5,
ReplicaNumber: 3,
DesiredShardCount: 2,
}
raw, err := original.Value()
require.NoError(t, err)
var scanned IndexConfig
require.NoError(t, scanned.Scan(raw.([]byte)))
assert.Equal(t, original, scanned)
})
t.Run("scalability fields omitted when zero", func(t *testing.T) {
raw, err := IndexConfig{IndexName: "test"}.Value()
require.NoError(t, err)
var parsed map[string]interface{}
require.NoError(t, json.Unmarshal(raw.([]byte), &parsed))
assert.NotContains(t, parsed, "shard_number")
assert.NotContains(t, parsed, "replication_factor")
assert.NotContains(t, parsed, "shards_num")
assert.NotContains(t, parsed, "replica_number")
assert.NotContains(t, parsed, "desired_shard_count")
})
}