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:
@@ -0,0 +1,50 @@
|
||||
package opensearch
|
||||
|
||||
import "context"
|
||||
|
||||
// AuditSink receives audit events emitted from within the driver at the
|
||||
// exact moment they occur (index provisioned, reindex executed). The driver
|
||||
// owns this abstraction so it imports no service package — the dependency
|
||||
// arrow stays one-way (service implements AuditSink; the driver only invokes
|
||||
// it). A nil sink is a no-op, so tests and the env-path (no audit service)
|
||||
// need no special casing.
|
||||
type AuditSink interface {
|
||||
// EmitIndexCreated fires once when the driver provisions a new k-NN
|
||||
// index. alias is the per-dimension alias (or the keyword-only index
|
||||
// name); dim is the embedding dimension (0 for the keyword-only index).
|
||||
EmitIndexCreated(ctx context.Context, alias string, dim int)
|
||||
// EmitReindexExecuted fires when CopyIndices finishes copying docs from
|
||||
// one index to another.
|
||||
EmitReindexExecuted(ctx context.Context, srcAlias, dstAlias string, docs int64)
|
||||
}
|
||||
|
||||
// nopSink is the null-object used when no sink is configured, so emit call
|
||||
// sites never need a nil check.
|
||||
type nopSink struct{}
|
||||
|
||||
func (nopSink) EmitIndexCreated(context.Context, string, int) {}
|
||||
func (nopSink) EmitReindexExecuted(context.Context, string, string, int64) {}
|
||||
|
||||
var _ AuditSink = nopSink{}
|
||||
|
||||
// Option configures a Repository at construction time.
|
||||
type Option func(*Repository)
|
||||
|
||||
// WithAuditSink injects an audit sink. A nil sink is ignored (the Repository
|
||||
// keeps its default no-op behavior).
|
||||
func WithAuditSink(s AuditSink) Option {
|
||||
return func(r *Repository) {
|
||||
if s != nil {
|
||||
r.sink = s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// auditSink returns the configured sink, or a no-op if none was set (e.g. a
|
||||
// Repository built directly in tests, or constructed without WithAuditSink).
|
||||
func (r *Repository) auditSink() AuditSink {
|
||||
if r.sink == nil {
|
||||
return nopSink{}
|
||||
}
|
||||
return r.sink
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// spySink records audit events for assertions.
|
||||
type spySink struct {
|
||||
mu sync.Mutex
|
||||
indexCreated []indexCreatedEvent
|
||||
reindex []reindexEvent
|
||||
}
|
||||
|
||||
type indexCreatedEvent struct {
|
||||
alias string
|
||||
dim int
|
||||
}
|
||||
type reindexEvent struct {
|
||||
src, dst string
|
||||
docs int64
|
||||
}
|
||||
|
||||
func (s *spySink) EmitIndexCreated(_ context.Context, alias string, dim int) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.indexCreated = append(s.indexCreated, indexCreatedEvent{alias, dim})
|
||||
}
|
||||
|
||||
func (s *spySink) EmitReindexExecuted(_ context.Context, src, dst string, docs int64) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.reindex = append(s.reindex, reindexEvent{src, dst, docs})
|
||||
}
|
||||
|
||||
// TestBuildInternalCfg_ReadsHNSWFields verifies the HNSW IndexConfig fields
|
||||
// flow into internalCfg, falling back to defaults when unset.
|
||||
func TestBuildInternalCfg_ReadsHNSWFields(t *testing.T) {
|
||||
t.Run("reads set fields", func(t *testing.T) {
|
||||
cfg, err := buildInternalCfg(&types.IndexConfig{
|
||||
HNSWM: 24,
|
||||
HNSWEFConstruction: 200,
|
||||
HNSWEFSearch: 128,
|
||||
KNNEngine: "faiss",
|
||||
NumberOfShards: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.hnswM != 24 || cfg.hnswEFConstruction != 200 || cfg.efSearch != 128 || cfg.knnEngine != "faiss" {
|
||||
t.Errorf("HNSW not wired: %+v", cfg)
|
||||
}
|
||||
if cfg.shards != 2 {
|
||||
t.Errorf("shards: want 2, got %d", cfg.shards)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("defaults when unset", func(t *testing.T) {
|
||||
cfg, err := buildInternalCfg(&types.IndexConfig{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.hnswM != 16 || cfg.hnswEFConstruction != 100 || cfg.efSearch != 100 || cfg.knnEngine != "lucene" {
|
||||
t.Errorf("defaults not applied: %+v", cfg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nil config is all defaults", func(t *testing.T) {
|
||||
cfg, err := buildInternalCfg(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.knnEngine != "lucene" || cfg.hnswM != 16 {
|
||||
t.Errorf("nil defaults wrong: %+v", cfg)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestBuildIndexMapping_ReflectsHNSWConfig verifies the end-to-end path
|
||||
// IndexConfig → buildInternalCfg → buildIndexMapping carries the operator's
|
||||
// HNSW values into the cluster mapping JSON (regression guard for the wire-
|
||||
// through, since defaults coincide with common values).
|
||||
func TestBuildIndexMapping_ReflectsHNSWConfig(t *testing.T) {
|
||||
cfg, err := buildInternalCfg(&types.IndexConfig{
|
||||
HNSWM: 24,
|
||||
HNSWEFConstruction: 200,
|
||||
HNSWEFSearch: 128,
|
||||
KNNEngine: "faiss",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := buildIndexMapping(cfg, 768)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := string(body)
|
||||
for _, want := range []string{`"m":24`, `"ef_construction":200`, `"engine":"faiss"`, `"knn.algo_param.ef_search":128`} {
|
||||
if !strings.Contains(s, want) {
|
||||
t.Errorf("mapping JSON missing %q\n%s", want, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWithAuditSink_SetsAndNilSafe verifies the functional option.
|
||||
func TestWithAuditSink_SetsAndNilSafe(t *testing.T) {
|
||||
spy := &spySink{}
|
||||
r := &Repository{}
|
||||
WithAuditSink(spy)(r)
|
||||
if r.sink != spy {
|
||||
t.Fatal("WithAuditSink did not set the sink")
|
||||
}
|
||||
// nil must not clobber an already-set sink
|
||||
WithAuditSink(nil)(r)
|
||||
if r.sink != spy {
|
||||
t.Fatal("WithAuditSink(nil) clobbered the sink")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuditSink_NopByDefault verifies a Repository with no sink does not panic
|
||||
// when the audit accessor is used (nopSink fallback).
|
||||
func TestAuditSink_NopByDefault(t *testing.T) {
|
||||
var _ AuditSink = nopSink{} // compile-time assertion
|
||||
r := &Repository{} // sink left nil
|
||||
// Must not panic.
|
||||
r.auditSink().EmitIndexCreated(context.Background(), "weknora_768", 768)
|
||||
r.auditSink().EmitReindexExecuted(context.Background(), "a", "b", 3)
|
||||
}
|
||||
|
||||
// TestAuditSink_EmitIndexCreated_OnEnsureReady verifies createIndexAndAlias
|
||||
// emits exactly one index-created event with the per-dim alias when a new
|
||||
// index is provisioned.
|
||||
func TestAuditSink_EmitIndexCreated_OnEnsureReady(t *testing.T) {
|
||||
repo, ts := newTestRepo(t, (&indexLifecycleHandler{}).ServeHTTP)
|
||||
defer ts.Close()
|
||||
spy := &spySink{}
|
||||
repo.sink = spy
|
||||
|
||||
if err := repo.ensureReady(context.Background(), 768); err != nil {
|
||||
t.Fatalf("ensureReady: %v", err)
|
||||
}
|
||||
if len(spy.indexCreated) != 1 {
|
||||
t.Fatalf("want 1 index_created event, got %d", len(spy.indexCreated))
|
||||
}
|
||||
got := spy.indexCreated[0]
|
||||
if got.alias != "weknora_test_768" || got.dim != 768 {
|
||||
t.Errorf("event mismatch: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
|
||||
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
|
||||
)
|
||||
|
||||
// BatchUpdateChunkEnabledStatus flips is_enabled for the given chunks. The
|
||||
// status map is grouped by value into one _update_by_query per distinct value
|
||||
// (mirrors the Qdrant grouping pattern), so the request body carries the
|
||||
// chunk ids via a terms filter and the new value via bound script params —
|
||||
// never per-chunk string interpolation.
|
||||
//
|
||||
// Targets the cross-dim <base>_* pattern: a chunk's embedding dimension is
|
||||
// not known here, and the same chunk_id is unique across the store's dim
|
||||
// indices + the keyword-only index.
|
||||
func (r *Repository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
if len(chunkStatusMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
groups := map[bool][]string{}
|
||||
for id, v := range chunkStatusMap {
|
||||
groups[v] = append(groups[v], id)
|
||||
}
|
||||
// Deterministic order (false then true) for predictable behavior/tests.
|
||||
for _, v := range []bool{false, true} {
|
||||
ids := groups[v]
|
||||
if len(ids) == 0 {
|
||||
continue
|
||||
}
|
||||
sort.Strings(ids)
|
||||
if err := r.updateByQueryScript(ctx, ids,
|
||||
"ctx._source.is_enabled = params.v", map[string]any{"v": v}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// BatchUpdateChunkTagID sets tag_id for the given chunks, grouped by tag.
|
||||
func (r *Repository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
|
||||
if len(chunkTagMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
groups := map[string][]string{}
|
||||
for id, tag := range chunkTagMap {
|
||||
groups[tag] = append(groups[tag], id)
|
||||
}
|
||||
tags := make([]string, 0, len(groups))
|
||||
for tag := range groups {
|
||||
tags = append(tags, tag)
|
||||
}
|
||||
sort.Strings(tags)
|
||||
for _, tag := range tags {
|
||||
ids := groups[tag]
|
||||
sort.Strings(ids)
|
||||
if err := r.updateByQueryScript(ctx, ids,
|
||||
"ctx._source.tag_id = params.v", map[string]any{"v": tag}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateByQueryScript runs an _update_by_query over the cross-dim <base>_*
|
||||
// pattern, matching the given chunk ids via a terms filter and applying a
|
||||
// constant Painless source with caller values flowing only through bound
|
||||
// params (Painless-injection-safe).
|
||||
func (r *Repository) updateByQueryScript(
|
||||
ctx context.Context, chunkIDs []string, source string, params map[string]any,
|
||||
) error {
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"query": map[string]any{
|
||||
"terms": map[string]any{"chunk_id": chunkIDs},
|
||||
},
|
||||
"script": map[string]any{
|
||||
"lang": "painless",
|
||||
"source": source,
|
||||
"params": params,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("opensearch: marshal update_by_query body: %w", err)
|
||||
}
|
||||
// Q2: UpdateByQueryParams.Refresh is *bool — the wire value "wait_for" is
|
||||
// not expressible via the typed SDK, so we force an immediate refresh.
|
||||
refresh := true
|
||||
resp, err := r.client.UpdateByQuery(ctx, osapi.UpdateByQueryReq{
|
||||
Indices: []string{r.baseIndex + "_*"},
|
||||
Body: bytes.NewReader(body),
|
||||
Params: osapi.UpdateByQueryParams{Refresh: &refresh},
|
||||
})
|
||||
if err != nil {
|
||||
return wrapTransport(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
defer drainAndClose(resp.Inspect().Response.Body)
|
||||
return inspectByQueryResponse(io.LimitReader(resp.Inspect().Response.Body, 16<<20))
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// inspectByQueryResponse parses an _update_by_query / _delete_by_query
|
||||
// response and surfaces partial failures without leaking cluster-side reason
|
||||
// strings (which may embed document content). Mirrors inspectBulkResponse:
|
||||
// the full reason goes to the debug log only; the returned error carries the
|
||||
// bounded id + type. A non-zero version_conflicts count with no hard failures
|
||||
// is logged as a warning but not treated as an error.
|
||||
func inspectByQueryResponse(body io.Reader) error {
|
||||
var r struct {
|
||||
VersionConflicts int `json:"version_conflicts"`
|
||||
Failures []struct {
|
||||
ID string `json:"id"`
|
||||
Cause struct {
|
||||
Type string `json:"type"`
|
||||
Reason string `json:"reason"`
|
||||
} `json:"cause"`
|
||||
} `json:"failures"`
|
||||
}
|
||||
if err := json.NewDecoder(body).Decode(&r); err != nil {
|
||||
return fmt.Errorf("opensearch: parse by-query response: %w", ErrTransport)
|
||||
}
|
||||
log := logger.GetLogger(context.Background())
|
||||
if len(r.Failures) == 0 {
|
||||
if r.VersionConflicts > 0 {
|
||||
log.Warnf("[OpenSearch] by-query had %d version conflicts (proceeded)", r.VersionConflicts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var msgs []string
|
||||
for _, f := range r.Failures {
|
||||
// Full reason → debug log only (may contain document content).
|
||||
log.Debugf("[OpenSearch] by-query failure: id=%s type=%s reason=%s",
|
||||
f.ID, f.Cause.Type, f.Cause.Reason)
|
||||
if len(msgs) < 5 {
|
||||
msgs = append(msgs, fmt.Sprintf("[%s] %s", f.ID, f.Cause.Type))
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("opensearch: by-query partial failure (%d failed, first 5: %s): %w",
|
||||
len(r.Failures), strings.Join(msgs, "; "), ErrTransport)
|
||||
}
|
||||
@@ -15,16 +15,15 @@ type internalCfg struct {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// substituting defaults for unset (zero / empty) fields. Validation of value
|
||||
// ranges (e.g. hnsw_m / ef_construction caps) is a service-layer concern
|
||||
// handled elsewhere (validateOpenSearchIndexConfig at CreateStore); this
|
||||
// function applies defaults only and never rejects. The env-path bypasses
|
||||
// service validation entirely, so the defaults below are its safety net.
|
||||
//
|
||||
// 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.
|
||||
// The OpenSearch-specific HNSW fields (knn_engine, hnsw_m,
|
||||
// hnsw_ef_construction, hnsw_ef_search) are read here. They are omitempty on
|
||||
// IndexConfig, so they do not affect other drivers' serialized config.
|
||||
func buildInternalCfg(c *types.IndexConfig) (internalCfg, error) {
|
||||
cfg := internalCfg{
|
||||
shards: 4, // matches the keyword-index default upstream
|
||||
@@ -43,5 +42,17 @@ func buildInternalCfg(c *types.IndexConfig) (internalCfg, error) {
|
||||
if c.NumberOfReplicas > 0 {
|
||||
cfg.replicas = c.NumberOfReplicas
|
||||
}
|
||||
if c.KNNEngine != "" {
|
||||
cfg.knnEngine = c.KNNEngine
|
||||
}
|
||||
if c.HNSWM > 0 {
|
||||
cfg.hnswM = c.HNSWM
|
||||
}
|
||||
if c.HNSWEFConstruction > 0 {
|
||||
cfg.hnswEFConstruction = c.HNSWEFConstruction
|
||||
}
|
||||
if c.HNSWEFSearch > 0 {
|
||||
cfg.efSearch = c.HNSWEFSearch
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// copyBatchSize is the pagination size for the source scan. Kept under the
|
||||
// BatchSave per-call cap so each copied page is a single bulk request.
|
||||
const copyBatchSize = 500
|
||||
|
||||
// copySourceDoc is the full _source read during CopyIndices — it includes the
|
||||
// embedding vector and is_recommended, which the retrieve-path hit struct
|
||||
// omits because retrieval does not need them.
|
||||
type copySourceDoc struct {
|
||||
Content string `json:"content"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType int `json:"source_type"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TagID string `json:"tag_id"`
|
||||
IsEnabled bool `json:"is_enabled"`
|
||||
IsRecommended bool `json:"is_recommended"`
|
||||
Embedding []float32 `json:"embedding"`
|
||||
}
|
||||
|
||||
// transformSourceID mirrors the sibling drivers' source_id remap:
|
||||
// - regular chunk (source_id == chunk_id) → target chunk id
|
||||
// - generated question (source_id == "<chunk>-<q>") → "<targetChunk>-<q>"
|
||||
// - anything else → a fresh uuid
|
||||
func transformSourceID(sourceID, chunkID, targetChunkID string) string {
|
||||
switch {
|
||||
case sourceID == chunkID:
|
||||
return targetChunkID
|
||||
case strings.HasPrefix(sourceID, chunkID+"-"):
|
||||
return targetChunkID + "-" + strings.TrimPrefix(sourceID, chunkID+"-")
|
||||
default:
|
||||
return uuid.New().String()
|
||||
}
|
||||
}
|
||||
|
||||
// CopyIndices copies all docs of one knowledge base into another (within the
|
||||
// same store) by scanning the source and re-saving via BatchSave — mirroring
|
||||
// the Elasticsearch / Qdrant drivers (search→BatchSave), which yields the
|
||||
// source_id transformation and dim/keyword routing for free. Runs
|
||||
// synchronously and paginates; the large-batch background-task path is a
|
||||
// later change.
|
||||
//
|
||||
// NOTE: from/size pagination is bounded by the index's max_result_window
|
||||
// (default 10000). Copies larger than that require the scroll-based async
|
||||
// path (a later change).
|
||||
func (r *Repository) CopyIndices(
|
||||
ctx context.Context,
|
||||
sourceKnowledgeBaseID string,
|
||||
sourceToTargetKBIDMap map[string]string, // keyed by source knowledge_id (mirrors sibling drivers)
|
||||
sourceToTargetChunkIDMap map[string]string,
|
||||
targetKnowledgeBaseID string,
|
||||
dimension int,
|
||||
knowledgeType string,
|
||||
) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(sourceToTargetChunkIDMap) == 0 {
|
||||
log.Warn("[OpenSearch] CopyIndices: empty chunk mapping, skipping")
|
||||
return nil
|
||||
}
|
||||
if dimension <= 0 {
|
||||
return fmt.Errorf("opensearch: CopyIndices requires dim > 0, got %d: %w",
|
||||
dimension, ErrDimensionMismatch)
|
||||
}
|
||||
if err := r.ensureReady(ctx, dimension); err != nil {
|
||||
return err
|
||||
}
|
||||
alias := r.indexAlias(dimension)
|
||||
|
||||
var total int64
|
||||
for from := 0; ; from += copyBatchSize {
|
||||
docs, err := r.copyScanBatch(ctx, alias, sourceKnowledgeBaseID, from, copyBatchSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(docs) == 0 {
|
||||
break
|
||||
}
|
||||
infos := make([]*types.IndexInfo, 0, len(docs))
|
||||
embMap := make(map[string][]float32, len(docs))
|
||||
enabledMap := make(map[string]bool, len(docs))
|
||||
for i := range docs {
|
||||
d := &docs[i]
|
||||
targetChunkID, ok := sourceToTargetChunkIDMap[d.ChunkID]
|
||||
if !ok {
|
||||
log.Warnf("[OpenSearch] CopyIndices: source chunk %s not mapped, skipping", d.ChunkID)
|
||||
continue
|
||||
}
|
||||
targetKnowledgeID, ok := sourceToTargetKBIDMap[d.KnowledgeID]
|
||||
if !ok {
|
||||
log.Warnf("[OpenSearch] CopyIndices: source knowledge %s not mapped, skipping", d.KnowledgeID)
|
||||
continue
|
||||
}
|
||||
targetSourceID := transformSourceID(d.SourceID, d.ChunkID, targetChunkID)
|
||||
if len(d.Embedding) > 0 {
|
||||
// BatchSave looks up embeddings by SourceID (lookupEmbedding),
|
||||
// so key by the target source id — not the chunk id, which is
|
||||
// the Elasticsearch driver's convention.
|
||||
embMap[targetSourceID] = d.Embedding
|
||||
}
|
||||
enabledMap[targetChunkID] = d.IsEnabled
|
||||
infos = append(infos, &types.IndexInfo{
|
||||
Content: d.Content,
|
||||
SourceID: targetSourceID,
|
||||
SourceType: types.SourceType(d.SourceType),
|
||||
ChunkID: targetChunkID,
|
||||
KnowledgeID: targetKnowledgeID,
|
||||
KnowledgeBaseID: targetKnowledgeBaseID,
|
||||
KnowledgeType: knowledgeType,
|
||||
TagID: d.TagID,
|
||||
IsEnabled: d.IsEnabled,
|
||||
IsRecommended: d.IsRecommended,
|
||||
})
|
||||
}
|
||||
if len(infos) > 0 {
|
||||
params := map[string]any{
|
||||
"embedding": embMap,
|
||||
"chunk_enabled": enabledMap,
|
||||
}
|
||||
if err := r.BatchSave(ctx, infos, params); err != nil {
|
||||
return fmt.Errorf("opensearch: CopyIndices batch save: %w", err)
|
||||
}
|
||||
total += int64(len(infos))
|
||||
}
|
||||
if len(docs) < copyBatchSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
log.Infof("[OpenSearch] CopyIndices: copied %d docs (KB %s → %s, dim=%d)",
|
||||
total, sourceKnowledgeBaseID, targetKnowledgeBaseID, dimension)
|
||||
r.auditSink().EmitReindexExecuted(ctx, alias, alias, total)
|
||||
return nil
|
||||
}
|
||||
|
||||
// copyScanBatch reads one page of docs belonging to sourceKB from the per-dim
|
||||
// index, decoding the full _source (including the embedding vector).
|
||||
func (r *Repository) copyScanBatch(
|
||||
ctx context.Context, index, sourceKB string, from, size int,
|
||||
) ([]copySourceDoc, error) {
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"from": from,
|
||||
"size": size,
|
||||
"query": map[string]any{
|
||||
"bool": map[string]any{
|
||||
"filter": []any{
|
||||
map[string]any{"term": map[string]any{"knowledge_base_id": sourceKB}},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opensearch: marshal copy scan body: %w", err)
|
||||
}
|
||||
req := osapi.SearchReq{Indices: []string{index}, Body: bytes.NewReader(body)}
|
||||
resp, err := r.client.Search(ctx, &req)
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return nil, fmt.Errorf("opensearch: index %s missing: %w", index, ErrIndexNotFound)
|
||||
}
|
||||
return nil, wrapTransport(err)
|
||||
}
|
||||
defer drainAndClose(resp.Inspect().Response.Body)
|
||||
var parsed struct {
|
||||
Hits struct {
|
||||
Hits []struct {
|
||||
Source copySourceDoc `json:"_source"`
|
||||
} `json:"hits"`
|
||||
} `json:"hits"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Inspect().Response.Body, 64<<20)).Decode(&parsed); err != nil {
|
||||
return nil, fmt.Errorf("opensearch: parse copy scan response: %w", ErrTransport)
|
||||
}
|
||||
out := make([]copySourceDoc, len(parsed.Hits.Hits))
|
||||
for i, h := range parsed.Hits.Hits {
|
||||
out[i] = h.Source
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestTransformSourceID covers the generated-question / regular / fallback
|
||||
// branches that CopyIndices uses to remap source_id.
|
||||
func TestTransformSourceID(t *testing.T) {
|
||||
t.Run("regular chunk uses target chunk id", func(t *testing.T) {
|
||||
if got := transformSourceID("chunk1", "chunk1", "tgt1"); got != "tgt1" {
|
||||
t.Errorf("want tgt1, got %s", got)
|
||||
}
|
||||
})
|
||||
t.Run("generated question preserves question id", func(t *testing.T) {
|
||||
if got := transformSourceID("chunk1-q7", "chunk1", "tgt1"); got != "tgt1-q7" {
|
||||
t.Errorf("want tgt1-q7, got %s", got)
|
||||
}
|
||||
})
|
||||
t.Run("unrelated source id gets fresh uuid", func(t *testing.T) {
|
||||
got := transformSourceID("totally-different", "chunk1", "tgt1")
|
||||
if got == "totally-different" || got == "tgt1" || len(got) != 36 {
|
||||
t.Errorf("want fresh uuid, got %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestCopyIndices_EmptyMapping_NoOp verifies an empty chunk map short-circuits
|
||||
// before any HTTP call.
|
||||
func TestCopyIndices_EmptyMapping_NoOp(t *testing.T) {
|
||||
repo, ts := newTestRepo(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("unexpected HTTP call: %s %s", r.Method, r.URL.Path)
|
||||
})
|
||||
defer ts.Close()
|
||||
err := repo.CopyIndices(context.Background(), "kbSrc", map[string]string{}, map[string]string{}, "kbDst", 768, "manual")
|
||||
if err != nil {
|
||||
t.Fatalf("want nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCopyIndices_ScanThenBatchSave verifies the search→BatchSave path:
|
||||
// remaps IDs, keys the embedding by the *target source id* (OpenSearch
|
||||
// BatchSave's lookup key), and emits one reindex audit event.
|
||||
func TestCopyIndices_ScanThenBatchSave(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
bulkBody string
|
||||
searchCnt int
|
||||
)
|
||||
handler := func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodHead:
|
||||
w.WriteHeader(http.StatusOK) // alias exists → ensureReady no-op
|
||||
case strings.Contains(r.URL.Path, "_search"):
|
||||
mu.Lock()
|
||||
searchCnt++
|
||||
first := searchCnt == 1
|
||||
mu.Unlock()
|
||||
if first {
|
||||
_, _ = w.Write([]byte(`{"hits":{"hits":[
|
||||
{"_source":{"content":"c","source_id":"srcChunk","source_type":1,"chunk_id":"srcChunk","knowledge_id":"srcKnow","knowledge_base_id":"kbSrc","tag_id":"t","is_enabled":true,"is_recommended":false,"embedding":[0.1,0.2,0.3]}}
|
||||
]}}`))
|
||||
} else {
|
||||
_, _ = w.Write([]byte(`{"hits":{"hits":[]}}`))
|
||||
}
|
||||
case strings.HasSuffix(r.URL.Path, "/_bulk"):
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
bulkBody = string(b)
|
||||
mu.Unlock()
|
||||
_, _ = w.Write([]byte(`{"errors":false,"items":[]}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}
|
||||
}
|
||||
repo, ts := newTestRepo(t, handler)
|
||||
defer ts.Close()
|
||||
spy := &spySink{}
|
||||
repo.sink = spy
|
||||
|
||||
err := repo.CopyIndices(context.Background(), "kbSrc",
|
||||
map[string]string{"srcKnow": "tgtKnow"}, // knowledge_id remap (sourceToTargetKBIDMap is keyed by knowledge_id, mirroring ES)
|
||||
map[string]string{"srcChunk": "tgtChunk"},
|
||||
"kbDst", 768, "manual")
|
||||
if err != nil {
|
||||
t.Fatalf("CopyIndices: %v", err)
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if bulkBody == "" {
|
||||
t.Fatal("no bulk request captured")
|
||||
}
|
||||
// Target IDs present, source IDs gone from the written doc.
|
||||
for _, want := range []string{`"chunk_id":"tgtChunk"`, `"knowledge_id":"tgtKnow"`, `"knowledge_base_id":"kbDst"`, `"source_id":"tgtChunk"`} {
|
||||
if !strings.Contains(bulkBody, want) {
|
||||
t.Errorf("bulk body missing %q\n%s", want, bulkBody)
|
||||
}
|
||||
}
|
||||
if strings.Contains(bulkBody, `"knowledge_base_id":"kbSrc"`) {
|
||||
t.Errorf("bulk body leaked source KB id\n%s", bulkBody)
|
||||
}
|
||||
// Embedding written (keyed by target source id internally).
|
||||
if !strings.Contains(bulkBody, "0.1") {
|
||||
t.Errorf("embedding not written\n%s", bulkBody)
|
||||
}
|
||||
if len(spy.reindex) != 1 || spy.reindex[0].docs != 1 {
|
||||
t.Errorf("want 1 reindex event with docs=1, got %+v", spy.reindex)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBatchUpdateChunkEnabledStatus_GroupedUpdateByQuery verifies the status
|
||||
// map is grouped by value into one _update_by_query per distinct value, each
|
||||
// passing chunk ids via terms + the new value via bound script params.
|
||||
func TestBatchUpdateChunkEnabledStatus_GroupedUpdateByQuery(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
bodies []string
|
||||
)
|
||||
handler := func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.URL.Path, "_update_by_query") {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
bodies = append(bodies, string(b))
|
||||
mu.Unlock()
|
||||
_, _ = w.Write([]byte(`{"updated":1,"version_conflicts":0,"failures":[]}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}
|
||||
repo, ts := newTestRepo(t, handler)
|
||||
defer ts.Close()
|
||||
|
||||
err := repo.BatchUpdateChunkEnabledStatus(context.Background(), map[string]bool{
|
||||
"c1": true, "c2": false, "c3": true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BatchUpdateChunkEnabledStatus: %v", err)
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(bodies) != 2 {
|
||||
t.Fatalf("want 2 grouped update_by_query calls (true/false), got %d: %v", len(bodies), bodies)
|
||||
}
|
||||
joined := strings.Join(bodies, "\n")
|
||||
for _, want := range []string{"c1", "c2", "c3", "is_enabled", "params"} {
|
||||
if !strings.Contains(joined, want) {
|
||||
t.Errorf("update_by_query bodies missing %q\n%s", want, joined)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchUpdateChunkEnabledStatus_Empty_NoOp(t *testing.T) {
|
||||
repo, ts := newTestRepo(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("unexpected HTTP call: %s %s", r.Method, r.URL.Path)
|
||||
})
|
||||
defer ts.Close()
|
||||
if err := repo.BatchUpdateChunkEnabledStatus(context.Background(), map[string]bool{}); err != nil {
|
||||
t.Fatalf("want nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInspectByQueryResponse covers the success path and the failure path,
|
||||
// asserting cluster-side reason text is NOT surfaced in the returned error.
|
||||
func TestInspectByQueryResponse(t *testing.T) {
|
||||
t.Run("clean response", func(t *testing.T) {
|
||||
body := strings.NewReader(`{"updated":5,"version_conflicts":0,"failures":[]}`)
|
||||
if err := inspectByQueryResponse(body); err != nil {
|
||||
t.Fatalf("want nil, got %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("failures do not leak reason", func(t *testing.T) {
|
||||
body := strings.NewReader(`{"updated":1,"version_conflicts":0,"failures":[
|
||||
{"id":"c9","cause":{"type":"version_conflict_engine_exception","reason":"SECRET document body leaked here"}}
|
||||
]}`)
|
||||
err := inspectByQueryResponse(body)
|
||||
if err == nil {
|
||||
t.Fatal("want error for failures, got nil")
|
||||
}
|
||||
if strings.Contains(err.Error(), "SECRET") {
|
||||
t.Errorf("error leaked cluster reason: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "version_conflict_engine_exception") {
|
||||
t.Errorf("error should surface bounded type: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// TestConnection verifies an OpenSearch cluster is reachable, runs a
|
||||
// supported version, and has the k-NN plugin installed on every node. It is
|
||||
// the connectivity probe used by the VectorStore service's CreateStore
|
||||
// health-check (the driver's unexported probes are reused here). Returns a
|
||||
// wrapped sentinel error on failure; nil on success.
|
||||
func TestConnection(ctx context.Context, cfg *types.ConnectionConfig) error {
|
||||
client, err := NewOpenSearchClient(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := probeVersion(ctx, client); err != nil {
|
||||
return err
|
||||
}
|
||||
return probeKNNPlugin(ctx, client)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// clusterHandler serves both GET / (version info) and /_cat/plugins, so the
|
||||
// full TestConnection probe (version + k-NN plugin) can run end to end.
|
||||
func clusterHandler(distribution, number string, plugins []osapi.CatPluginResp) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/_cat/plugins" {
|
||||
_ = json.NewEncoder(w).Encode(plugins)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"version":{"distribution":"` + distribution + `","number":"` + number + `"}}`))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestConnection_Success(t *testing.T) {
|
||||
ts := httptest.NewServer(clusterHandler("opensearch", "3.3.2", []osapi.CatPluginResp{
|
||||
{Name: "node-1", Component: "opensearch-knn"},
|
||||
}))
|
||||
defer ts.Close()
|
||||
if err := TestConnection(context.Background(), &types.ConnectionConfig{Addr: ts.URL}); err != nil {
|
||||
t.Errorf("healthy cluster: want nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestConnection_RejectsElasticsearch(t *testing.T) {
|
||||
ts := httptest.NewServer(clusterHandler("elasticsearch", "8.10.4", nil))
|
||||
defer ts.Close()
|
||||
if err := TestConnection(context.Background(), &types.ConnectionConfig{Addr: ts.URL}); err == nil {
|
||||
t.Error("elasticsearch cluster should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestConnection_EmptyAddr(t *testing.T) {
|
||||
if err := TestConnection(context.Background(), &types.ConnectionConfig{}); err == nil {
|
||||
t.Error("empty addr should be rejected")
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,11 @@ func (r *Repository) createIndexAndAlias(ctx context.Context, dim int) error {
|
||||
}
|
||||
return fmt.Errorf("put alias %s → %s: %w", alias, realIndex, err)
|
||||
}
|
||||
if indexCreated {
|
||||
// Emit only when we actually provisioned the index (not when a
|
||||
// concurrent writer / existing index short-circuited above).
|
||||
r.auditSink().EmitIndexCreated(ctx, alias, dim)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -217,6 +222,7 @@ func (r *Repository) ensureKeywordsIndex(ctx context.Context) error {
|
||||
r.keywordsErr = err
|
||||
return err
|
||||
}
|
||||
created := false
|
||||
if err := r.indicesCreate(ctx, name, body); err != nil {
|
||||
if !isAlreadyExistsError(err) {
|
||||
r.keywordsErr = err
|
||||
@@ -224,9 +230,15 @@ func (r *Repository) ensureKeywordsIndex(ctx context.Context) error {
|
||||
}
|
||||
// resource_already_exists_exception — race with concurrent process,
|
||||
// treat as success.
|
||||
} else {
|
||||
created = true
|
||||
}
|
||||
r.keywordsReady = true
|
||||
r.keywordsErr = nil
|
||||
if created {
|
||||
// dim=0 marks the dim-less keyword-only index.
|
||||
r.auditSink().EmitIndexCreated(ctx, name, 0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,11 @@ type Repository struct {
|
||||
keywordsMu sync.Mutex
|
||||
keywordsReady bool
|
||||
keywordsErr error
|
||||
|
||||
// sink receives audit events (index created / reindex executed). nil
|
||||
// means no auditing; use r.auditSink() to get a non-nil sink. Set via
|
||||
// WithAuditSink at construction.
|
||||
sink AuditSink
|
||||
}
|
||||
|
||||
// Compile-time interface satisfaction (Go best practice — keeps the build
|
||||
@@ -87,6 +92,10 @@ var _ interfaces.RetrieveEngineRepository = (*Repository)(nil)
|
||||
// indexCfg is optional — pass nil to use env var (OPENSEARCH_INDEX) or
|
||||
// default ("weknora") values.
|
||||
//
|
||||
// Optional behavior is configured via functional options (e.g.
|
||||
// WithAuditSink). Passing no options keeps audit emission as a no-op, so the
|
||||
// env-path and tests need no extra wiring.
|
||||
//
|
||||
// Returns a typed sentinel error wrapped with %w; callers translate to
|
||||
// AppError at the engine-factory boundary.
|
||||
func NewRepository(
|
||||
@@ -94,6 +103,7 @@ func NewRepository(
|
||||
client *osapi.Client,
|
||||
storeID string,
|
||||
indexCfg *types.IndexConfig,
|
||||
opts ...Option,
|
||||
) (interfaces.RetrieveEngineRepository, error) {
|
||||
log := logger.GetLogger(ctx)
|
||||
|
||||
@@ -135,6 +145,9 @@ func NewRepository(
|
||||
once: make(map[int]*sync.Once),
|
||||
initErr: make(map[int]error),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(r)
|
||||
}
|
||||
log.Infof("[OpenSearch] repository ready (baseIndex=%s, knn_engine=%s, hnsw_m=%d)",
|
||||
base, icfg.knnEngine, icfg.hnswM)
|
||||
return r, nil
|
||||
|
||||
@@ -218,18 +218,18 @@ func TestSanitizeIndexName_RejectsInvalid(t *testing.T) {
|
||||
func TestParseMajorMinor(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
in string
|
||||
wantMaj int
|
||||
wantMinor int
|
||||
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
|
||||
{"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
|
||||
{"abc", 0, 0}, // unparseable
|
||||
{"3", 0, 0}, // missing minor
|
||||
{"", 0, 0},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
@@ -636,9 +636,9 @@ func TestEffectiveTopK(t *testing.T) {
|
||||
in int
|
||||
want int
|
||||
}{
|
||||
{0, 10}, // default
|
||||
{-5, 10}, // negative falls back to default
|
||||
{5, 5}, // normal
|
||||
{0, 10}, // default
|
||||
{-5, 10}, // negative falls back to default
|
||||
{5, 5}, // normal
|
||||
{10000, 10000},
|
||||
{50000, 10000}, // cap
|
||||
}
|
||||
@@ -992,7 +992,7 @@ func TestEnsureReady_PerDimensionIsolation(t *testing.T) {
|
||||
// errorHandler returns a configurable status code for index PUTs to
|
||||
// simulate transient (5xx) vs permanent (400) failures.
|
||||
type errorHandler struct {
|
||||
statusForIndexPut int
|
||||
statusForIndexPut int
|
||||
indexPutsAttempted atomic.Int32
|
||||
}
|
||||
|
||||
@@ -1123,34 +1123,14 @@ func TestNewRepository_AcceptsLongStoreID(t *testing.T) {
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Stub coverage — every stub returns the not-enabled sentinel
|
||||
// Stub coverage — remaining stubs return the not-enabled sentinel
|
||||
//
|
||||
// CopyIndices / BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID are now
|
||||
// implemented (see copy_bulk_test.go for their behavioral tests); their stub
|
||||
// assertions were removed. EstimateStorageSize keeps its conservative
|
||||
// lower-bound until the real _stats-based implementation lands.
|
||||
// ============================================================================
|
||||
|
||||
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{}
|
||||
|
||||
@@ -6,43 +6,12 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// This file holds the remaining stubs for methods whose real
|
||||
// implementation has not landed yet — the async / batch paths and the
|
||||
// rolling-reindex swap. Each stub returns ErrFeatureNotEnabled (or, for
|
||||
// EstimateStorageSize, a conservative lower-bound) so any accidental
|
||||
// invocation surfaces loudly. The driver as a whole is still gated dead
|
||||
// code (no registry / factory / env path mentions it); these stubs
|
||||
// disappear when their behaviours arrive in follow-up commits.
|
||||
|
||||
// CopyIndices: the async _reindex path with task polling for >10K-doc
|
||||
// batches arrives in a later change.
|
||||
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
|
||||
}
|
||||
// This file holds the remaining stubs for methods whose real implementation
|
||||
// has not landed yet — the rolling-reindex swap (swapToVersion) and the
|
||||
// precise storage estimate. CopyIndices (copy.go), BatchUpdateChunkEnabledStatus
|
||||
// and BatchUpdateChunkTagID (bulk_update.go) are now implemented. Each
|
||||
// remaining stub returns ErrFeatureNotEnabled (or, for EstimateStorageSize, a
|
||||
// conservative lower-bound) so any accidental invocation surfaces loudly.
|
||||
|
||||
// EstimateStorageSize: the real implementation that reads cluster
|
||||
// `_stats` for the per-dim alias arrives in a later change. For now we
|
||||
|
||||
@@ -12,12 +12,10 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// newOpenSearchClient builds a TLS-hardened, pool-tuned *osapi.Client for
|
||||
// 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.
|
||||
// Repository constructor itself receives the pre-built client.
|
||||
//
|
||||
// TLS posture:
|
||||
// - MinVersion: TLS 1.2 (TLS 1.3 negotiated when both ends support).
|
||||
@@ -33,7 +31,7 @@ import (
|
||||
// - IdleConnTimeout: 90s (typical LB keep-alive)
|
||||
// - ResponseHeaderTimeout: 30s (per-request safety net)
|
||||
// - ExpectContinueTimeout: 1s
|
||||
func newOpenSearchClient(cfg *types.ConnectionConfig) (*osapi.Client, error) {
|
||||
func NewOpenSearchClient(cfg *types.ConnectionConfig) (*osapi.Client, error) {
|
||||
if cfg == nil || cfg.Addr == "" {
|
||||
return nil, fmt.Errorf("opensearch: ConnectionConfig.Addr required: %w", ErrConfigInvalid)
|
||||
}
|
||||
|
||||
@@ -14,11 +14,11 @@ import (
|
||||
// transport error later.
|
||||
func TestNewOpenSearchClient_RejectsEmptyAddr(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := newOpenSearchClient(&types.ConnectionConfig{Addr: ""})
|
||||
_, err := NewOpenSearchClient(&types.ConnectionConfig{Addr: ""})
|
||||
if !errors.Is(err, ErrConfigInvalid) {
|
||||
t.Fatalf("empty addr: want ErrConfigInvalid, got %v", err)
|
||||
}
|
||||
_, err = newOpenSearchClient(nil)
|
||||
_, err = NewOpenSearchClient(nil)
|
||||
if !errors.Is(err, ErrConfigInvalid) {
|
||||
t.Fatalf("nil cfg: want ErrConfigInvalid, got %v", err)
|
||||
}
|
||||
@@ -30,13 +30,13 @@ func TestNewOpenSearchClient_RejectsEmptyAddr(t *testing.T) {
|
||||
// returns successfully.
|
||||
func TestNewOpenSearchClient_Succeeds_OnValidAddr(t *testing.T) {
|
||||
t.Parallel()
|
||||
client, err := newOpenSearchClient(&types.ConnectionConfig{
|
||||
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)
|
||||
t.Fatalf("NewOpenSearchClient: %v", err)
|
||||
}
|
||||
if client == nil {
|
||||
t.Fatal("client must be non-nil on success")
|
||||
|
||||
Reference in New Issue
Block a user