feat(retriever): add OpenSearch driver skeleton + interface stubs (PR 2a of 3)
First half of the gated OpenSearch k-NN driver introduced in PR 1 (#1445) by way of #1440. PR 2a ships a hollow, interface-compliant shell of the `internal/application/repository/retriever/opensearch/` package — every behavioural method (Save / BatchSave / DeleteBy* / Retrieve, plus the previously-stubbed CopyIndices / BatchUpdate* / EstimateStorageSize / swapToVersion) returns `ErrFeatureNotEnabled` or a conservative sentinel value. PR 2b lands the real read/write implementations in dedicated files (`query.go` + `retrieve.go` + `crud.go`) and replaces the stubs accordingly. Strict feature-gate (unchanged from PR 1): no entry is added to validEngineTypes / GetVectorStoreTypes / retrieverEngineMapping / BuildEnvVectorStores / container env path / engine factory switch, so the driver remains unreachable. Attempting to register an `engine_type=opensearch` VectorStore continues to fail with the existing "not a valid engine type" error. What lands in PR 2a ------------------- Driver skeleton (6 production files + 2 test files, ~1170 + ~1115 LoC): - `repository.go` — Repository struct + NewRepository constructor that validates cluster reachability + OS version (2.4+ / 3.x; primary tested 3.3.2) + k-NN plugin presence on every cluster node. sync.Once-guarded ensureReady(ctx, dim) for lazy per- dimension index creation, with transient errors not cached so a momentary cluster blip does not permanently poison a dim. sanitizeIndexName enforces a strict OS-compatible name spec. probeVersion uses robust strings.Split/Atoi parsing for pre-release suffixes and missing-patch versions. EngineType returns the PR 1 constant; Support returns [keywords, vector]. - `transport.go` — newOpenSearchClient ships TLS posture (MinVersion TLS 1.2, opt-in InsecureSkipVerify, forward-secrecy- only cipher list) and transport tuning for the driver. Caller exists only in PR 3 (container.go + engine_factory.go); PR 2a remains gated dead code. - `mapping.go` — buildIndexMapping(cfg, dim) produces the full knn_vector + HNSW + content-analyzer mapping with every *_id field as an explicit keyword and source_type as integer. buildKeywordsMapping ships the dim-less keyword-only index mapping used by the no-embedding save path. createIndexAndAlias creates <alias>_v1 and aliases <alias> to it, with best-effort orphan cleanup and mapping-drift detection. - `config.go` — internalCfg (value type) applying OpenSearch defaults (hnsw_m=16, ef_construction=100, ef_search=100, shards=4, replicas=1, engine=lucene). - `errors.go` — nine sentinels (ErrIndexNotFound, ErrDimensionMismatch, ErrAuth, ErrTransport, ErrVersionUnsupported, ErrConfigInvalid, ErrFeatureNotEnabled, ErrBatchTooLarge, ErrCircuitBreaker). Repository never imports apperrors; PR 3's engine factory wraps these to typed AppError 2200/2201. - `stubs.go` — every behavioural method returns ErrFeatureNotEnabled. EstimateStorageSize returns a conservative HNSW lower-bound estimate (not 0) so the Phase 2 KB-delete guard fails-closed for non-empty KBs. Tests (~1115 LoC, 50 cases): - `repository_test.go` — interface satisfaction, sentinel mapping, sanitizeIndexName positive/negative matrix, semver parsing (pre-release / missing-patch), buildIndexMapping JSON shape pin (Lucene + Faiss + Keywords), probeVersion matrix (OS 1.x / 2.2 / 2.5 / 2.11 / 3.x / 3.0.0-rc1 / ES rejection), probeKNNPlugin multi-node coverage, ensureReady concurrency + per-dim isolation + transient retry, NewRepository storeID validation, all 11 stubs (CopyIndices, BatchUpdate*, EstimateStorageSize, SwapToVersion + Save / BatchSave / Retrieve / DeleteBy*), wrapTransport sentinel mapping + leak guard, isNotFound / isAlreadyExistsError, drainAndClose / limitedDecode helpers. - `transport_test.go` — TLS defaults / opt-in InsecureSkipVerify / TLS 1.2 pinning / cipher list / transport tuning. Single dependency addition: github.com/opensearch-project/ opensearch-go/v4 v4.6.0 in go.mod/go.sum. SDK quirks discovered (opensearch-go v4.6.0) -------------------------------------------- PR 2a includes the workarounds for two of three SDK limitations that landed during full implementation (the third, Refresh:*bool, only affects the delete path that ships in PR 2b): - AliasExists 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 *opensearch.StructError. aliasExists therefore inspects resp.StatusCode directly (resp is returned even when err is non-nil) and only falls back to wrapTransport for the "no response at all" case. - sync.OnceReset is not in the standard library; the keyword-only index uses a mutex + ready/err flag pattern so transient failures can be retried by the next caller. The per-dimension path uses the `once map[int]*sync.Once` delete-and-recreate trick. Test fixes folded in -------------------- While doing a full `go test ./...` against PR 1-merged main, two deterministic regressions surfaced that block a clean run-everything signal. Both are unrelated to the driver and are folded into PR 2a so the PR's own CI run is green: (1) Follow-up to #1445 — fanout test missed the new normalizer policy (internal/application/service/knowledgebase_search_fanout_test.go, +46 / -6). #1445 changed EngineAwareNormalizer for ES / ElasticFaiss / OpenSearch / Weaviate / Postgres / SQLite / Qdrant / TencentVectorDB / Doris from (score+1)/2 to clamp01 passthrough (those engines surface non-negative cosine to the normalizer per Lucene script_score non-negative invariant for ES, k-NN plugin SpaceType.COSINESIMIL.scoreTranslation for OpenSearch, engine-internal or IR-normalized conversions for the rest). Milvus is now the only engine that still surfaces raw signed cosine in [-1, 1]. TestRetrieveFromStores_MixedEngine_Normalizes still asserted the old cosine-shift behaviour for ES (raw -0.4 → expected 0.3) which under passthrough now becomes clamp01(-0.4) = 0. The normalizer's own _test.go was updated at #1445 time, but this fan-out integration test was not. Fix: rewrite the godoc to spell out the two engine groups; restate sub-case 2 as ES passthrough on a production-possible mid-range cosine (0.3 → 0.3, PG out-ranks ES); add sub-case 3 pinning the cosine-shift branch via Milvus -0.4 → 0.3. (2) Pre-existing — SSRF whitelist singleton race surfaced by this run (internal/utils/security.go + internal/utils/security_test.go + internal/infrastructure/web_search/searxng_test.go, +33 / -9). loadSSRFWhitelist in internal/utils/security.go is cached via sync.Once on first call. The internal reset helper resetSSRFWhitelistForTest was unexported, so tests in other packages could not reset and saw whatever whitelist was cached by the first sync.Once.Do() in the same test binary. In internal/infrastructure/web_search/, TestValidateProxyURL runs before TestValidateSearxngBaseURL alphabetically and exercises ValidateURLForSSRF with no SSRF_WHITELIST set, caching an empty whitelist; the later setenv in searxng_test then has no effect and 127.0.0.1 is rejected with "hostname 127.0.0.1 is restricted". Pre-existing on main; surfaced now because this PR was the first to do a full `go test ./...` run on top of #1445. Fix: capitalize the helper to ResetSSRFWhitelistForTest (the ForTest suffix is the test-only contract); update in-package callers; in web_search/searxng_test.go import internal/utils and call ResetSSRFWhitelistForTest around the env mutation in both TestValidateSearxngBaseURL and TestSearxngProvider_Search. No production code path changes. Roadmap ------- - PR 2b (next, depends on this PR) — read/write implementations: query.go + retrieve.go + crud.go land their real bodies; stubs for Save / BatchSave / DeleteBy* / Retrieve in stubs.go are removed; corresponding CRUD/retrieve/filter test cases (~430 LoC) join repository_test.go. - PR 3 — activation switch + async paths (CopyIndices, BatchUpdate*, large-batch async deletes) + i18n + docker-compose dev profile. After PR 3 merges, the OpenSearch driver becomes reachable via either `engine_type=opensearch` VectorStore or `RETRIEVE_DRIVER=opensearch` env. Backward compatibility ---------------------- - New package — additive only. No existing file modified except go.mod / go.sum, the two test files in (1)/(2), and the test-only export rename in utils/security.go. - Driver is unreachable: no registry path activates it. - No SQL migration. - The PR 1 normalizer case for OpenSearch remains unreachable here (no driver instance produces a result yet). Test plan --------- - [x] go build ./... clean - [x] go vet ./... clean - [x] go test -race -count=1 ./internal/application/repository/retriever/opensearch/... passes - [x] grep -r "case types.OpenSearchRetrieverEngineType" internal/ shows only PR 1's normalizer case + this driver's EngineType() and tests — no activation path. - [x] grep -r "case \"opensearch\"" internal/ shows no hits.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 "<alias>_v1" with the full k-NN mapping
|
||||
// and then aliases "<alias>" → "<alias>_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/<name> (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
|
||||
}
|
||||
@@ -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 <alias>_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)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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)")
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user