feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482) laid the type prep + driver skeleton + read/write paths as gated dead code; this PR wires every activation surface so opensearch becomes a registerable VectorStore engine. Activation wiring - internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping / buildEnvStoreForDriver — every gated surface now recognises "opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM / HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines' serialised config byte-identical. - internal/container: createOpenSearchEngine + the switch case in createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path in initRetrieveEngineRegistry; NewEngineFactory now closes over the AuditLogService (the EngineFactory type itself is unchanged). - internal/application/service/vectorstore_healthcheck.go: a testOpenSearchConnection case so CreateStore's connectivity probe accepts opensearch instead of returning 400. - internal/application/repository/retriever/opensearch/transport.go: NewOpenSearchClient is exported so the factory and env path can build the TLS-hardened client; healthcheck.go reuses the unexported probeVersion / probeKNNPlugin for the service-layer probe. Service-layer validation - validateOpenSearchIndexConfig validates the HNSW caps (m 2-100, ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss). Shards/replicas continue to be enforced by the flat ValidateIndexConfig. Create-only: UpdateStore mutates the name only. - validateConnectionConfig requires addr for opensearch. Sync implementations (stubs.go shrinks) - CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern — search → BatchSave with the source_id remap for generated questions — so dim/keyword routing and the source_id contract come from BatchSave for free. embeddingMap is keyed by the *target* SourceID because OpenSearch's BatchSave looks up embeddings by SourceID (lookupEmbedding), not by chunk_id (the ES driver's convention). Pagination is from/size; copies larger than max_result_window (default 10000) need the scroll-based async path that lands later. - BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go) group the input by target value and issue one _update_by_query per group over the cross-dim <base>_* pattern. Caller values flow through bound script params only — never string-interpolated into the Painless source — closing the script-injection surface. - inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the full failure reason goes to the debug log only; the returned error carries the bounded id + type. - UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same shape as DeleteByQuery's quirk), so refresh=wait_for is not expressible; we use refresh=true. Driver-owned audit (DIP) - A new opensearch.AuditSink interface (with nopSink + WithAuditSink functional option) lets the driver emit opensearch.index_created and opensearch.reindex_executed events without importing any service package — the service layer implements the interface. NewRepository takes opts, so existing 4-arg test call sites keep compiling unchanged. - internal/container/audit_sink.go bridges AuditSink to AuditLogService. When the context carries no tenant (the env-path registration ctx during boot, for example) the adapter skips the emit with a warning rather than silently writing tenant_id=0, which would collide with the system-scope sentinel. Frontend + polish - FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/ immutable. VectorStoreSettings.vue is now schema-driven: a closed `enum` renders a t-select; number inputs use the schema's `:min`/`:max` and fall back to the legacy replica-vs-shard heuristic only when the schema does not pin them; a danger-coloured warning fires when insecure_skip_verify is toggled on (the switch and warning are wrapped in a vertical stack so the warning sits on its own row below the switch). - i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search / knn_engine / insecure_skip_verify plus the warning copy in en-US, ko-KR, zh-CN, ru-RU. - docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with security plugin disabled for dev only). OpenSearch Dashboards lives in a separate, opt-in opensearch-ui profile so the heavy UI container is not forced up alongside the cluster (the driver e2e is fully curl-verifiable against :9200). The new docs/dev/opensearch-integration-test.md covers the end-to-end exercise and the single-node guidance (set replicas=0 to keep the cluster Green). Gating-guard tests flipped - The "OpenSearch is NOT in validEngineTypes / mapping / types list / env builder / stubs" guard tests from PR 1 / PR 2 are replaced by their positive counterparts in this PR. The test suite was the activation checklist; the activation flip is its diff. Backward compatibility - Additive everywhere. IndexConfig's new HNSW fields are omitempty so other engines' serialised config is byte-identical. Existing Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB stores are untouched. No migrations. Test plan - go build ./... clean - go vet ./... clean - gofmt -l clean on touched files - go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS endpoint), the docreader gRPC tests, and the doris SQL-shape tests fail; all three are pre-existing on upstream/main and untouched by this PR. - New tests across internal/types, opensearch, service and container — including a full end-to-end env-path test that exercises initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an httptest cluster.
This commit is contained in:
@@ -67,6 +67,14 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto
|
||||
return err
|
||||
}
|
||||
|
||||
// 2.6. Engine-specific index config validation (OpenSearch HNSW bounds).
|
||||
// Create-only: UpdateStore mutates just the name, so this is not re-run there.
|
||||
if store.EngineType == types.OpenSearchRetrieverEngineType {
|
||||
if err := validateOpenSearchIndexConfig(store.IndexConfig); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Duplicate check — DB stores
|
||||
endpoint := store.ConnectionConfig.GetEndpoint()
|
||||
indexName := store.IndexConfig.GetIndexNameOrDefault(store.EngineType)
|
||||
@@ -452,8 +460,51 @@ func validateConnectionConfig(engineType types.RetrieverEngineType, config types
|
||||
if config.Database == "" {
|
||||
return errors.NewValidationError("database is required for doris")
|
||||
}
|
||||
case types.OpenSearchRetrieverEngineType:
|
||||
if config.Addr == "" {
|
||||
return errors.NewValidationError("addr is required for opensearch")
|
||||
}
|
||||
case types.SQLiteRetrieverEngineType:
|
||||
// No connection config needed for SQLite
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// openSearch HNSW bound constants. Shards / replicas are NOT validated here —
|
||||
// the flat types.ValidateIndexConfig already enforces those caps for every
|
||||
// engine. These caps mirror the GetVectorStoreTypes Min/Max so the UI and
|
||||
// backend agree. A zero / empty field means "use the driver default" and is
|
||||
// always accepted.
|
||||
const (
|
||||
osHNSWMMin = 2
|
||||
osHNSWMMax = 100
|
||||
osHNSWEFConstructionMin = 2
|
||||
osHNSWEFConstructionMax = 4096
|
||||
osHNSWEFSearchMin = 1
|
||||
osHNSWEFSearchMax = 10000
|
||||
)
|
||||
|
||||
// validateOpenSearchIndexConfig validates the OpenSearch-specific HNSW fields.
|
||||
// Called from CreateStore only (the store is create-only; UpdateStore mutates
|
||||
// just the name). Unset fields (zero / empty) fall back to driver defaults and
|
||||
// are accepted.
|
||||
func validateOpenSearchIndexConfig(ic types.IndexConfig) error {
|
||||
if ic.HNSWM != 0 && (ic.HNSWM < osHNSWMMin || ic.HNSWM > osHNSWMMax) {
|
||||
return errors.NewValidationError(
|
||||
fmt.Sprintf("hnsw_m must be between %d and %d", osHNSWMMin, osHNSWMMax))
|
||||
}
|
||||
if ic.HNSWEFConstruction != 0 &&
|
||||
(ic.HNSWEFConstruction < osHNSWEFConstructionMin || ic.HNSWEFConstruction > osHNSWEFConstructionMax) {
|
||||
return errors.NewValidationError(
|
||||
fmt.Sprintf("hnsw_ef_construction must be between %d and %d", osHNSWEFConstructionMin, osHNSWEFConstructionMax))
|
||||
}
|
||||
if ic.HNSWEFSearch != 0 &&
|
||||
(ic.HNSWEFSearch < osHNSWEFSearchMin || ic.HNSWEFSearch > osHNSWEFSearchMax) {
|
||||
return errors.NewValidationError(
|
||||
fmt.Sprintf("hnsw_ef_search must be between %d and %d", osHNSWEFSearchMin, osHNSWEFSearchMax))
|
||||
}
|
||||
if ic.KNNEngine != "" && ic.KNNEngine != "lucene" && ic.KNNEngine != "faiss" {
|
||||
return errors.NewValidationError(`knn_engine must be "lucene" or "faiss"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
openSearchRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/opensearch"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -47,6 +48,8 @@ func (s *vectorStoreService) TestConnection(
|
||||
return testWeaviateConnection(ctx, config)
|
||||
case types.DorisRetrieverEngineType:
|
||||
return testDorisConnection(ctx, config)
|
||||
case types.OpenSearchRetrieverEngineType:
|
||||
return testOpenSearchConnection(ctx, config)
|
||||
case types.SQLiteRetrieverEngineType:
|
||||
// SQLite is file-based, no remote connection to test
|
||||
return "", nil
|
||||
@@ -305,3 +308,23 @@ func testDorisConnection(ctx context.Context, config types.ConnectionConfig) (st
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
// testOpenSearchConnection verifies the cluster is reachable, runs a
|
||||
// supported OpenSearch version, and has the k-NN plugin installed. The driver
|
||||
// owns the probe logic; a generic message is returned on failure so cluster
|
||||
// internals are not surfaced to the API caller.
|
||||
func testOpenSearchConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
|
||||
if config.Addr == "" {
|
||||
return "", errors.NewBadRequestError("failed to create opensearch connection: addr is required")
|
||||
}
|
||||
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
|
||||
defer cancel()
|
||||
if err := openSearchRepo.TestConnection(testCtx, &config); err != nil {
|
||||
logger.Warnf(ctx, "OpenSearch connection test failed: %v", err)
|
||||
return "", errors.NewBadRequestError(
|
||||
"failed to connect to opensearch: check address, credentials, version (>= 2.4), and that the k-NN plugin is installed")
|
||||
}
|
||||
// Version is detected during the probe but not surfaced here; lazy index
|
||||
// creation re-validates on first use.
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestValidateConnectionConfig_OpenSearch_RequiresAddr(t *testing.T) {
|
||||
if err := validateConnectionConfig(types.OpenSearchRetrieverEngineType, types.ConnectionConfig{}); err == nil {
|
||||
t.Error("empty addr should be rejected for opensearch")
|
||||
}
|
||||
if err := validateConnectionConfig(types.OpenSearchRetrieverEngineType,
|
||||
types.ConnectionConfig{Addr: "https://os:9200"}); err != nil {
|
||||
t.Errorf("valid addr should pass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateOpenSearchIndexConfig_BoundaryMatrix(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ic types.IndexConfig
|
||||
wantErr bool
|
||||
}{
|
||||
{"all unset (defaults)", types.IndexConfig{}, false},
|
||||
{"valid mid-range", types.IndexConfig{HNSWM: 16, HNSWEFConstruction: 100, HNSWEFSearch: 100, KNNEngine: "lucene"}, false},
|
||||
{"valid faiss", types.IndexConfig{KNNEngine: "faiss"}, false},
|
||||
{"valid boundaries", types.IndexConfig{HNSWM: 2, HNSWEFConstruction: 2, HNSWEFSearch: 1}, false},
|
||||
{"valid upper boundaries", types.IndexConfig{HNSWM: 100, HNSWEFConstruction: 4096, HNSWEFSearch: 10000}, false},
|
||||
{"hnsw_m too low", types.IndexConfig{HNSWM: 1}, true},
|
||||
{"hnsw_m too high", types.IndexConfig{HNSWM: 101}, true},
|
||||
{"ef_construction too high", types.IndexConfig{HNSWEFConstruction: 4097}, true},
|
||||
{"ef_search too high", types.IndexConfig{HNSWEFSearch: 10001}, true},
|
||||
{"invalid engine", types.IndexConfig{KNNEngine: "nmslib"}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateOpenSearchIndexConfig(tt.ic)
|
||||
if tt.wantErr && err == nil {
|
||||
t.Errorf("want error, got nil")
|
||||
}
|
||||
if !tt.wantErr && err != nil {
|
||||
t.Errorf("want nil, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user