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:
ochan.kwon
2026-05-28 18:01:17 +09:00
committed by lyingbug
parent 19a1b15106
commit 40b74e2efa
35 changed files with 1781 additions and 169 deletions
+10
View File
@@ -29,6 +29,16 @@ export interface FieldSchema {
sensitive?: boolean
description?: string
default?: any
// Inclusive bounds for number fields (omitempty on the backend). When
// absent the UI falls back to per-field heuristics (isReplicaField).
min?: number
max?: number
// Closed value set for string fields (e.g. knn_engine ∈ lucene|faiss).
// When non-empty the UI renders a select instead of a free-text input.
enum?: string[]
// Marks a field that cannot change after store creation. Informational
// for now (edit mode is fully read-only); kept for forward use.
immutable?: boolean
}
// ===== API Functions =====
+6
View File
@@ -1107,11 +1107,17 @@ export default {
shards_num: 'Shards',
replica_number: 'In-memory Replicas',
desired_shard_count: 'Shard Count',
insecure_skip_verify: 'Skip TLS Verification',
hnsw_m: 'HNSW M (graph degree)',
hnsw_ef_construction: 'HNSW ef_construction',
hnsw_ef_search: 'HNSW ef_search',
knn_engine: 'k-NN Engine',
},
envTag: 'DEFAULT',
testConnection: 'Test Connection',
testing: 'Testing...',
immutableNotice: 'Engine type, connection, and index settings cannot be changed after creation.\nTo change these, delete and recreate.',
insecureSkipVerifyWarning: 'Disabling TLS certificate verification exposes the connection to man-in-the-middle attacks. Use only for self-signed development clusters — never in production.',
validation: {
nameRequired: 'Name is required',
engineTypeRequired: 'Engine type is required',
+6
View File
@@ -967,11 +967,17 @@ export default {
shards_num: "샤드 수",
replica_number: "인메모리 레플리카",
desired_shard_count: "샤드 수",
insecure_skip_verify: "TLS 인증서 검증 생략",
hnsw_m: "HNSW M (그래프 차수)",
hnsw_ef_construction: "HNSW ef_construction",
hnsw_ef_search: "HNSW ef_search",
knn_engine: "k-NN 엔진",
},
envTag: "DEFAULT",
testConnection: "연결 테스트",
testing: "테스트 중...",
immutableNotice: "엔진 타입, 연결 정보, 인덱스 설정은 생성 후 변경할 수 없습니다.\n변경이 필요하면 삭제 후 다시 생성하세요.",
insecureSkipVerifyWarning: "TLS 인증서 검증을 끄면 중간자 공격에 노출됩니다. 자체 서명 인증서를 쓰는 개발 클러스터에서만 사용하고, 운영 환경에서는 절대 사용하지 마세요.",
validation: {
nameRequired: "이름은 필수입니다",
engineTypeRequired: "엔진 타입은 필수입니다",
+6
View File
@@ -1019,11 +1019,17 @@ export default {
shards_num: 'Шарды',
replica_number: 'Реплики в памяти',
desired_shard_count: 'Количество шардов',
insecure_skip_verify: 'Пропустить проверку TLS',
hnsw_m: 'HNSW M (степень графа)',
hnsw_ef_construction: 'HNSW ef_construction',
hnsw_ef_search: 'HNSW ef_search',
knn_engine: 'Движок k-NN',
},
envTag: 'DEFAULT',
testConnection: 'Тест подключения',
testing: 'Тестирование...',
immutableNotice: 'Тип движка, подключение и настройки индекса нельзя изменить после создания.\nДля изменения удалите и создайте заново.',
insecureSkipVerifyWarning: 'Отключение проверки сертификата TLS делает соединение уязвимым для атак «человек посередине». Используйте только для dev-кластеров с самоподписанными сертификатами — никогда в продакшене.',
validation: {
nameRequired: 'Название обязательно',
engineTypeRequired: 'Тип движка обязателен',
+6
View File
@@ -965,11 +965,17 @@ export default {
shards_num: "分片数",
replica_number: "内存副本数",
desired_shard_count: "分片数",
insecure_skip_verify: "跳过 TLS 证书校验",
hnsw_m: "HNSW M(图度数)",
hnsw_ef_construction: "HNSW ef_construction",
hnsw_ef_search: "HNSW ef_search",
knn_engine: "k-NN 引擎",
},
envTag: "DEFAULT",
testConnection: "测试连接",
testing: "测试中...",
immutableNotice: "创建后无法更改引擎类型、连接和索引设置。\n如需更改,请删除后重新创建。",
insecureSkipVerifyWarning: "关闭 TLS 证书校验会使连接面临中间人攻击风险。仅可用于自签名证书的开发集群,切勿在生产环境使用。",
validation: {
nameRequired: "名称为必填项",
engineTypeRequired: "引擎类型为必填项",
@@ -165,10 +165,15 @@
:label="fieldLabel(field.name)"
:name="`connection_config.${field.name}`"
>
<t-switch
v-if="field.type === 'boolean'"
v-model="form.connection_config[field.name]"
/>
<div v-if="field.type === 'boolean'" class="boolean-field">
<t-switch v-model="form.connection_config[field.name]" />
<div
v-if="field.name === 'insecure_skip_verify' && form.connection_config[field.name]"
class="field-warning"
>
{{ t('vectorStoreSettings.insecureSkipVerifyWarning') }}
</div>
</div>
<t-input
v-else-if="field.type === 'string' && field.sensitive"
v-model="form.connection_config[field.name]"
@@ -201,12 +206,20 @@
<template v-if="showAdvanced">
<template v-for="field in selectedType.index_fields" :key="field.name">
<t-form-item :label="fieldLabel(field.name)" :name="`index_config.${field.name}`">
<!-- Closed value set → dropdown (e.g. knn_engine) -->
<t-select
v-if="field.enum && field.enum.length"
v-model="form.index_config[field.name]"
:placeholder="field.default?.toString() || ''"
>
<t-option v-for="opt in field.enum" :key="opt" :value="opt" :label="opt" />
</t-select>
<t-input-number
v-if="field.type === 'number'"
v-else-if="field.type === 'number'"
v-model="form.index_config[field.name]"
:placeholder="field.default?.toString()"
:min="1"
:max="isReplicaField(field.name) ? 10 : 64"
:min="field.min ?? 1"
:max="field.max ?? (isReplicaField(field.name) ? 10 : 64)"
theme="normal"
style="width: 100%;"
/>
@@ -861,6 +874,23 @@ onMounted(async () => {
white-space: pre-line;
}
/* Wrap switch + warning in a vertical stack so the warning sits on its own
line below the switch, independent of TDesign's form-item content flex
(which is a nowrap row — margin-top alone has no visible effect there). */
.boolean-field {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 100%;
}
.field-warning {
margin-top: 8px;
font-size: 12px;
line-height: 1.4;
color: var(--td-error-color, #d54941);
}
.readonly-fields {
padding: 10px 14px;
background: var(--td-bg-color-secondarycontainer);