diff --git a/go.mod b/go.mod index 7c43e09a..b51c7843 100644 --- a/go.mod +++ b/go.mod @@ -236,6 +236,7 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/oklog/ulid/v2 v2.1.1 // indirect github.com/opencontainers/runtime-spec v1.0.2 // indirect + github.com/opensearch-project/opensearch-go/v4 v4.6.0 // indirect github.com/parquet-go/bitpack v1.0.0 // indirect github.com/parquet-go/jsonlite v1.0.0 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect @@ -269,9 +270,9 @@ require ( github.com/spf13/pflag v1.0.10 // indirect github.com/stretchr/objx v0.5.3 // indirect github.com/subosito/gotenv v1.6.0 // indirect - github.com/tidwall/gjson v1.17.1 // indirect + github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.0 // indirect + github.com/tidwall/pretty v1.2.1 // indirect github.com/tiendc/go-deepcopy v1.7.2 // indirect github.com/tinylib/msgp v1.6.1 // indirect github.com/tklauser/go-sysconf v0.3.16 // indirect diff --git a/go.sum b/go.sum index 2c1b5406..533b0800 100644 --- a/go.sum +++ b/go.sum @@ -2254,6 +2254,8 @@ github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJw github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/opencontainers/runtime-spec v1.0.2 h1:UfAcuLBJB9Coz72x1hgl8O5RVzTdNiaglX6v2DM6FI0= github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opensearch-project/opensearch-go/v4 v4.6.0 h1:Ac8aLtDSmLEyOmv0r1qhQLw3b4vcUhE42NE9k+Z4cRc= +github.com/opensearch-project/opensearch-go/v4 v4.6.0/go.mod h1:3iZtb4SNt3IzaxavKq0dURh1AmtVgYW71E4XqmYnIiQ= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw= github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= @@ -2483,10 +2485,14 @@ github.com/tencentyun/cos-go-sdk-v5 v0.7.73/go.mod h1:STbTNaNKq03u+gscPEGOahKzLc github.com/tencentyun/qcloud-cos-sts-sdk v0.0.0-20250515025012-e0eec8a5d123/go.mod h1:b18KQa4IxHbxeseW1GcZox53d7J0z39VNONTxvvlkXw= github.com/tidwall/gjson v1.17.1 h1:wlYEnwqAHgzmhNUFfw7Xalt2JzQvsMx2Se4PcoFCT/U= github.com/tidwall/gjson v1.17.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44= github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ= github.com/tiktoken-go/tokenizer v0.7.0 h1:VMu6MPT0bXFDHr7UPh9uii7CNItVt3X9K90omxL54vw= diff --git a/internal/application/repository/retriever/opensearch/config.go b/internal/application/repository/retriever/opensearch/config.go new file mode 100644 index 00000000..90b8f9b1 --- /dev/null +++ b/internal/application/repository/retriever/opensearch/config.go @@ -0,0 +1,47 @@ +package opensearch + +import "github.com/Tencent/WeKnora/internal/types" + +// internalCfg is the driver-internal, immutable view of IndexConfig. +// Defaults are chosen so the env-path (no IndexConfig) and DB-store path +// (with IndexConfig) produce identical mappings. +type internalCfg struct { + shards int + replicas int + knnEngine string // "lucene" | "faiss" + hnswM int + hnswEFConstruction int + efSearch int +} + +// buildInternalCfg projects IndexConfig to the driver-internal view, +// substituting defaults for unset fields. Validation of value ranges +// (e.g. hnsw_m / ef_construction caps) is a service-layer concern handled +// elsewhere; this function applies defaults only and never rejects. +// +// OpenSearch-specific overrides (knn_engine, hnsw_m, hnsw_ef_construction, +// hnsw_ef_search) are intentionally NOT read from IndexConfig here: +// IndexConfig is a schema shared across all drivers, and adding OpenSearch- +// specific fields would surface them in the shared VectorStoreFieldInfo +// form visible to every driver's create UI. Wiring those fields through to +// IndexConfig is a follow-up that lands alongside the activation switch. +func buildInternalCfg(c *types.IndexConfig) (internalCfg, error) { + cfg := internalCfg{ + shards: 4, // matches the keyword-index default upstream + replicas: 1, // assumes >= 2-node cluster + knnEngine: "lucene", // OS default; Faiss preferred only at >= 10M docs + hnswM: 16, // OS official default + hnswEFConstruction: 100, // OS official default + efSearch: 100, // OS default + } + if c == nil { + return cfg, nil + } + if c.NumberOfShards > 0 { + cfg.shards = c.NumberOfShards + } + if c.NumberOfReplicas > 0 { + cfg.replicas = c.NumberOfReplicas + } + return cfg, nil +} diff --git a/internal/application/repository/retriever/opensearch/errors.go b/internal/application/repository/retriever/opensearch/errors.go new file mode 100644 index 00000000..7e492772 --- /dev/null +++ b/internal/application/repository/retriever/opensearch/errors.go @@ -0,0 +1,62 @@ +// Package opensearch implements the RetrieveEngineRepository interface +// for OpenSearch k-NN native vector search. +package opensearch + +import "errors" + +// Sentinel errors returned by Repository. The service-layer factory wraps +// these into typed AppError values (2200/2201) — the repository itself +// never imports internal/errors. The boundary is intentional (directional +// dependency). +var ( + // ErrIndexNotFound — alias / underlying index missing. Search and + // delete-by-query operations return this when the per-dim alias has + // not been created yet (no Save has been issued for that dim). + ErrIndexNotFound = errors.New("opensearch: index not found") + + // ErrDimensionMismatch — embedding dimension violates the per-dim + // invariant (e.g. dim <= 0, dim > 16000, or embeddings within a + // single batch disagree). + ErrDimensionMismatch = errors.New("opensearch: embedding dimension mismatch") + + // ErrAuth — cluster returned 401 / 403. Distinguished from ErrTransport + // so the service layer can map to a clean 4xx instead of 503. + ErrAuth = errors.New("opensearch: authentication failed") + + // ErrTransport — network / 5xx / opaque cluster error. Classified as + // transient: ensureReady does NOT persist this in initErr, so the next + // caller will retry. + ErrTransport = errors.New("opensearch: transport error") + + // ErrVersionUnsupported — cluster is not OpenSearch, is OS 1.x, or is + // OS 2.0~2.3 (pre-Lucene-HNSW-GA). probeVersion enforces. + ErrVersionUnsupported = errors.New("opensearch: cluster version unsupported") + + // ErrConfigInvalid — IndexConfig / storeID / sanitizeIndexName guard + // failed, or the k-NN plugin is missing on one or more cluster nodes. + ErrConfigInvalid = errors.New("opensearch: invalid index config") + + // ErrFeatureNotEnabled — stubs.go returns this from methods whose real + // implementation has not landed yet (CopyIndices / BatchUpdateChunk* / + // swapToVersion, plus the read/write methods that a follow-up commit + // will replace with production code). + ErrFeatureNotEnabled = errors.New("opensearch: feature not enabled in this build") + + // ErrBatchTooLarge — Save / Delete batch exceeded the driver's sync + // cap. Distinct from ErrFeatureNotEnabled so the service layer can + // chunk + retry rather than treat the failure as "waiting on a future + // implementation." + ErrBatchTooLarge = errors.New("opensearch: batch size exceeds driver cap") + + // ErrCircuitBreaker — OpenSearch k-NN circuit breaker returned 429 + // (knn_circuit_breaker_exception). Classified as transient so the + // caller can retry after the operator scales the cluster. + ErrCircuitBreaker = errors.New("opensearch: knn circuit breaker open") +) + +// isTransientErr classifies sentinel errors. Transient errors do not get +// persisted in ensureReady's initErr cache — they can be retried by the +// next caller after the underlying cause clears. +func isTransientErr(err error) bool { + return errors.Is(err, ErrTransport) || errors.Is(err, ErrCircuitBreaker) +} diff --git a/internal/application/repository/retriever/opensearch/mapping.go b/internal/application/repository/retriever/opensearch/mapping.go new file mode 100644 index 00000000..451d98ca --- /dev/null +++ b/internal/application/repository/retriever/opensearch/mapping.go @@ -0,0 +1,408 @@ +package opensearch + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + + osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// createIndexAndAlias creates "_v1" with the full k-NN mapping +// and then aliases "" → "_v1". Idempotent: returns nil if +// the alias already exists (so concurrent NewRepository calls in +// different processes don't race the PUT). +// +// Orphan cleanup: if aliasPut fails after a successful indicesCreate, +// the function attempts best-effort DELETE of the orphan _v1 index. +// Cleanup failure is logged but does not mask the original aliasPut +// error. +// +// Mapping-drift detection: if indicesCreate returns +// resource_already_exists_exception (cross-process race), the existing +// mapping's structural fingerprint is checked against the expected +// fingerprint. Drift returns ErrConfigInvalid wrapping a clear "manual +// reindex required" message instead of silently overlaying a foreign +// mapping. +func (r *Repository) createIndexAndAlias(ctx context.Context, dim int) error { + log := logger.GetLogger(ctx) + alias := r.indexAlias(dim) + realIndex := alias + "_v1" + + exists, err := r.aliasExists(ctx, alias) + if err != nil { + return fmt.Errorf("alias check %s: %w", alias, err) + } + if exists { + return nil // another writer already set it up + } + + body, err := buildIndexMapping(r.cfg, dim) + if err != nil { + return fmt.Errorf("build mapping for dim=%d: %w", dim, err) + } + + indexCreated := false + if err := r.indicesCreate(ctx, realIndex, body); err != nil { + if isAlreadyExistsError(err) { + // Cross-process race or stale orphan. Verify the existing + // mapping matches what we expected; drift → ErrConfigInvalid. + if driftErr := r.verifyMappingMatches(ctx, realIndex, body); driftErr != nil { + return fmt.Errorf( + "mapping drift on %s: existing index has incompatible mapping; "+ + "manual reindex required: %w", + realIndex, driftErr, + ) + } + // Mapping matches → safe to proceed with alias setup. + } else { + return fmt.Errorf("create index %s: %w", realIndex, err) + } + } else { + indexCreated = true + } + + if err := r.aliasPut(ctx, realIndex, alias); err != nil { + // Best-effort orphan cleanup so future retries find a clean slate. + if indexCreated { + if delErr := r.indicesDelete(ctx, realIndex); delErr != nil { + log.Warnf("[OpenSearch] orphan cleanup failed for %s: %v "+ + "(operator must DELETE manually)", realIndex, delErr) + } else { + log.Infof("[OpenSearch] cleaned up orphan %s after aliasPut failure", realIndex) + } + } + return fmt.Errorf("put alias %s → %s: %w", alias, realIndex, err) + } + return nil +} + +// buildIndexMapping returns the full mapping JSON for a new OpenSearch +// k-NN index. content uses the standard analyzer (BM25 default); all +// *_id fields are explicit keyword sub-fields so DeleteByQuery / terms +// filters hit them without the ES v8 "useKeywordSuffix" auto-detection +// dance. +// +// match_type is intentionally NOT in the mapping — it's a per-result +// classification derived from RetrieverType at parse time. source_type +// is stored as `integer` (not stringified) so the wire format remains +// stable across SourceType enum extension. +// +// Pure function — no IO, no logging. Easy to unit-test (byte-exact diff). +func buildIndexMapping(cfg internalCfg, dim int) ([]byte, error) { + type mapping struct { + Settings struct { + Index struct { + Knn bool `json:"knn"` + NumberOfShards int `json:"number_of_shards"` + NumberOfReplicas int `json:"number_of_replicas"` + RefreshInterval string `json:"refresh_interval"` + KnnAlgoParamEFSearch int `json:"knn.algo_param.ef_search"` + } `json:"index"` + } `json:"settings"` + Mappings struct { + Properties map[string]any `json:"properties"` + } `json:"mappings"` + } + var m mapping + m.Settings.Index.Knn = true + m.Settings.Index.NumberOfShards = cfg.shards + m.Settings.Index.NumberOfReplicas = cfg.replicas + m.Settings.Index.RefreshInterval = "1s" + m.Settings.Index.KnnAlgoParamEFSearch = cfg.efSearch + m.Mappings.Properties = map[string]any{ + "embedding": map[string]any{ + "type": "knn_vector", + "dimension": dim, + "method": map[string]any{ + "name": "hnsw", + "space_type": "cosinesimil", + "engine": cfg.knnEngine, + "parameters": map[string]any{ + "m": cfg.hnswM, + "ef_construction": cfg.hnswEFConstruction, + }, + }, + }, + "content": map[string]any{"type": "text", "analyzer": "standard"}, + "chunk_id": map[string]any{"type": "keyword"}, + "knowledge_id": map[string]any{"type": "keyword"}, + "knowledge_base_id": map[string]any{"type": "keyword"}, + "tag_id": map[string]any{"type": "keyword"}, + "source_id": map[string]any{"type": "keyword"}, + "source_type": map[string]any{"type": "integer"}, + "is_enabled": map[string]any{"type": "boolean"}, + "is_recommended": map[string]any{"type": "boolean"}, + } + out, err := json.Marshal(&m) + if err != nil { + // Cannot happen for our internal struct, but propagate for symmetry + // with the other JSON builders in the package. + return nil, fmt.Errorf("marshal mapping: %w", err) + } + return out, nil +} + +// buildKeywordsMapping returns the mapping for the dim-less keyword-only +// index. Same as buildIndexMapping but with the embedding field omitted +// — used by the no-embedding save path (the service layer dispatches +// there when the knowledge base has vector indexing disabled). +func buildKeywordsMapping(cfg internalCfg) ([]byte, error) { + type mapping struct { + Settings struct { + Index struct { + NumberOfShards int `json:"number_of_shards"` + NumberOfReplicas int `json:"number_of_replicas"` + RefreshInterval string `json:"refresh_interval"` + } `json:"index"` + } `json:"settings"` + Mappings struct { + Properties map[string]any `json:"properties"` + } `json:"mappings"` + } + var m mapping + m.Settings.Index.NumberOfShards = cfg.shards + m.Settings.Index.NumberOfReplicas = cfg.replicas + m.Settings.Index.RefreshInterval = "1s" + m.Mappings.Properties = map[string]any{ + "content": map[string]any{"type": "text", "analyzer": "standard"}, + "chunk_id": map[string]any{"type": "keyword"}, + "knowledge_id": map[string]any{"type": "keyword"}, + "knowledge_base_id": map[string]any{"type": "keyword"}, + "tag_id": map[string]any{"type": "keyword"}, + "source_id": map[string]any{"type": "keyword"}, + "source_type": map[string]any{"type": "integer"}, + "is_enabled": map[string]any{"type": "boolean"}, + "is_recommended": map[string]any{"type": "boolean"}, + } + out, err := json.Marshal(&m) + if err != nil { + return nil, fmt.Errorf("marshal keywords mapping: %w", err) + } + return out, nil +} + +// ensureKeywordsIndex creates the dim-less keyword-only index used by +// the no-embedding save path. mutex + flag pattern so transient +// failures can be retried by the next caller (sync.Once cannot be +// reset). +func (r *Repository) ensureKeywordsIndex(ctx context.Context) error { + r.keywordsMu.Lock() + defer r.keywordsMu.Unlock() + + if r.keywordsReady { + return nil + } + if r.keywordsErr != nil && !isTransientErr(r.keywordsErr) { + // Permanent failure — don't retry, surface the same error. + return r.keywordsErr + } + + name := r.keywordsIndex() + exists, err := r.aliasExists(ctx, name) // returns true if index exists too + if err != nil { + r.keywordsErr = err + return err + } + if exists { + r.keywordsReady = true + r.keywordsErr = nil + return nil + } + body, err := buildKeywordsMapping(r.cfg) + if err != nil { + r.keywordsErr = err + return err + } + if err := r.indicesCreate(ctx, name, body); err != nil { + if !isAlreadyExistsError(err) { + r.keywordsErr = err + return err + } + // resource_already_exists_exception — race with concurrent process, + // treat as success. + } + r.keywordsReady = true + r.keywordsErr = nil + return nil +} + +// indicesCreate is the low-level wrapper around Indices.Create. Body is +// the JSON mapping produced by buildIndexMapping. +func (r *Repository) indicesCreate(ctx context.Context, name string, body []byte) error { + req := osapi.IndicesCreateReq{Index: name, Body: bytes.NewReader(body)} + resp, err := r.client.Indices.Create(ctx, req) + if err != nil { + return wrapTransport(err) + } + if resp != nil { + drainAndClose(resp.Inspect().Response.Body) + } + return nil +} + +// indicesDelete is used by createIndexAndAlias's orphan cleanup path. +// Caller decides what to do with the error. +func (r *Repository) indicesDelete(ctx context.Context, name string) error { + req := osapi.IndicesDeleteReq{Indices: []string{name}} + resp, err := r.client.Indices.Delete(ctx, req) + if err != nil { + return wrapTransport(err) + } + if resp != nil { + drainAndClose(resp.Inspect().Response.Body) + } + return nil +} + +// aliasExists uses HEAD /_alias/ (Indices.Alias.Exists) — returns +// true on 200, false on 404, error on 5xx / transport. +// +// SDK quirk (opensearch-go v4.6.0): the Exists method passes +// dataPointer=nil to its internal do(), which means non-2xx responses +// come back as a plain *errors.errorString ("status: 404 Not Found") +// rather than as a *opensearch.StructError. We therefore inspect +// resp.StatusCode directly (resp is always returned even when err is +// non-nil) and only fall back to wrapTransport for the "no response at +// all" case (true network failure). +func (r *Repository) aliasExists(ctx context.Context, alias string) (bool, error) { + req := osapi.AliasExistsReq{Alias: []string{alias}} + resp, err := r.client.Indices.Alias.Exists(ctx, req) + if resp != nil { + statusCode := resp.StatusCode + drainAndClose(resp.Body) + switch statusCode { + case 200: + return true, nil + case 404: + return false, nil + } + // Unexpected status (5xx) — fall through to the err path so + // wrapTransport can classify (and so the test handler's + // errBody is logged for diagnosis). + } + if err != nil { + return false, wrapTransport(err) + } + return false, nil +} + +// aliasPut creates an alias pointing at index. Single add operation +// (rolling-reindex atomic swap is deferred to a follow-up PR — see +// stubs.go swapToVersion). +func (r *Repository) aliasPut(ctx context.Context, index, alias string) error { + req := osapi.AliasPutReq{ + Indices: []string{index}, + Alias: alias, + } + resp, err := r.client.Indices.Alias.Put(ctx, req) + if err != nil { + return wrapTransport(err) + } + if resp != nil { + drainAndClose(resp.Inspect().Response.Body) + } + return nil +} + +// verifyMappingMatches GETs the existing index's mapping and compares +// the embedding field's structural fingerprint (dimension, HNSW +// parameters, engine) against the expected. A full field-by-field diff +// would be ideal but expensive; we check only the parts that matter for +// query correctness. +func (r *Repository) verifyMappingMatches(ctx context.Context, index string, expected []byte) error { + req := osapi.MappingGetReq{Indices: []string{index}} + resp, err := r.client.Indices.Mapping.Get(ctx, &req) + if err != nil { + return fmt.Errorf("get mapping %s: %w", index, wrapTransport(err)) + } + if resp != nil { + drainAndClose(resp.Inspect().Response.Body) + } + + // Both fingerprints are derived from the mapping's embedding-field + // HNSW parameters: dimension, m, ef_construction, engine, space_type. + // We parse the expected (our own JSON) and the actual (cluster + // response) and compare just those bits. + expectedFP, err := extractEmbeddingFingerprint(expected) + if err != nil { + return fmt.Errorf("parse expected fingerprint: %w", err) + } + actualFP, err := extractMappingFingerprintFromResp(resp, index) + if err != nil { + return fmt.Errorf("parse actual fingerprint: %w", err) + } + if expectedFP != actualFP { + return fmt.Errorf("mapping fingerprint mismatch: expected %+v, got %+v: %w", + expectedFP, actualFP, ErrConfigInvalid) + } + return nil +} + +// embFingerprint is the minimal set of HNSW parameters that uniquely +// determine query semantics for a k-NN index. If any of these differ +// between create-time and an existing index, retrieval is incorrect. +type embFingerprint struct { + Dimension int + M int + EFConstruction int + Engine string + SpaceType string +} + +// extractEmbeddingFingerprint parses our own mapping JSON (produced by +// buildIndexMapping) to pull out the HNSW parameters. +func extractEmbeddingFingerprint(body []byte) (embFingerprint, error) { + var m struct { + Mappings struct { + Properties map[string]any `json:"properties"` + } `json:"mappings"` + } + if err := json.Unmarshal(body, &m); err != nil { + return embFingerprint{}, err + } + return extractFingerprintFromProps(m.Mappings.Properties) +} + +// extractMappingFingerprintFromResp parses the cluster's GET-mapping +// response and pulls out the embedding-field HNSW fingerprint for the +// given index. +func extractMappingFingerprintFromResp(resp *osapi.MappingGetResp, index string) (embFingerprint, error) { + indexMapping, ok := resp.Indices[index] + if !ok { + return embFingerprint{}, fmt.Errorf("index %s not in mapping response", index) + } + // MappingGetResp.Indices[index].Mappings is a json.RawMessage in + // the SDK — we decode the inner properties shape ourselves. + var m struct { + Properties map[string]any `json:"properties"` + } + if err := json.Unmarshal(indexMapping.Mappings, &m); err != nil { + return embFingerprint{}, err + } + return extractFingerprintFromProps(m.Properties) +} + +func extractFingerprintFromProps(props map[string]any) (embFingerprint, error) { + emb, ok := props["embedding"].(map[string]any) + if !ok { + return embFingerprint{}, fmt.Errorf("embedding field missing or wrong type") + } + dim, _ := emb["dimension"].(float64) // json.Unmarshal produces float64 for numbers + method, _ := emb["method"].(map[string]any) + engine, _ := method["engine"].(string) + spaceType, _ := method["space_type"].(string) + params, _ := method["parameters"].(map[string]any) + m, _ := params["m"].(float64) + efc, _ := params["ef_construction"].(float64) + return embFingerprint{ + Dimension: int(dim), + M: int(m), + EFConstruction: int(efc), + Engine: engine, + SpaceType: spaceType, + }, nil +} diff --git a/internal/application/repository/retriever/opensearch/repository.go b/internal/application/repository/retriever/opensearch/repository.go new file mode 100644 index 00000000..fee20f9a --- /dev/null +++ b/internal/application/repository/retriever/opensearch/repository.go @@ -0,0 +1,443 @@ +package opensearch + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" + "sync" + + "github.com/opensearch-project/opensearch-go/v4" + osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// EngineAwareNormalizer applies the documented per-engine cosine-score +// formula. (Repository implements interfaces.RetrieveEngineRepository for +// OpenSearch k-NN. Safe for concurrent use after construction: all fields +// except the once / initErr maps are read-only after NewRepository returns; +// per-dimension index initialization is guarded by sync.Once. +// +// Lifecycle: NewRepository validates connectivity + cluster version + +// k-NN plugin, but does NOT create any index. Index creation happens +// lazily on first Save / BatchSave / Retrieve once the embedding +// dimension is known (see ensureReady — per-dimension index naming). +// +// Concurrency: A single Repository instance is shared across N goroutines +// concurrently retrieving from the same store (the multi-store fan-out +// dispatcher in the service layer). The struct is therefore designed to +// be allocation-stable after construction; the only mutable state is the +// sync.Once + initErr maps, each guarded by its own mutex. +// +// CRITICAL INVARIANT: initErr[dim] = err must be written INSIDE the +// once.Do closure — moving it outside opens a TOCTOU where a concurrent +// caller reads zero before the first caller persists. +type Repository struct { + client *osapi.Client + baseIndex string // pre-suffix base name, e.g. "weknora_abcdef012345" + cfg internalCfg // immutable after construction (value, not pointer) + + // Per-dimension lazy initialization. ensureReady(ctx, dim) inserts an + // entry the first time dim is seen, runs the create-index work inside + // sync.Once, and persists any permanent error so subsequent callers + // see the same failure without re-attempting the PUT. Transient + // errors (ErrTransport, ErrCircuitBreaker) are NOT persisted — the + // next caller retries. + onceMu sync.Mutex + once map[int]*sync.Once + initMu sync.Mutex + initErr map[int]error + + // Lazy init state for the dim-less keyword-only index used by the + // no-embedding path (concurrentBatchSaveNoEmbedding in the service + // layer). Mutex + flag pattern (rather than sync.Once) so transient + // failures can be retried by the next caller — sync.Once does not + // support reset. + keywordsMu sync.Mutex + keywordsReady bool + keywordsErr error +} + +// Compile-time interface satisfaction (Go best practice — keeps the build +// red if the interface drifts and our implementation lags). +var _ interfaces.RetrieveEngineRepository = (*Repository)(nil) + +// NewRepository builds a new OpenSearch k-NN repository and verifies the +// backing cluster is reachable + version-compatible + has the k-NN +// plugin installed on every cluster node. It does NOT create any index — +// callers (Save / Retrieve) trigger lazy per-dimension creation via +// ensureReady on first use. +// +// storeID is the VectorStore.ID owning this repository instance. It is +// folded into the base index name so multiple OpenSearch VectorStores +// pointing at the same cluster do not collide: +// - storeID == "" — env-path; no prefix, base index = "weknora". +// - len(storeID) >= 16 — DB-store path; prefix = storeID[:12] +// (48-bit collision space). +// - 1..15 chars — rejected with ErrConfigInvalid. +// +// indexCfg is optional — pass nil to use env var (OPENSEARCH_INDEX) or +// default ("weknora") values. +// +// Returns a typed sentinel error wrapped with %w; callers translate to +// AppError at the engine-factory boundary. +func NewRepository( + ctx context.Context, + client *osapi.Client, + storeID string, + indexCfg *types.IndexConfig, +) (interfaces.RetrieveEngineRepository, error) { + log := logger.GetLogger(ctx) + + if storeID != "" && len(storeID) < 16 { + return nil, fmt.Errorf( + "opensearch: storeID must be empty or >=16 chars, got %d: %w", + len(storeID), ErrConfigInvalid, + ) + } + + base := types.ResolveIndexName(indexCfg, "OPENSEARCH_INDEX", "weknora") + if storeID != "" { + // 12 hex chars → 48-bit collision space (UUID is 32 chars; using + // half gives strong-enough collision avoidance for the realistic + // "two OpenSearch VectorStores on the same cluster" case). + base = fmt.Sprintf("%s_%s", base, storeID[:12]) + } + base, err := sanitizeIndexName(base) + if err != nil { + return nil, fmt.Errorf("opensearch: invalid index base name: %w", err) + } + + icfg, err := buildInternalCfg(indexCfg) + if err != nil { + return nil, fmt.Errorf("opensearch: invalid index config: %w", err) + } + + if err := probeVersion(ctx, client); err != nil { + return nil, err // already wraps ErrVersionUnsupported / ErrTransport + } + if err := probeKNNPlugin(ctx, client); err != nil { + return nil, err // already wraps ErrConfigInvalid / ErrTransport + } + + r := &Repository{ + client: client, + baseIndex: base, + cfg: icfg, + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + log.Infof("[OpenSearch] repository ready (baseIndex=%s, knn_engine=%s, hnsw_m=%d)", + base, icfg.knnEngine, icfg.hnswM) + return r, nil +} + +// ensureReady creates the per-dimension index (alias-backed) the first +// time a given embedding dimension is seen. Concurrent callers for the +// same dim block on the same sync.Once. +// +// Transient vs permanent error handling: +// - PERMANENT failures (ErrConfigInvalid, ErrAuth, ErrVersionUnsupported, +// ErrDimensionMismatch) are persisted in initErr[dim] and re-served to +// all future callers without retry — caller must restart or fix config. +// - TRANSIENT failures (ErrTransport, ErrCircuitBreaker) are NOT +// persisted; the sync.Once is reset for that dim so the next caller +// can retry. This prevents a single cluster blip from permanently +// locking out a dim. +// +// Caller MUST pass a real ctx; nil is rejected. dim must be in (0, 16000] +// (OpenSearch knn_vector hard limit). +// +// CRITICAL INVARIANT: initErr[dim] = err is written INSIDE the once.Do +// closure. Moving it outside opens a TOCTOU where a concurrent caller +// reads zero before the first caller persists. +func (r *Repository) ensureReady(ctx context.Context, dim int) error { + if ctx == nil { + return fmt.Errorf("opensearch: ensureReady requires non-nil ctx") + } + if dim <= 0 || dim > 16000 { + return fmt.Errorf("opensearch: dim %d out of range (1..16000): %w", + dim, ErrDimensionMismatch) + } + + r.onceMu.Lock() + once, ok := r.once[dim] + if !ok { + once = &sync.Once{} + r.once[dim] = once + } + r.onceMu.Unlock() + + once.Do(func() { + err := r.createIndexAndAlias(ctx, dim) + if err != nil && isTransientErr(err) { + // Do NOT persist transient errors. Reset the sync.Once so + // the next caller retries (requires once map mutation). + r.onceMu.Lock() + delete(r.once, dim) + r.onceMu.Unlock() + // Fall through — caller still sees this attempt's err. + } + r.initMu.Lock() + if err == nil || !isTransientErr(err) { + r.initErr[dim] = err // nil on success, persist permanent failures + } + r.initMu.Unlock() + }) + + r.initMu.Lock() + err := r.initErr[dim] + r.initMu.Unlock() + return err +} + +// indexAlias returns the alias name for a given dimension. All reads / +// writes target the alias; the alias points at the actual _v1 +// index, enabling future rolling-reindex swap workflows (the swap path +// itself is deferred to a follow-up PR; see stubs.go swapToVersion). +func (r *Repository) indexAlias(dim int) string { + return fmt.Sprintf("%s_%d", r.baseIndex, dim) +} + +// keywordsIndex returns the name of the dim-less keyword-only index used +// by the no-embedding save path (the service layer dispatches there when +// the knowledge base has vector indexing disabled). The mapping is the +// same as the per-dim index minus the knn_vector field. +func (r *Repository) keywordsIndex() string { + return r.baseIndex + "_keywords" +} + +// EngineType returns the engine constant for OpenSearch. Used by the +// fan-out normalizer to route to the [0, 1] passthrough group. +func (r *Repository) EngineType() types.RetrieverEngineType { + return types.OpenSearchRetrieverEngineType +} + +// Support reports the retrieval modes this driver implements. OpenSearch +// k-NN supports both ANN (vector) and BM25 (keyword) within a single +// document; the keyword-only index keeps BM25 functional for callers +// that omit the embedding map. +func (r *Repository) Support() []types.RetrieverType { + return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType} +} + +// probeVersion sends GET / and validates the cluster is OpenSearch in +// a supported version range: +// - Reject: ES (any), OS 1.x, OS 2.0~2.3 (Lucene HNSW preview). +// - Warn-but-accept: OS 2.4~2.10 (Lucene HNSW GA, pre-LTS). +// - Clean-accept: OS 2.11+, OS 3.x (primary tested: 3.3.2). +func probeVersion(ctx context.Context, client *osapi.Client) error { + resp, err := client.Info(ctx, nil) + if err != nil { + return fmt.Errorf("opensearch: cluster info: %w", wrapTransport(err)) + } + distribution := resp.Version.Distribution + number := resp.Version.Number + + if distribution != "opensearch" { + return fmt.Errorf("opensearch: unsupported distribution %q: %w", + distribution, ErrVersionUnsupported) + } + maj, min := parseMajorMinor(number) + switch { + case maj == 1: + return fmt.Errorf("opensearch: 1.x EOL: %w", ErrVersionUnsupported) + case maj == 2 && min >= 0 && min <= 3: + return fmt.Errorf("opensearch: %s lacks Lucene HNSW GA (need 2.4+): %w", + number, ErrVersionUnsupported) + case maj == 2 && min >= 4 && min <= 10: + logger.GetLogger(ctx).Warnf( + "[OpenSearch] using pre-2.11 cluster %s; recommend 2.11+ LTS", number) + return nil + case maj == 2 || maj == 3: + return nil + default: + return fmt.Errorf("opensearch: unsupported version %s: %w", + number, ErrVersionUnsupported) + } +} + +// parseMajorMinor extracts (major, minor) from a semver string such as +// "3.3.2", "2.10.0-SNAPSHOT", "2.10". Returns (0, 0) for unparseable +// input. Robust to pre-release suffixes (strips after '-') and missing +// patch component (e.g. "2.10"). +func parseMajorMinor(num string) (major, minor int) { + base := strings.SplitN(num, "-", 2)[0] + parts := strings.Split(base, ".") + if len(parts) < 2 { + return 0, 0 + } + m1, err1 := strconv.Atoi(parts[0]) + m2, err2 := strconv.Atoi(parts[1]) + if err1 != nil || err2 != nil { + return 0, 0 + } + return m1, m2 +} + +// probeKNNPlugin verifies the OpenSearch cluster has the opensearch-knn +// plugin installed on EVERY node. Without it on at least one node, +// knn_vector queries that route a shard to that node fail with opaque +// shard-failure errors — we surface this as a clear "plugin missing on +// N nodes" message at registration. +// +// Implementation: _cat/plugins returns one row per (node, plugin) pair. +// We group by node name and verify every distinct node has the +// opensearch-knn component. +func probeKNNPlugin(ctx context.Context, client *osapi.Client) error { + // CatPluginsReq's Params struct has no Format field — the SDK + // negotiates JSON via Accept header and returns a typed + // CatPluginsResp with .Plugins []CatPluginResp already parsed. + resp, err := client.Cat.Plugins(ctx, &osapi.CatPluginsReq{}) + if err != nil { + return fmt.Errorf("opensearch: cat plugins: %w", wrapTransport(err)) + } + + // Group by node, verify every distinct node has opensearch-knn. + nodes := make(map[string]bool) // nodeName -> hasKNN + for _, p := range resp.Plugins { + if p.Name == "" { + continue + } + if _, seen := nodes[p.Name]; !seen { + nodes[p.Name] = false + } + if p.Component == "opensearch-knn" { + nodes[p.Name] = true + } + } + if len(nodes) == 0 { + return fmt.Errorf("opensearch: _cat/plugins returned no rows: %w", ErrConfigInvalid) + } + var missing []string + for node, hasKNN := range nodes { + if !hasKNN { + missing = append(missing, node) + } + } + if len(missing) > 0 { + return fmt.Errorf( + "opensearch: opensearch-knn plugin missing on %d/%d nodes (%v): %w", + len(missing), len(nodes), missing, ErrConfigInvalid, + ) + } + return nil +} + +// wrapTransport classifies a raw transport error into one of the +// driver's sentinel errors based on HTTP status ONLY. The cluster-side +// error message (err.Error()) is intentionally NOT included in the +// wrapped public error — it may contain internal index names, shard +// IDs, node hostnames, or document content snippets. The full SDK +// error is routed to log.Debug for operator forensics. +// +// Classification: +// - 401 / 403 → ErrAuth +// - 404 → caller decides (use isNotFound separately for index ops) +// - 429 + knn_circuit_breaker_exception → ErrCircuitBreaker +// - 5xx / network / timeout → ErrTransport +// +// This is the ONE place in the package that maps wire errors to +// sentinels; downstream functions just propagate. +func wrapTransport(err error) error { + if err == nil { + return nil + } + // Route the verbose SDK message to debug log (operator-visible, not + // user-visible). Background ctx is intentional — wrapTransport may + // be invoked from any caller including the constructor. + logger.GetLogger(context.Background()).Debugf("[OpenSearch] transport err: %v", err) + + var se *opensearch.StructError + if errors.As(err, &se) { + switch se.Status { + case http.StatusUnauthorized, http.StatusForbidden: + return fmt.Errorf("authentication failed: %w", ErrAuth) + case http.StatusTooManyRequests: + if se.Err.Type == "knn_circuit_breaker_exception" { + return fmt.Errorf("circuit breaker open: %w", ErrCircuitBreaker) + } + } + } + return fmt.Errorf("transport error: %w", ErrTransport) +} + +// isNotFound returns true if err carries an HTTP 404. Used by index / +// search code paths that want to distinguish "missing alias" from +// "transport problem". +func isNotFound(err error) bool { + var se *opensearch.StructError + return errors.As(err, &se) && se.Status == http.StatusNotFound +} + +// isAlreadyExistsError returns true if err is a 400 with OpenSearch's +// resource_already_exists_exception type. Used by createIndexAndAlias +// to handle the cross-process race where two replicas try to create +// the same per-dim index simultaneously. +func isAlreadyExistsError(err error) bool { + if err == nil { + return false + } + var se *opensearch.StructError + if !errors.As(err, &se) { + return false + } + return se.Status == http.StatusBadRequest && + se.Err.Type == "resource_already_exists_exception" +} + +// sanitizeRe enforces the OpenSearch index-name contract: +// - lowercase ASCII letters, digits, underscore, hyphen only +// - must start with [a-z0-9] +// - length 1..255 +var sanitizeRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,254}$`) + +// sanitizeIndexName rejects names that violate the OpenSearch index-name +// rules. Any non-conforming input returns ErrConfigInvalid — the driver +// does NOT silently rewrite invalid input so operators get a clear +// error at registration. +func sanitizeIndexName(name string) (string, error) { + if name == "" { + return "", fmt.Errorf("empty index name: %w", ErrConfigInvalid) + } + // Explicit reject of OpenSearch-reserved wildcards / separators / + // control characters. Some of these would already be caught by the + // regexp below, but a dedicated check keeps the error message + // specific. + if strings.ContainsAny(name, "*?,\n\r\t/\\") { + return "", fmt.Errorf("invalid char in %q: %w", name, ErrConfigInvalid) + } + if !sanitizeRe.MatchString(name) { + return "", fmt.Errorf("name %q must match %s: %w", + name, sanitizeRe.String(), ErrConfigInvalid) + } + return name, nil +} + +// drainAndClose closes the response body after draining unread bytes — +// required for HTTP keep-alive connection reuse. opensearch-go does NOT +// drain the body for us; failing to drain on every response will starve +// the per-host connection pool under load. +func drainAndClose(body io.ReadCloser) { + if body == nil { + return + } + _, _ = io.Copy(io.Discard, body) + _ = body.Close() +} + +// limitedDecode wraps json.NewDecoder with an io.LimitReader so a +// pathological or malicious cluster response cannot exhaust process +// memory. Callers pass the documented per-endpoint cap (e.g. 64MB for +// bulk, 16MB for search, 1MB for plugin probe). +func limitedDecode(body io.Reader, maxBytes int64, v any) error { + return json.NewDecoder(io.LimitReader(body, maxBytes)).Decode(v) +} diff --git a/internal/application/repository/retriever/opensearch/repository_test.go b/internal/application/repository/retriever/opensearch/repository_test.go new file mode 100644 index 00000000..418f77c6 --- /dev/null +++ b/internal/application/repository/retriever/opensearch/repository_test.go @@ -0,0 +1,1002 @@ +package opensearch + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/opensearch-project/opensearch-go/v4" + osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// ============================================================================ +// Test helpers +// +// newTestClient builds an *osapi.Client pointing at an httptest URL. No TLS, +// no auth — the test server is plain http:// on localhost. This helper lives +// in *_test.go so it can never bleed into production code (build tag). +// ============================================================================ + +func newTestClient(t *testing.T, url string) *osapi.Client { + t.Helper() + c, err := osapi.NewClient(osapi.Config{ + Client: opensearch.Config{ + Addresses: []string{url}, + }, + }) + if err != nil { + t.Fatalf("newTestClient: %v", err) + } + return c +} + +// newTestRepo builds a Repository directly (bypassing NewRepository's probe +// calls) for unit tests that exercise post-construction behavior. The +// caller supplies the http handler that simulates the cluster. +func newTestRepo(t *testing.T, handler http.HandlerFunc) (*Repository, *httptest.Server) { + t.Helper() + ts := httptest.NewServer(handler) + client := newTestClient(t, ts.URL) + repo := &Repository{ + client: client, + baseIndex: "weknora_test", + cfg: internalCfg{ + shards: 1, replicas: 0, + knnEngine: "lucene", + hnswM: 16, + hnswEFConstruction: 100, + efSearch: 100, + }, + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + return repo, ts +} + +// ============================================================================ +// Interface satisfaction (compile-time check — duplicates the var _ assertion +// in repository.go but documents the intent explicitly in tests). +// ============================================================================ + +func TestRepository_ImplementsRetrieveEngineRepository(t *testing.T) { + t.Parallel() + var _ interfaces.RetrieveEngineRepository = (*Repository)(nil) +} + +func TestRepository_EngineType_ReturnsOpenSearch(t *testing.T) { + t.Parallel() + r := &Repository{} + if got := r.EngineType(); got != types.OpenSearchRetrieverEngineType { + t.Errorf("EngineType: want OpenSearch, got %v", got) + } +} + +func TestRepository_Support_KeywordsAndVector(t *testing.T) { + t.Parallel() + r := &Repository{} + got := r.Support() + want := map[types.RetrieverType]bool{ + types.KeywordsRetrieverType: true, + types.VectorRetrieverType: true, + } + if len(got) != len(want) { + t.Fatalf("Support: want %d types, got %d (%v)", len(want), len(got), got) + } + for _, rt := range got { + if !want[rt] { + t.Errorf("Support returned unexpected %v", rt) + } + } +} + +// ============================================================================ +// Sentinel errors — errors.Is chain compatibility +// ============================================================================ + +func TestSentinelErrors_AreErrorsIsCompatible(t *testing.T) { + t.Parallel() + cases := []struct { + name string + sentinel error + }{ + {"ErrIndexNotFound", ErrIndexNotFound}, + {"ErrDimensionMismatch", ErrDimensionMismatch}, + {"ErrAuth", ErrAuth}, + {"ErrTransport", ErrTransport}, + {"ErrVersionUnsupported", ErrVersionUnsupported}, + {"ErrConfigInvalid", ErrConfigInvalid}, + {"ErrFeatureNotEnabled", ErrFeatureNotEnabled}, + {"ErrBatchTooLarge", ErrBatchTooLarge}, + {"ErrCircuitBreaker", ErrCircuitBreaker}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + wrapped := fmt.Errorf("wrap: %w", tc.sentinel) + if !errors.Is(wrapped, tc.sentinel) { + t.Errorf("errors.Is(%s wrapped) returned false", tc.name) + } + }) + } +} + +func TestIsTransientErr(t *testing.T) { + t.Parallel() + cases := []struct { + err error + want bool + }{ + {ErrTransport, true}, + {ErrCircuitBreaker, true}, + {fmt.Errorf("wrap: %w", ErrTransport), true}, + {ErrAuth, false}, + {ErrConfigInvalid, false}, + {ErrDimensionMismatch, false}, + {nil, false}, + } + for _, tc := range cases { + got := isTransientErr(tc.err) + if got != tc.want { + t.Errorf("isTransientErr(%v): want %v, got %v", tc.err, tc.want, got) + } + } +} + +// ============================================================================ +// sanitizeIndexName — strict OS-compatible name spec +// ============================================================================ + +func TestSanitizeIndexName_AcceptsValidNames(t *testing.T) { + t.Parallel() + cases := []string{ + "weknora", + "weknora_abc123def456_768", + "a", + "1abc", + "foo-bar_baz", + } + for _, name := range cases { + got, err := sanitizeIndexName(name) + if err != nil { + t.Errorf("%q: want OK, got %v", name, err) + } + if got != name { + t.Errorf("%q: must be returned unchanged, got %q", name, got) + } + } +} + +func TestSanitizeIndexName_RejectsInvalid(t *testing.T) { + t.Parallel() + cases := []struct { + name string + reason string + }{ + {"", "empty"}, + {"Foo", "uppercase"}, + {"foo*", "wildcard"}, + {"foo?bar", "wildcard"}, + {"foo,bar", "comma"}, + {"foo\nbar", "newline"}, + {"foo\rbar", "carriage return"}, + {"foo\tbar", "tab"}, + {"../foo", "path traversal"}, + {"/foo", "leading slash"}, + {"foo/bar", "embedded slash"}, + {"_foo", "leading underscore"}, + {"-foo", "leading hyphen"}, + {"+foo", "leading plus"}, + {".foo", "leading dot"}, + {"foo.bar", "embedded dot"}, // regex rejects '.' + {strings.Repeat("a", 256), "too long"}, + } + for _, tc := range cases { + t.Run(tc.reason, func(t *testing.T) { + _, err := sanitizeIndexName(tc.name) + if !errors.Is(err, ErrConfigInvalid) { + t.Errorf("%q (%s): want ErrConfigInvalid, got %v", tc.name, tc.reason, err) + } + }) + } +} + +// ============================================================================ +// parseMajorMinor — robust semver parsing +// ============================================================================ + +func TestParseMajorMinor(t *testing.T) { + t.Parallel() + cases := []struct { + in string + wantMaj int + wantMinor int + }{ + {"3.3.2", 3, 3}, + {"2.10.0", 2, 10}, + {"2.10", 2, 10}, // missing patch — must still parse + {"3.0.0-rc1", 3, 0}, + {"2.10.0-SNAPSHOT", 2, 10}, + {"1.3.18", 1, 3}, + {"abc", 0, 0}, // unparseable + {"3", 0, 0}, // missing minor + {"", 0, 0}, + } + for _, tc := range cases { + t.Run(tc.in, func(t *testing.T) { + maj, min := parseMajorMinor(tc.in) + if maj != tc.wantMaj || min != tc.wantMinor { + t.Errorf("parseMajorMinor(%q): want (%d, %d), got (%d, %d)", + tc.in, tc.wantMaj, tc.wantMinor, maj, min) + } + }) + } +} + +// ============================================================================ +// buildIndexMapping — pure func, JSON shape pin +// ============================================================================ + +func TestBuildIndexMapping_LuceneEngine_768Dim(t *testing.T) { + t.Parallel() + cfg := internalCfg{ + shards: 4, replicas: 1, knnEngine: "lucene", + hnswM: 16, hnswEFConstruction: 100, efSearch: 100, + } + body, err := buildIndexMapping(cfg, 768) + if err != nil { + t.Fatalf("buildIndexMapping: %v", err) + } + var parsed map[string]any + if err := json.Unmarshal(body, &parsed); err != nil { + t.Fatalf("invalid JSON: %v", err) + } + settings := parsed["settings"].(map[string]any)["index"].(map[string]any) + if settings["knn"] != true { + t.Errorf("knn should be true, got %v", settings["knn"]) + } + if settings["number_of_shards"].(float64) != 4 { + t.Errorf("number_of_shards: want 4, got %v", settings["number_of_shards"]) + } + props := parsed["mappings"].(map[string]any)["properties"].(map[string]any) + + // match_type must NOT be in the mapping — derived from RetrieverType at parse time. + if _, ok := props["match_type"]; ok { + t.Error("match_type must NOT be in mapping (derived from RetrieverType)") + } + // source_type must be `integer`, not `keyword`. + if st := props["source_type"].(map[string]any); st["type"] != "integer" { + t.Errorf("source_type: want type=integer, got %v", st["type"]) + } + // embedding field structural check. + emb := props["embedding"].(map[string]any) + if emb["type"] != "knn_vector" { + t.Errorf("embedding.type: want knn_vector, got %v", emb["type"]) + } + if emb["dimension"].(float64) != 768 { + t.Errorf("embedding.dimension: want 768, got %v", emb["dimension"]) + } + method := emb["method"].(map[string]any) + if method["space_type"] != "cosinesimil" || method["engine"] != "lucene" { + t.Errorf("method: space_type/engine mismatch: %v", method) + } + params := method["parameters"].(map[string]any) + if params["m"].(float64) != 16 || params["ef_construction"].(float64) != 100 { + t.Errorf("HNSW params mismatch: %v", params) + } + + // All *_id fields must be keyword. + for _, f := range []string{"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id", "source_id"} { + if props[f].(map[string]any)["type"] != "keyword" { + t.Errorf("%s: want keyword, got %v", f, props[f]) + } + } + + // Boolean flags from the IndexInfo / VectorEmbedding shape. + for _, f := range []string{"is_enabled", "is_recommended"} { + fp, ok := props[f].(map[string]any) + if !ok { + t.Errorf("%s: missing from mapping", f) + continue + } + if fp["type"] != "boolean" { + t.Errorf("%s: want boolean, got %v", f, fp["type"]) + } + } +} + +func TestBuildIndexMapping_FaissEngine_CustomParams(t *testing.T) { + t.Parallel() + cfg := internalCfg{ + shards: 8, replicas: 2, knnEngine: "faiss", + hnswM: 32, hnswEFConstruction: 512, efSearch: 200, + } + body, err := buildIndexMapping(cfg, 1536) + if err != nil { + t.Fatalf("buildIndexMapping: %v", err) + } + var parsed map[string]any + _ = json.Unmarshal(body, &parsed) + emb := parsed["mappings"].(map[string]any)["properties"].(map[string]any)["embedding"].(map[string]any) + method := emb["method"].(map[string]any) + if method["engine"] != "faiss" { + t.Errorf("engine: want faiss, got %v", method["engine"]) + } + if emb["dimension"].(float64) != 1536 { + t.Errorf("dimension: want 1536, got %v", emb["dimension"]) + } +} + +func TestBuildKeywordsMapping_OmitsEmbeddingField(t *testing.T) { + t.Parallel() + cfg := internalCfg{shards: 1, replicas: 0} + body, err := buildKeywordsMapping(cfg) + if err != nil { + t.Fatalf("buildKeywordsMapping: %v", err) + } + var parsed map[string]any + _ = json.Unmarshal(body, &parsed) + props := parsed["mappings"].(map[string]any)["properties"].(map[string]any) + if _, ok := props["embedding"]; ok { + t.Error("keywords mapping must NOT include embedding field") + } + if _, ok := props["content"]; !ok { + t.Error("keywords mapping must include content field for BM25") + } + // Boolean flags from the IndexInfo / VectorEmbedding shape. + for _, f := range []string{"is_enabled", "is_recommended"} { + fp, ok := props[f].(map[string]any) + if !ok { + t.Errorf("%s: missing from keywords mapping", f) + continue + } + if fp["type"] != "boolean" { + t.Errorf("%s: want boolean, got %v", f, fp["type"]) + } + } +} + +// ============================================================================ +// retrieveFilters — typed filter struct closes JSON injection surface +// ============================================================================ + + +// ============================================================================ +// probeVersion — supported-version acceptance/rejection matrix +// ============================================================================ + +func versionHandler(distribution, number string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"version":{"distribution":%q,"number":%q}}`, distribution, number) + } +} + +func TestProbeVersion_AcceptsOpenSearch3x(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(versionHandler("opensearch", "3.3.2")) + defer ts.Close() + if err := probeVersion(context.Background(), newTestClient(t, ts.URL)); err != nil { + t.Errorf("OS 3.3.2: want nil, got %v", err) + } +} + +func TestProbeVersion_AcceptsOpenSearch211(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(versionHandler("opensearch", "2.11.0")) + defer ts.Close() + if err := probeVersion(context.Background(), newTestClient(t, ts.URL)); err != nil { + t.Errorf("OS 2.11: want nil, got %v", err) + } +} + +func TestProbeVersion_WarnsButAcceptsOS25(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(versionHandler("opensearch", "2.5.0")) + defer ts.Close() + if err := probeVersion(context.Background(), newTestClient(t, ts.URL)); err != nil { + t.Errorf("OS 2.5 (warn-but-accept): want nil, got %v", err) + } +} + +func TestProbeVersion_RejectsOpenSearch1x(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(versionHandler("opensearch", "1.3.18")) + defer ts.Close() + err := probeVersion(context.Background(), newTestClient(t, ts.URL)) + if !errors.Is(err, ErrVersionUnsupported) { + t.Errorf("OS 1.x: want ErrVersionUnsupported, got %v", err) + } +} + +func TestProbeVersion_RejectsOpenSearch22(t *testing.T) { + t.Parallel() + // OS 2.0~2.3 are pre-Lucene-HNSW-GA. + ts := httptest.NewServer(versionHandler("opensearch", "2.2.0")) + defer ts.Close() + err := probeVersion(context.Background(), newTestClient(t, ts.URL)) + if !errors.Is(err, ErrVersionUnsupported) { + t.Errorf("OS 2.2: want ErrVersionUnsupported, got %v", err) + } +} + +func TestProbeVersion_RejectsElasticsearch(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(versionHandler("elasticsearch", "8.10.4")) + defer ts.Close() + err := probeVersion(context.Background(), newTestClient(t, ts.URL)) + if !errors.Is(err, ErrVersionUnsupported) { + t.Errorf("ES 8.10: want ErrVersionUnsupported, got %v", err) + } +} + +func TestProbeVersion_HandlesPreReleaseSuffix(t *testing.T) { + t.Parallel() + // 3.0.0-rc1 should be accepted (rc of a supported major). + ts := httptest.NewServer(versionHandler("opensearch", "3.0.0-rc1")) + defer ts.Close() + if err := probeVersion(context.Background(), newTestClient(t, ts.URL)); err != nil { + t.Errorf("OS 3.0.0-rc1: want nil, got %v", err) + } +} + +// ============================================================================ +// probeKNNPlugin — multi-node coverage +// ============================================================================ + +func pluginsHandler(rows []osapi.CatPluginResp) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(rows) + } +} + +func TestProbeKNNPlugin_AllNodesPresent(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(pluginsHandler([]osapi.CatPluginResp{ + {Name: "node-1", Component: "opensearch-knn"}, + {Name: "node-1", Component: "opensearch-sql"}, + {Name: "node-2", Component: "opensearch-knn"}, + {Name: "node-2", Component: "opensearch-sql"}, + })) + defer ts.Close() + if err := probeKNNPlugin(context.Background(), newTestClient(t, ts.URL)); err != nil { + t.Errorf("all nodes have plugin: want nil, got %v", err) + } +} + +func TestProbeKNNPlugin_OneNodeMissing(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(pluginsHandler([]osapi.CatPluginResp{ + {Name: "node-1", Component: "opensearch-knn"}, + {Name: "node-2", Component: "opensearch-sql"}, // missing knn + {Name: "node-3", Component: "opensearch-knn"}, + })) + defer ts.Close() + err := probeKNNPlugin(context.Background(), newTestClient(t, ts.URL)) + if !errors.Is(err, ErrConfigInvalid) { + t.Errorf("missing on one node: want ErrConfigInvalid, got %v", err) + } + if !strings.Contains(err.Error(), "node-2") { + t.Errorf("error should name the missing node: %v", err) + } +} + +func TestProbeKNNPlugin_EmptyResponse(t *testing.T) { + t.Parallel() + ts := httptest.NewServer(pluginsHandler([]osapi.CatPluginResp{})) + defer ts.Close() + err := probeKNNPlugin(context.Background(), newTestClient(t, ts.URL)) + if !errors.Is(err, ErrConfigInvalid) { + t.Errorf("empty response: want ErrConfigInvalid, got %v", err) + } +} + +// ============================================================================ +// ensureReady — concurrency + transient vs permanent error caching +// ============================================================================ + +func TestEnsureReady_ZeroDim_Rejected(t *testing.T) { + t.Parallel() + r := &Repository{ + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + err := r.ensureReady(context.Background(), 0) + if !errors.Is(err, ErrDimensionMismatch) { + t.Errorf("dim=0: want ErrDimensionMismatch, got %v", err) + } +} + +func TestEnsureReady_DimAboveLimit_Rejected(t *testing.T) { + t.Parallel() + r := &Repository{ + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + err := r.ensureReady(context.Background(), 16001) + if !errors.Is(err, ErrDimensionMismatch) { + t.Errorf("dim>16000: want ErrDimensionMismatch, got %v", err) + } +} + +func TestEnsureReady_NilCtx_Rejected(t *testing.T) { + t.Parallel() + r := &Repository{ + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + err := r.ensureReady(nil, 768) //nolint:staticcheck — explicit nil ctx test + if err == nil || !strings.Contains(err.Error(), "non-nil ctx") { + t.Errorf("nil ctx: want error about non-nil ctx, got %v", err) + } +} + +// indexLifecycleHandler simulates a cluster where: +// - HEAD /_alias/ returns 404 (alias does not exist). +// - PUT / returns 200 (create succeeds). +// - POST /_aliases-style PUT alias returns 200. +// - All other paths return 200 with empty JSON. +// +// Tracks PUT-index invocations via the put counter. +type indexLifecycleHandler struct { + puts atomic.Int32 +} + +func (h *indexLifecycleHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Distinguish index-create PUT (path ends with _v1) from alias-put + // PUT (path contains /_alias/). Both PUTs hit URLs containing _v1 + // because the alias-put path is //_alias/. + switch { + case r.Method == http.MethodHead: + // All HEAD requests (alias exists checks) return 404 so + // createIndexAndAlias proceeds to PUT. + w.WriteHeader(http.StatusNotFound) + case r.Method == http.MethodPut && strings.Contains(r.URL.Path, "/_alias/"): + // Alias PUT — acknowledge, do NOT count. + _, _ = w.Write([]byte(`{"acknowledged": true}`)) + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "_v1"): + // Index PUT — count it. Path is exactly /__v1. + h.puts.Add(1) + _, _ = w.Write([]byte(`{"acknowledged": true}`)) + case r.Method == http.MethodPost && r.URL.Path == "/_aliases": + _, _ = w.Write([]byte(`{"acknowledged": true}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{}`)) + } +} + +func TestEnsureReady_ConcurrentCallers_SingleCreate(t *testing.T) { + t.Parallel() + h := &indexLifecycleHandler{} + ts := httptest.NewServer(h) + defer ts.Close() + + repo := &Repository{ + client: newTestClient(t, ts.URL), + baseIndex: "weknora_test", + cfg: internalCfg{shards: 1, replicas: 0, knnEngine: "lucene", hnswM: 16, hnswEFConstruction: 100, efSearch: 100}, + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + + var wg sync.WaitGroup + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _ = repo.ensureReady(context.Background(), 768) + }() + } + wg.Wait() + + if got := h.puts.Load(); got != 1 { + t.Errorf("100 concurrent ensureReady(768): want 1 PUT, got %d", got) + } +} + +func TestEnsureReady_PerDimensionIsolation(t *testing.T) { + t.Parallel() + h := &indexLifecycleHandler{} + ts := httptest.NewServer(h) + defer ts.Close() + + repo := &Repository{ + client: newTestClient(t, ts.URL), + baseIndex: "weknora_test", + cfg: internalCfg{shards: 1, replicas: 0, knnEngine: "lucene", hnswM: 16, hnswEFConstruction: 100, efSearch: 100}, + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + + for _, dim := range []int{768, 1024, 1536} { + if err := repo.ensureReady(context.Background(), dim); err != nil { + t.Errorf("ensureReady(dim=%d): %v", dim, err) + } + } + if got := h.puts.Load(); got != 3 { + t.Errorf("3 distinct dims: want 3 PUTs, got %d", got) + } +} + +// errorHandler returns a configurable status code for index PUTs to +// simulate transient (5xx) vs permanent (400) failures. +type errorHandler struct { + statusForIndexPut int + indexPutsAttempted atomic.Int32 +} + +func (h *errorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodHead: + w.WriteHeader(http.StatusNotFound) + case r.Method == http.MethodPut && strings.Contains(r.URL.Path, "/_alias/"): + // Alias PUT — do not count, just acknowledge (though this path + // only triggers if index create succeeds, which it doesn't in + // the error handler's case). + _, _ = w.Write([]byte(`{"acknowledged":true}`)) + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "_v1"): + h.indexPutsAttempted.Add(1) + w.WriteHeader(h.statusForIndexPut) + // Write a minimal OS error response so wrapTransport can parse it. + errBody := `{"error":{"type":"server_error","reason":"simulated"},"status":` + fmt.Sprintf("%d", h.statusForIndexPut) + `}` + _, _ = w.Write([]byte(errBody)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"acknowledged":true}`)) + } +} + +func TestEnsureReady_TransientError_NotCached(t *testing.T) { + t.Parallel() + h := &errorHandler{statusForIndexPut: http.StatusInternalServerError} + ts := httptest.NewServer(h) + defer ts.Close() + + repo := &Repository{ + client: newTestClient(t, ts.URL), + baseIndex: "weknora_test", + cfg: internalCfg{shards: 1, replicas: 0, knnEngine: "lucene", hnswM: 16, hnswEFConstruction: 100, efSearch: 100}, + once: make(map[int]*sync.Once), + initErr: make(map[int]error), + } + + // First call fails with transient 5xx. + _ = repo.ensureReady(context.Background(), 768) + first := h.indexPutsAttempted.Load() + + // Second call MUST retry — transient errors are not persisted. + _ = repo.ensureReady(context.Background(), 768) + second := h.indexPutsAttempted.Load() + + if second <= first { + t.Errorf("transient error must allow retry: first=%d, second=%d", first, second) + } +} + +// ============================================================================ +// indexAlias / keywordsIndex naming +// ============================================================================ + +func TestIndexAlias(t *testing.T) { + t.Parallel() + r := &Repository{baseIndex: "weknora_abc123def456"} + if got := r.indexAlias(768); got != "weknora_abc123def456_768" { + t.Errorf("indexAlias(768): want weknora_abc123def456_768, got %s", got) + } +} + +func TestKeywordsIndex(t *testing.T) { + t.Parallel() + r := &Repository{baseIndex: "weknora_abc123def456"} + if got := r.keywordsIndex(); got != "weknora_abc123def456_keywords" { + t.Errorf("keywordsIndex: want weknora_abc123def456_keywords, got %s", got) + } +} + +// ============================================================================ +// NewRepository storeID validation +// ============================================================================ + +// minimalCluster handles enough endpoints for NewRepository's probes to +// succeed when we want to test the constructor's pre-flight validation +// (which runs BEFORE the probes). +func minimalCluster(t *testing.T) (*httptest.Server, *osapi.Client) { + t.Helper() + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/": + _, _ = w.Write([]byte(`{"version":{"distribution":"opensearch","number":"3.3.2"}}`)) + case "/_cat/plugins": + _, _ = w.Write([]byte(`[{"name":"node-1","component":"opensearch-knn"}]`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{}`)) + } + })) + return ts, newTestClient(t, ts.URL) +} + +func TestNewRepository_RejectsShortStoreID(t *testing.T) { + t.Parallel() + ts, client := minimalCluster(t) + defer ts.Close() + cases := []string{"a", "abc", "1234567890abcde"} // 1, 3, 15 chars + for _, sid := range cases { + _, err := NewRepository(context.Background(), client, sid, nil) + if !errors.Is(err, ErrConfigInvalid) { + t.Errorf("storeID=%q (len=%d): want ErrConfigInvalid, got %v", sid, len(sid), err) + } + } +} + +func TestNewRepository_AcceptsEmptyStoreID_EnvPath(t *testing.T) { + t.Parallel() + ts, client := minimalCluster(t) + defer ts.Close() + _, err := NewRepository(context.Background(), client, "", nil) + if err != nil { + t.Errorf("empty storeID (env-path): want nil, got %v", err) + } +} + +func TestNewRepository_AcceptsLongStoreID(t *testing.T) { + t.Parallel() + ts, client := minimalCluster(t) + defer ts.Close() + // 32-char UUID-like string (without hyphens). + storeID := "abc123def4567890abcdef0123456789" + _, err := NewRepository(context.Background(), client, storeID, nil) + if err != nil { + t.Errorf("32-char storeID: want nil, got %v", err) + } +} + +// ============================================================================ +// Stub coverage — every stub returns the not-enabled sentinel +// ============================================================================ + +func TestStub_CopyIndices_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + err := r.CopyIndices(context.Background(), "kb1", nil, nil, "kb2", 768, "") + if !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("CopyIndices: want ErrFeatureNotEnabled, got %v", err) + } +} + +func TestStub_BatchUpdateChunkEnabledStatus_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + if err := r.BatchUpdateChunkEnabledStatus(context.Background(), nil); !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("want ErrFeatureNotEnabled, got %v", err) + } +} + +func TestStub_BatchUpdateChunkTagID_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + if err := r.BatchUpdateChunkTagID(context.Background(), nil); !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("want ErrFeatureNotEnabled, got %v", err) + } +} + +func TestStub_EstimateStorageSize_EmptyZero_NonEmptyPositive(t *testing.T) { + t.Parallel() + r := &Repository{} + if got := r.EstimateStorageSize(context.Background(), nil, nil); got != 0 { + t.Errorf("empty list: want 0, got %d", got) + } + infos := []*types.IndexInfo{{ChunkID: "c1"}, {ChunkID: "c2"}} + if got := r.EstimateStorageSize(context.Background(), infos, nil); got <= 0 { + t.Errorf("non-empty list: want >0, got %d", got) + } +} + +func TestStub_SwapToVersion_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + if err := r.swapToVersion(context.Background(), 768, 2); !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("swapToVersion: want ErrFeatureNotEnabled, got %v", err) + } +} + +// ============================================================================ +// Behavioural-method stubs — a follow-up commit replaces each of these +// (Save / BatchSave / Retrieve / DeleteBy*) with the real implementation, +// at which point the corresponding stub-test below disappears. Each stub +// returns ErrFeatureNotEnabled so any accidental invocation at this stage +// surfaces loudly. +// ============================================================================ + +func TestStub_Save_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + err := r.Save(context.Background(), &types.IndexInfo{ChunkID: "c1"}, nil) + if !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("Save: want ErrFeatureNotEnabled, got %v", err) + } +} + +func TestStub_BatchSave_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + err := r.BatchSave(context.Background(), + []*types.IndexInfo{{ChunkID: "c1"}}, nil) + if !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("BatchSave: want ErrFeatureNotEnabled, got %v", err) + } +} + +func TestStub_Retrieve_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + res, err := r.Retrieve(context.Background(), types.RetrieveParams{TopK: 10}) + if !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("Retrieve: want ErrFeatureNotEnabled, got %v", err) + } + if res != nil { + t.Errorf("Retrieve: want nil result, got %v", res) + } +} + +func TestStub_DeleteByChunkIDList_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + err := r.DeleteByChunkIDList(context.Background(), + []string{"c1"}, 768, "") + if !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("DeleteByChunkIDList: want ErrFeatureNotEnabled, got %v", err) + } +} + +func TestStub_DeleteBySourceIDList_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + err := r.DeleteBySourceIDList(context.Background(), + []string{"s1"}, 768, "") + if !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("DeleteBySourceIDList: want ErrFeatureNotEnabled, got %v", err) + } +} + +func TestStub_DeleteByKnowledgeIDList_ReturnsFeatureNotEnabled(t *testing.T) { + t.Parallel() + r := &Repository{} + err := r.DeleteByKnowledgeIDList(context.Background(), + []string{"k1"}, 768, "") + if !errors.Is(err, ErrFeatureNotEnabled) { + t.Errorf("DeleteByKnowledgeIDList: want ErrFeatureNotEnabled, got %v", err) + } +} + +// ============================================================================ +// wrapTransport — sentinel mapping + leak guard +// ============================================================================ + +func TestWrapTransport_NilPassthrough(t *testing.T) { + t.Parallel() + if err := wrapTransport(nil); err != nil { + t.Errorf("nil in: want nil out, got %v", err) + } +} + +func TestWrapTransport_GenericErrorYieldsTransport(t *testing.T) { + t.Parallel() + in := errors.New("network unreachable") + out := wrapTransport(in) + if !errors.Is(out, ErrTransport) { + t.Errorf("generic error: want ErrTransport, got %v", out) + } + // Leak guard: cluster-side message ("network unreachable") must NOT + // be exposed in the wrapped public error. + if strings.Contains(out.Error(), "network unreachable") { + t.Errorf("wrapped error must NOT include raw cluster message: %v", out) + } +} + +func TestWrapTransport_401_YieldsErrAuth(t *testing.T) { + t.Parallel() + se := &opensearch.StructError{Status: 401, Err: opensearch.Err{Type: "security_exception"}} + out := wrapTransport(se) + if !errors.Is(out, ErrAuth) { + t.Errorf("401: want ErrAuth, got %v", out) + } +} + +func TestWrapTransport_403_YieldsErrAuth(t *testing.T) { + t.Parallel() + se := &opensearch.StructError{Status: 403, Err: opensearch.Err{Type: "security_exception"}} + out := wrapTransport(se) + if !errors.Is(out, ErrAuth) { + t.Errorf("403: want ErrAuth, got %v", out) + } +} + +func TestWrapTransport_429CircuitBreaker_YieldsErrCircuitBreaker(t *testing.T) { + t.Parallel() + se := &opensearch.StructError{ + Status: 429, + Err: opensearch.Err{Type: "knn_circuit_breaker_exception"}, + } + out := wrapTransport(se) + if !errors.Is(out, ErrCircuitBreaker) { + t.Errorf("429 + knn_circuit_breaker_exception: want ErrCircuitBreaker, got %v", out) + } +} + +func TestIsNotFound(t *testing.T) { + t.Parallel() + if isNotFound(nil) { + t.Error("nil err: must not be NotFound") + } + if isNotFound(errors.New("generic")) { + t.Error("generic err: must not be NotFound") + } + se := &opensearch.StructError{Status: 404} + if !isNotFound(se) { + t.Error("404 StructError: must be NotFound") + } + se2 := &opensearch.StructError{Status: 500} + if isNotFound(se2) { + t.Error("500 StructError: must not be NotFound") + } +} + +func TestIsAlreadyExistsError(t *testing.T) { + t.Parallel() + if isAlreadyExistsError(nil) { + t.Error("nil err: must not be AlreadyExists") + } + se := &opensearch.StructError{ + Status: 400, + Err: opensearch.Err{Type: "resource_already_exists_exception"}, + } + if !isAlreadyExistsError(se) { + t.Error("400 + resource_already_exists_exception: must be AlreadyExists") + } + se2 := &opensearch.StructError{Status: 400, Err: opensearch.Err{Type: "other"}} + if isAlreadyExistsError(se2) { + t.Error("400 + other type: must not be AlreadyExists") + } +} + +// ============================================================================ +// limitedDecode + drainAndClose helpers +// ============================================================================ + +func TestLimitedDecode_AppliesLimit(t *testing.T) { + t.Parallel() + // 100MB of zeros — limitedDecode with 1KB cap should fail to decode + // (truncated JSON) rather than allocate the whole thing. + huge := bytes.NewReader(make([]byte, 100<<20)) + var out map[string]any + err := limitedDecode(huge, 1024, &out) + if err == nil { + t.Error("limitedDecode must fail on truncated input") + } +} + +func TestDrainAndClose_HandlesNil(t *testing.T) { + t.Parallel() + drainAndClose(nil) // must not panic +} + +func TestDrainAndClose_DrainsAndClosesBody(t *testing.T) { + t.Parallel() + body := io.NopCloser(strings.NewReader("hello")) + drainAndClose(body) + // Second close should not panic (io.NopCloser is idempotent). + drainAndClose(body) +} diff --git a/internal/application/repository/retriever/opensearch/stubs.go b/internal/application/repository/retriever/opensearch/stubs.go new file mode 100644 index 00000000..c60a68f7 --- /dev/null +++ b/internal/application/repository/retriever/opensearch/stubs.go @@ -0,0 +1,136 @@ +package opensearch + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/types" +) + +// This file ships every behavioural method of the OpenSearch driver as a +// stub returning ErrFeatureNotEnabled (or, for EstimateStorageSize, a +// conservative lower-bound). The package is a hollow, interface-compliant +// shell at this commit — every real code path is gated dead code (no +// registry / factory / env path mentions this driver), and any accidental +// invocation surfaces loudly. +// +// Follow-up commits land the real implementations: the read/write methods +// (Save / BatchSave / DeleteBy* / Retrieve) migrate to dedicated files +// (crud.go / retrieve.go + supporting query.go); the async / batch paths +// (CopyIndices, BatchUpdate*) and the real EstimateStorageSize arrive +// alongside the activation switch. + +// Save is replaced by a real bulk-driven single-doc path in a later commit. +func (r *Repository) Save( + _ context.Context, _ *types.IndexInfo, _ map[string]any, +) error { + return ErrFeatureNotEnabled +} + +// BatchSave is replaced by a real dim-aware pre-marshal + per-item-error +// inspection path in a later commit. +func (r *Repository) BatchSave( + _ context.Context, _ []*types.IndexInfo, _ map[string]any, +) error { + return ErrFeatureNotEnabled +} + +// DeleteByChunkIDList is replaced by a capped sync _delete_by_query path +// in a later commit. +func (r *Repository) DeleteByChunkIDList( + _ context.Context, _ []string, _ int, _ string, +) error { + return ErrFeatureNotEnabled +} + +// DeleteBySourceIDList is replaced by a capped sync _delete_by_query path +// in a later commit. +func (r *Repository) DeleteBySourceIDList( + _ context.Context, _ []string, _ int, _ string, +) error { + return ErrFeatureNotEnabled +} + +// DeleteByKnowledgeIDList is replaced by a capped sync _delete_by_query +// path in a later commit. +func (r *Repository) DeleteByKnowledgeIDList( + _ context.Context, _ []string, _ int, _ string, +) error { + return ErrFeatureNotEnabled +} + +// Retrieve is replaced by a dim-resolve + per-dim alias k-NN / BM25 path +// in a later commit. +func (r *Repository) Retrieve( + _ context.Context, _ types.RetrieveParams, +) ([]*types.RetrieveResult, error) { + return nil, ErrFeatureNotEnabled +} + +// CopyIndices: the async _reindex path with task polling for >10K-doc +// batches arrives in a later change. Until then this is unreachable in +// production (no registry registration path activates the OpenSearch +// driver), but the stub fails closed if reached. +func (r *Repository) CopyIndices( + _ context.Context, + _ string, // sourceKnowledgeBaseID + _ map[string]string, // sourceToTargetKBIDMap + _ map[string]string, // sourceToTargetChunkIDMap + _ string, // targetKnowledgeBaseID + _ int, // dimension + _ string, // knowledgeType +) error { + return ErrFeatureNotEnabled +} + +// BatchUpdateChunkEnabledStatus: the _update_by_query path arrives in a +// later change. +func (r *Repository) BatchUpdateChunkEnabledStatus( + _ context.Context, _ map[string]bool, +) error { + return ErrFeatureNotEnabled +} + +// BatchUpdateChunkTagID: the _update_by_query path arrives in a later +// change. +func (r *Repository) BatchUpdateChunkTagID( + _ context.Context, _ map[string]string, +) error { + return ErrFeatureNotEnabled +} + +// EstimateStorageSize: the real implementation that reads cluster `_stats` +// for the per-dim alias arrives in a later change. For now we return a +// conservative lower-bound estimate using the HNSW memory formula so the +// upstream KB-delete guard fails-closed (treats non-empty KBs as "may free +// non-trivial storage, force confirmation") rather than failing open. +// +// Formula: N * (1024 content bytes + 4*dimGuess float + 128 HNSW M=16 overhead) +// dimGuess = 768 (common embedding size; the real implementation reads the +// actual dim from the cluster). +func (r *Repository) EstimateStorageSize( + _ context.Context, + indexInfoList []*types.IndexInfo, + _ map[string]any, +) int64 { + if len(indexInfoList) == 0 { + return 0 + } + const ( + contentBytes = 1024 // average chunk content + embDimGuess = 768 // common embedding size + hnswOverhead = 128 // M=16 → 8*M = 128 bytes/vector + ) + return int64(len(indexInfoList)) * int64(contentBytes+4*embDimGuess+hnswOverhead) +} + +// swapToVersion is a stub for the future rolling-reindex swap path. +// Calling it is illegal at this stage — alias is fixed at "_v1" and only +// a follow-up change ships the swap orchestration. The surface exists so +// the future API contract is reviewable now. +// +// Unexported because it is not part of the public +// RetrieveEngineRepository interface — exposing it would require an +// interface widening in internal/types/interfaces. +func (r *Repository) swapToVersion(_ context.Context, _ int, _ int) error { + return ErrFeatureNotEnabled +} diff --git a/internal/application/repository/retriever/opensearch/transport.go b/internal/application/repository/retriever/opensearch/transport.go new file mode 100644 index 00000000..1e1dc86c --- /dev/null +++ b/internal/application/repository/retriever/opensearch/transport.go @@ -0,0 +1,76 @@ +package opensearch + +import ( + "crypto/tls" + "fmt" + "net/http" + "time" + + "github.com/opensearch-project/opensearch-go/v4" + osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi" + + "github.com/Tencent/WeKnora/internal/types" +) + +// newOpenSearchClient builds a TLS-hardened, pool-tuned *osapi.Client for +// the OpenSearch driver. The caller wires it into the registry from the +// env path (container) and the DB-store path (engine factory); the +// Repository constructor itself receives the pre-built client. While the +// driver is still gated dead code, no code path here is reachable from +// production — the activation switch lands in a later change. +// +// TLS posture: +// - MinVersion: TLS 1.2 (TLS 1.3 negotiated when both ends support). +// - InsecureSkipVerify: opt-in via ConnectionConfig.InsecureSkipVerify. +// Default false. Operators set true ONLY for self-signed dev clusters. +// - CipherSuites: explicit forward-secrecy-only list. TLS 1.2's default +// cipher list includes TLS_RSA_* (no forward secrecy); we drop them. +// TLS 1.3 cipher selection is automatic and safe. +// +// Transport tuning: +// - MaxIdleConnsPerHost: 32 (Go default 2 is too low when callers +// dispatch concurrent queries across multiple knowledge bases) +// - IdleConnTimeout: 90s (typical LB keep-alive) +// - ResponseHeaderTimeout: 30s (per-request safety net) +// - ExpectContinueTimeout: 1s +func newOpenSearchClient(cfg *types.ConnectionConfig) (*osapi.Client, error) { + if cfg == nil || cfg.Addr == "" { + return nil, fmt.Errorf("opensearch: ConnectionConfig.Addr required: %w", ErrConfigInvalid) + } + transport := buildHTTPTransport(cfg.InsecureSkipVerify) + return osapi.NewClient(osapi.Config{ + Client: opensearch.Config{ + Addresses: []string{cfg.Addr}, + Username: cfg.Username, + Password: cfg.Password, + Transport: transport, + }, + }) +} + +// buildHTTPTransport constructs the TLS-hardened, pool-tuned +// *http.Transport used by every OpenSearch client this driver creates. +// Extracted from newOpenSearchClient so unit tests can pin the TLS +// posture directly (the opensearch-go SDK wraps the transport in an +// internal interface, making reflection-based introspection of the +// final client fragile across SDK versions). +func buildHTTPTransport(insecureSkipVerify bool) *http.Transport { + return &http.Transport{ + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + InsecureSkipVerify: insecureSkipVerify, //nolint:gosec — operator opt-in flag + CipherSuites: []uint16{ + tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, + tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, + }, + }, + MaxIdleConnsPerHost: 32, + IdleConnTimeout: 90 * time.Second, + ResponseHeaderTimeout: 30 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + } +} diff --git a/internal/application/repository/retriever/opensearch/transport_test.go b/internal/application/repository/retriever/opensearch/transport_test.go new file mode 100644 index 00000000..173712ac --- /dev/null +++ b/internal/application/repository/retriever/opensearch/transport_test.go @@ -0,0 +1,137 @@ +package opensearch + +import ( + "crypto/tls" + "errors" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// TestNewOpenSearchClient_RejectsEmptyAddr verifies the constructor +// refuses an empty Addr — operators who forget to set OPENSEARCH_ADDR +// get a clear ErrConfigInvalid at registration instead of a cryptic +// transport error later. +func TestNewOpenSearchClient_RejectsEmptyAddr(t *testing.T) { + t.Parallel() + _, err := newOpenSearchClient(&types.ConnectionConfig{Addr: ""}) + if !errors.Is(err, ErrConfigInvalid) { + t.Fatalf("empty addr: want ErrConfigInvalid, got %v", err) + } + _, err = newOpenSearchClient(nil) + if !errors.Is(err, ErrConfigInvalid) { + t.Fatalf("nil cfg: want ErrConfigInvalid, got %v", err) + } +} + +// TestNewOpenSearchClient_Succeeds_OnValidAddr is a smoke test for the +// happy path — a non-empty Addr must produce a non-nil *osapi.Client. +// We don't probe the cluster (no network), just verify the constructor +// returns successfully. +func TestNewOpenSearchClient_Succeeds_OnValidAddr(t *testing.T) { + t.Parallel() + client, err := newOpenSearchClient(&types.ConnectionConfig{ + Addr: "https://opensearch.example.com:9200", + Username: "admin", + Password: "secret", // not a real password — wire-format only + }) + if err != nil { + t.Fatalf("newOpenSearchClient: %v", err) + } + if client == nil { + t.Fatal("client must be non-nil on success") + } +} + +// TestBuildHTTPTransport_DefaultsToSecureTLS pins the default +// InsecureSkipVerify=false. Operators who don't opt in MUST get a +// strict-verify HTTPS client. +func TestBuildHTTPTransport_DefaultsToSecureTLS(t *testing.T) { + t.Parallel() + tr := buildHTTPTransport(false) + if tr.TLSClientConfig == nil { + t.Fatal("TLSClientConfig must be set") + } + if tr.TLSClientConfig.InsecureSkipVerify { + t.Fatal("default InsecureSkipVerify must be false (secure)") + } +} + +// TestBuildHTTPTransport_InsecureSkipVerifyOptIn confirms the flag +// flows through to tls.Config. Self-signed dev clusters can opt in; +// production deployments MUST leave it false. +func TestBuildHTTPTransport_InsecureSkipVerifyOptIn(t *testing.T) { + t.Parallel() + tr := buildHTTPTransport(true) + if tr.TLSClientConfig == nil { + t.Fatal("TLSClientConfig must be set") + } + if !tr.TLSClientConfig.InsecureSkipVerify { + t.Fatal("InsecureSkipVerify=true must propagate to tls.Config") + } +} + +// TestBuildHTTPTransport_TLS12MinVersion pins the TLS 1.2 hard floor. +// TLS 1.3 negotiates automatically when both ends support it; 1.0 / 1.1 +// must be rejected at handshake time. +func TestBuildHTTPTransport_TLS12MinVersion(t *testing.T) { + t.Parallel() + tr := buildHTTPTransport(false) + if tr.TLSClientConfig.MinVersion != tls.VersionTLS12 { + t.Fatalf("MinVersion: want tls.VersionTLS12 (0x%x), got 0x%x", + tls.VersionTLS12, tr.TLSClientConfig.MinVersion) + } +} + +// TestBuildHTTPTransport_CipherSuitesExcludeNonECDHE pins the explicit +// cipher list to forward-secrecy-only ECDHE suites. TLS 1.2's default +// list includes TLS_RSA_* (no forward secrecy); we drop them. TLS 1.3 +// cipher selection is automatic so this only matters for the 1.2 path. +func TestBuildHTTPTransport_CipherSuitesExcludeNonECDHE(t *testing.T) { + t.Parallel() + tr := buildHTTPTransport(false) + cs := tr.TLSClientConfig.CipherSuites + if len(cs) == 0 { + t.Fatal("CipherSuites must be explicitly pinned (got empty)") + } + allowed := map[uint16]bool{ + tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true, + tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: true, + tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true, + tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: true, + tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: true, + tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: true, + } + for _, suite := range cs { + if !allowed[suite] { + t.Fatalf("cipher suite 0x%x is not in the forward-secrecy whitelist", suite) + } + } + // Spot-check that a known-weak non-ECDHE cipher is NOT in the list. + for _, suite := range cs { + if suite == tls.TLS_RSA_WITH_AES_128_GCM_SHA256 { + t.Fatal("TLS_RSA_WITH_AES_128_GCM_SHA256 must NOT be present (no forward secrecy)") + } + } +} + +// TestBuildHTTPTransport_PoolTuning pins the connection-pool settings. +// The Go default MaxIdleConnsPerHost is 2, which is too low for concurrent +// queries across multiple knowledge bases. +func TestBuildHTTPTransport_PoolTuning(t *testing.T) { + t.Parallel() + tr := buildHTTPTransport(false) + if tr.MaxIdleConnsPerHost < 32 { + t.Errorf("MaxIdleConnsPerHost: want >=32 for concurrent KB queries, got %d", + tr.MaxIdleConnsPerHost) + } + if tr.IdleConnTimeout == 0 { + t.Error("IdleConnTimeout must be set (Go default of 0 leaks idle conns)") + } + if tr.ResponseHeaderTimeout == 0 { + t.Error("ResponseHeaderTimeout must be set (Go default of 0 means unbounded)") + } + if tr.ExpectContinueTimeout == 0 { + t.Error("ExpectContinueTimeout must be set (avoids 100-continue stalls)") + } +} diff --git a/internal/application/service/knowledgebase_search_fanout_test.go b/internal/application/service/knowledgebase_search_fanout_test.go index 64adc4a1..d2130dd2 100644 --- a/internal/application/service/knowledgebase_search_fanout_test.go +++ b/internal/application/service/knowledgebase_search_fanout_test.go @@ -545,9 +545,18 @@ func TestRetrieveFromStores_MultiGroupParallel_Concat(t *testing.T) { func TestRetrieveFromStores_MixedEngine_Normalizes(t *testing.T) { t.Parallel() - // ES returns raw cosine in [-1, 1]. Without normalization, mixing - // with PG (already [0, 1]) ranks ES too high. The normalizer rescales - // ES scores to [0, 1] before fusion. + // EngineAwareNormalizer policy in effect: + // - ES / ElasticFaiss / OpenSearch / Weaviate / Postgres / SQLite / + // Qdrant / TencentVectorDB / Doris surface non-negative cosine in + // [0, 1] when the value reaches the normalizer (Lucene script_score + // non-negative invariant for ES; k-NN plugin SpaceType.COSINESIMIL + // pre-translation for OpenSearch; engine-internal conversions for + // the rest) → passthrough via clamp01. + // - Milvus is the only engine in this codebase that still surfaces + // the raw signed cosine in [-1, 1] → cosine-shift via (score + 1) / 2. + // + // First sub-case below pins the ES passthrough; the Milvus sub-case + // pins the cosine-shift path so the [-1, 1] branch stays under coverage. fakeES := &fakeRetrieveEngineService{ engineType: types.ElasticsearchRetrieverEngineType, support: []types.RetrieverType{types.VectorRetrieverType}, @@ -574,15 +583,17 @@ func TestRetrieveFromStores_MixedEngine_Normalizes(t *testing.T) { scoresByChunk[hit.ChunkID] = hit.Score } } - // ES 1.0 → (1+1)/2 = 1.0 (top), PG 0.9 → 0.9 unchanged. + // ES 1.0 → clamp01(1.0) = 1.0 (passthrough); PG 0.9 → 0.9 unchanged. assert.InDelta(t, 1.0, scoresByChunk["es1"], 1e-9) assert.InDelta(t, 0.9, scoresByChunk["pg1"], 1e-9) - // Now check that an ES cosine of -0.4 normalizes to 0.3 (below PG 0.9). + // ES passthrough on a production-possible mid-range cosine: 0.3 → 0.3 + // (below PG 0.8, so PG out-ranks ES — the property the old cosine-shift + // test asserted, restated for the passthrough policy). fakeES2 := &fakeRetrieveEngineService{ engineType: types.ElasticsearchRetrieverEngineType, support: []types.RetrieverType{types.VectorRetrieverType}, - canned: []*types.IndexWithScore{{ChunkID: "es2", Score: -0.4}}, + canned: []*types.IndexWithScore{{ChunkID: "es2", Score: 0.3}}, } fakePG2 := &fakeRetrieveEngineService{ engineType: types.PostgresRetrieverEngineType, @@ -603,6 +614,35 @@ func TestRetrieveFromStores_MixedEngine_Normalizes(t *testing.T) { } assert.InDelta(t, 0.3, scoresByChunk2["es2"], 1e-9) assert.InDelta(t, 0.8, scoresByChunk2["pg2"], 1e-9) + + // Milvus cosine-shift coverage: raw -0.4 → (−0.4 + 1) / 2 = 0.3. + // Milvus is now the only engine in this switch that still uses the + // signed-cosine branch; without this case the [-1, 1] arm would be + // uncovered by the mixed-engine integration test. + fakeMilvus := &fakeRetrieveEngineService{ + engineType: types.MilvusRetrieverEngineType, + support: []types.RetrieverType{types.VectorRetrieverType}, + canned: []*types.IndexWithScore{{ChunkID: "mv1", Score: -0.4}}, + } + fakePG3 := &fakeRetrieveEngineService{ + engineType: types.PostgresRetrieverEngineType, + support: []types.RetrieverType{types.VectorRetrieverType}, + canned: []*types.IndexWithScore{{ChunkID: "pg3", Score: 0.8}}, + } + groups3 := []*storeGroup{ + {Engine: buildBoundComposite(t, fakeMilvus), BaseParams: vectorParams("q"), TopK: 50, KBIDs: []string{"kb-mv"}}, + {Engine: buildBoundComposite(t, fakePG3), BaseParams: vectorParams("q"), TopK: 50, KBIDs: []string{"kb-pg3"}}, + } + res3, err := s.retrieveFromStores(context.Background(), groups3, retriever.EngineAwareNormalizer{}) + require.NoError(t, err) + scoresByChunk3 := map[string]float64{} + for _, rr := range res3 { + for _, hit := range rr.Results { + scoresByChunk3[hit.ChunkID] = hit.Score + } + } + assert.InDelta(t, 0.3, scoresByChunk3["mv1"], 1e-9) + assert.InDelta(t, 0.8, scoresByChunk3["pg3"], 1e-9) } func TestRetrieveFromStores_KeywordPassthroughOnMixed(t *testing.T) { diff --git a/internal/infrastructure/web_search/searxng_test.go b/internal/infrastructure/web_search/searxng_test.go index 3ce18701..f7df650b 100644 --- a/internal/infrastructure/web_search/searxng_test.go +++ b/internal/infrastructure/web_search/searxng_test.go @@ -10,11 +10,22 @@ import ( "time" "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/utils" ) func TestValidateSearxngBaseURL(t *testing.T) { + // utils.ValidateURLForSSRF caches the parsed SSRF_WHITELIST via + // sync.Once on first call. An alphabetically-earlier test in this + // binary (TestValidateProxyURL) triggers ValidateURLForSSRF with an + // empty whitelist and caches an empty config, so the later setenv + // here would otherwise be ignored. Reset the singleton on both + // entry and exit to keep the env / singleton in sync. + utils.ResetSSRFWhitelistForTest() os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") - defer os.Unsetenv("SSRF_WHITELIST") + defer func() { + os.Unsetenv("SSRF_WHITELIST") + utils.ResetSSRFWhitelistForTest() + }() cases := []struct { name string @@ -63,8 +74,15 @@ func TestParseSearxngDate(t *testing.T) { } func TestSearxngProvider_Search(t *testing.T) { + // See TestValidateSearxngBaseURL comment — reset the SSRF whitelist + // singleton so the setenv below is actually observed by the cached + // ssrfWhitelistConfig in internal/utils. + utils.ResetSSRFWhitelistForTest() os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") - defer os.Unsetenv("SSRF_WHITELIST") + defer func() { + os.Unsetenv("SSRF_WHITELIST") + utils.ResetSSRFWhitelistForTest() + }() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/search" { diff --git a/internal/utils/security.go b/internal/utils/security.go index 75a22817..52293937 100644 --- a/internal/utils/security.go +++ b/internal/utils/security.go @@ -967,9 +967,15 @@ func IsSSRFWhitelisted(hostname string) bool { return false } -// resetSSRFWhitelistForTest resets the whitelist singleton so tests can -// re-read the environment variable. NOT for production use. -func resetSSRFWhitelistForTest() { +// ResetSSRFWhitelistForTest resets the whitelist singleton so tests in any +// package can re-read the SSRF_WHITELIST environment variable after changing +// it. Exported (rather than unexported) because callers exist outside +// internal/utils — notably internal/infrastructure/web_search/searxng_test.go, +// whose tests would otherwise see whatever whitelist an alphabetically- +// earlier test in the same binary (e.g. proxy_test.go's TestValidateProxyURL) +// cached via the first sync.Once.Do(). NOT for production use — the ForTest +// suffix is the contract. +func ResetSSRFWhitelistForTest() { ssrfWhitelistOnce = sync.Once{} ssrfWhitelist = nil } diff --git a/internal/utils/security_test.go b/internal/utils/security_test.go index f7dd4268..22fba126 100644 --- a/internal/utils/security_test.go +++ b/internal/utils/security_test.go @@ -196,11 +196,11 @@ func TestValidateURLForSSRF_IPv6Whitelist(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Reset whitelist singleton so we can set a new value - resetSSRFWhitelistForTest() + ResetSSRFWhitelistForTest() os.Setenv("SSRF_WHITELIST", tt.whitelist) defer func() { os.Unsetenv("SSRF_WHITELIST") - resetSSRFWhitelistForTest() + ResetSSRFWhitelistForTest() }() err := ValidateURLForSSRF(tt.rawURL) @@ -233,13 +233,13 @@ func TestSSRFWhitelistExtraMerge(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - resetSSRFWhitelistForTest() + ResetSSRFWhitelistForTest() os.Setenv("SSRF_WHITELIST", tc.main) os.Setenv("SSRF_WHITELIST_EXTRA", tc.extra) defer func() { os.Unsetenv("SSRF_WHITELIST") os.Unsetenv("SSRF_WHITELIST_EXTRA") - resetSSRFWhitelistForTest() + ResetSSRFWhitelistForTest() }() if got := IsSSRFWhitelisted(tc.host); got != tc.want { t.Fatalf("IsSSRFWhitelisted(%q) main=%q extra=%q = %v, want %v",