diff --git a/.claude/rules/java.md b/.claude/rules/java.md index 0190192c82c9..a5f9206104fd 100644 --- a/.claude/rules/java.md +++ b/.claude/rules/java.md @@ -24,12 +24,14 @@ repository) and `common/src/main/java/org/openmetadata/common/utils/CommonUtil.j - **Methods ≤ ~15 lines** (excluding blanks/braces) and do **one nameable thing** — if you describe it with "and"/"then", split it. -- **Prefer one successful return, placed at the end.** Do not scatter multiple success and fallback - returns through a long method. Extract validation and named helpers until the main flow reads - linearly. Throwing a specific validation exception at the boundary is preferable to manufacturing - an `error` result or deeply nesting the valid path. Do not introduce a mutable `result` variable - solely to satisfy a return-count rule when a direct expression is clearer. (Returns inside lambdas, - `switch` expressions, and anonymous classes don't count against the outer method.) +- **One return per method, at the end** (ADR:2026-11-20-a-method-returns-once). A method that + returns a value computes it through `if`/`else`, a ternary or a `switch` expression and returns it + once, as its last statement. A `void` method has no `return`: put the work inside the condition + that allows it. No guard-clause `return` and no early `return` from a loop. Throwing a specific + validation exception at the boundary is allowed and is preferable to manufacturing an `error` + result. When the conditions nest past three levels, extract a named helper instead of adding + returns. (Returns inside lambdas, `switch` expression arms and anonymous classes belong to those + bodies, not the outer method.) ```java // BAD: mixed validation, fallback, and success returns QueryResult execute(String query) { @@ -44,6 +46,13 @@ repository) and `common/src/main/java/org/openmetadata/common/utils/CommonUtil.j String validatedQuery = requireSupportedQuery(query); return run(validatedQuery); } + + // BAD: void guard clauses // GOOD: the condition wraps the work + void refresh(Entity entity) { void refresh(Entity entity) { + if (!client.isAvailable()) return; if (client.isAvailable() && isStale(entity)) { + if (!isStale(entity)) return; write(entity); + write(entity); } + } } ``` - **Max 3 levels of nesting** — extract a named eligibility helper, don't sprinkle early returns. - **Max cyclomatic complexity 10** — extract complex booleans into named methods. diff --git a/AGENTS.md b/AGENTS.md index 7c1192ca53b9..d27d1de0082c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,6 +90,8 @@ check it isn't already cached a layer down (e.g. `OpenMetadata._search_es_entity **Comments explain *why*, never restate code.** Do NOT add comments that describe what obvious code does (`// Create user` before `createUser()`). Only comment complex business logic, non-obvious algorithms/workarounds, public-API JavaDoc, or `TODO/FIXME` with a ticket reference. If code needs a comment to be understood, refactor it to be clearer instead. +**One return per method, at the end (Java).** Compute the result through `if`/`else`, a ternary or a `switch` expression and return it once as the last statement; a `void` method has no `return` and puts its work inside the condition that allows it. No guard-clause or early returns; throwing a specific validation exception is allowed, and conditions nested past three levels move into a named helper. Details and examples in `.claude/rules/java.md`; rationale in ADR:2026-11-20-a-method-returns-once. + **Testing philosophy.** Test real behavior, not mock wiring — if a test mocks 3+ of your own classes to verify a method call, it tests the wrong thing. Prefer integration tests over heavily-mocked unit tests (this project has real ITs: `OpenMetadataApplicationTest`, Docker, real OpenSearch). Mocks are for boundaries (HTTP clients, third-party APIs), not internals. Ask "what breaks if this test passes but the code is wrong?" — if the answer is "nothing", rewrite it. Assert on observable outcomes (API responses, DB state), not @@ -102,8 +104,7 @@ is enforced — the `ui-license-header` pre-commit hook and CI `ui-checkstyle`; **Schema-first.** JSON Schemas in `openmetadata-spec/` are the single source of truth; all generated code (Java POJOs, Pydantic models, TS types) is derived. **Edit the schema, then regenerate — never hand-edit generated output.** Details in `.claude/rules/schema-first.md`. -**Output style.** Clean code blocks, no unnecessary explanation; assume an experienced reader; focus on functionality over education. Do not add unnecessary blank lines between -prose and code blocks. +**Output style.** Clean code blocks, no unnecessary explanation; assume an experienced reader; focus on functionality over education. Do not add unnecessary blank lines between prose and code blocks. **No wrappers around core-ui components.** If a wrapper component exists that wraps a core-ui component, skip it — use the `openmetadata-ui-core-components` component directly at the call site. Only create a wrapper if it adds genuine, non-trivial behaviour (custom hook logic, composed sub-components, domain-specific state). A wrapper that only passes props through is a maintenance liability: it hides which core component is in use and drifts from upstream updates. diff --git a/REVIEW.md b/REVIEW.md index da38d8f93a52..3d250f931479 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -649,8 +649,9 @@ Anything below is enforced by CI, or authors rejected it repeatedly in this wind - **Java micro-style quoted from [`java.md`](.claude/rules/java.md) without a defect**: fully qualified names, `final` on locals, method or class length, utility classes not `final`, literals in test assertions. These had zero acceptances across 18 bot threads. Authors still follow `java.md` while writing; a - reviewer does not post a finding for it. `java.md` says to *prefer* one successful return: - flat validation guards and throws are fine, so "use one trailing return" is not a finding. Size + reviewer does not post a finding for it. The one exception is the return rule + (ADR:2026-11-20-a-method-returns-once): a new or changed production method with more than one + `return`, or a `return` that is not its last statement, is a 🟡 finding. Throws are fine. Size rules target production code, not tests or verbatim backports. - **`@Isolated` or `@Execution(SAME_THREAD)`** on an IT that touches process-global state. That is a supported group (74 IT files use it), not a breach of the concurrent-IT rule. diff --git a/docs/decisions/2026-11-11-chunk-llm-context-lists-child-fields-under-columns.md b/docs/decisions/2026-11-11-chunk-llm-context-lists-child-fields-under-columns.md index 5c2b20f29562..e0684473d97d 100644 --- a/docs/decisions/2026-11-11-chunk-llm-context-lists-child-fields-under-columns.md +++ b/docs/decisions/2026-11-11-chunk-llm-context-lists-child-fields-under-columns.md @@ -2,7 +2,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-11 (initial) · v2 2026-11-12 (Elasticsearch topics refresh on the - next reindex, not only when edited) + next reindex, not only when edited) · v3 2026-11-20 (Elasticsearch embeds every chunk) - **Deciders:** Search and AI context maintainers - **Guard:** `VectorDocBuilderTopicFieldsTest` (topic format, chunk boundary) and `VectorDocBuilderTest` (`tableChunkText_isByteIdenticalToTheFormatBeforeTopicFields`, @@ -64,3 +64,8 @@ v2 (2026-11-12): a reindex reuses a stored embedding only when its fingerprint m `updatedAt` no longer decides (ADR:2026-11-11-reindex-reuses-an-embedding-only-when-its-fingerprint-matches). On Elasticsearch, the next Search Indexing run for `topic` re-embeds every topic with schema fields, one paid call each, without waiting for an edit. Elasticsearch still embeds chunk 0 only. +No longer true; see v3. + +v3 (2026-11-20): Elasticsearch has the chunk index and embeds every chunk +(ADR:2026-11-20-elasticsearch-and-opensearch-share-one-vector-index-service). Upgrading is the +same on both engines. Run Search Indexing for `topic`. diff --git a/docs/decisions/2026-11-11-reindex-reuses-an-embedding-only-when-its-fingerprint-matches.md b/docs/decisions/2026-11-11-reindex-reuses-an-embedding-only-when-its-fingerprint-matches.md index 33a3bed947ec..e60509488a12 100644 --- a/docs/decisions/2026-11-11-reindex-reuses-an-embedding-only-when-its-fingerprint-matches.md +++ b/docs/decisions/2026-11-11-reindex-reuses-an-embedding-only-when-its-fingerprint-matches.md @@ -1,11 +1,12 @@ # A reindex reuses a stored embedding only when its fingerprint matches - **Status:** Accepted -- **Revisions:** v1 2026-11-11 (initial) +- **Revisions:** v1 2026-11-11 (initial) · v2 2026-11-20 (both engines share the reuse lookup; + Elasticsearch embeds every chunk) - **Deciders:** Search and AI context maintainers - **Guard:** `StoredEmbeddingReuseTest`, `reindexReusesOnlyStoredEmbeddingsWhoseFingerprintIsCurrent` - in `ElasticSearchVectorServiceTest` and `OpenSearchVectorServiceTest`, `StoredEmbeddingReuseIT` - (both engines); live/reindex parity: `VectorDocBuilderTest` (custom properties) and + in `OpenSearchVectorServiceTest`, `StoredEmbeddingReuseIT` (both engines); live/reindex parity: + `VectorDocBuilderTest` (custom properties) and `MetricRepositoryTest.aReindexReadKeepsEveryInputOfTheMetricEmbeddingFingerprint` - **Related:** open-metadata/OpenMetadata#37524, open-metadata/OpenMetadata#37522, open-metadata/OpenMetadata#28313 @@ -54,9 +55,10 @@ old embedding forever: - **Upgrade cost.** The first reindex after a release that changes the fingerprinted text re-embeds exactly the entities whose text changed. Elasticsearch makes one paid call per entity - (chunk 0 only). OpenSearch makes none beyond what it already made, because the chunks were - re-embedded anyway and chunk 0 now also reaches the entity doc. Entities with unchanged text keep - their embedding. Upgrade notes for such a release must say which entity types will re-embed. + (chunk 0 only). No longer true; see the v2 amendment. OpenSearch makes none beyond what it + already made, because the chunks were re-embedded anyway and chunk 0 now also reaches the entity + doc. Entities with unchanged text keep their embedding. Upgrade notes for such a release must + say which entity types will re-embed. #37522 is such a change: the first reindex that has both re-embeds every topic with schema fields, on both engines, and no other entity type because of it. - **The first reindex with this rule also refreshes embeddings left stale by earlier releases**: @@ -86,3 +88,15 @@ old embedding forever: fingerprint itself, to be picked up. - **Revisit** if fingerprint computation shows up as a measurable share of reindex time. A cheaper key must still change when the embedding text changes. + +## Amendment + +v2 (2026-11-20): both engines run one vector index service +(ADR:2026-11-20-elasticsearch-and-opensearch-share-one-vector-index-service). + +- **One reuse lookup.** `getExistingEmbeddingsBatch` has a single implementation, so its unit + guard is the OpenSearch test alone. `StoredEmbeddingReuseIT` still runs it on both engines. +- **Elasticsearch embeds every chunk.** Where this record says Elasticsearch makes one call per + entity, or embeds chunk 0 only, it now makes one call per chunk, as OpenSearch does. The entity + doc takes chunk 0's embedding from that same call. +- **`reembed` runs on Elasticsearch.** diff --git a/docs/decisions/2026-11-20-a-method-returns-once.md b/docs/decisions/2026-11-20-a-method-returns-once.md new file mode 100644 index 000000000000..4f9a1564149c --- /dev/null +++ b/docs/decisions/2026-11-20-a-method-returns-once.md @@ -0,0 +1,31 @@ +# A Java method returns once, at the end + +- **Status:** Accepted +- **Revisions:** v1 2026-11-20 (initial) +- **Deciders:** Sriharsha Chintalapani +- **Guard:** reviewer, per the `REVIEW.md` "Do not report" exception for the return rule +- **Related:** ADR:2026-11-20-elasticsearch-and-opensearch-share-one-vector-index-service + +## Context +`.claude/rules/java.md` asked authors to *prefer* one successful return and explicitly allowed +direct early returns where a result variable felt heavier. In practice that wording let guard +clauses accumulate: the shared vector index service extracted for Elasticsearch parity carried +sixteen methods with two or three exits, `void` methods among them, and review stopped on +`updateEntityEmbedding`, which returned from two places before doing its work. A reader has to +trace every exit to know what a method does on each path, and a later edit placed after an early +return silently runs on only some of them. + +## Decision +A Java method has at most one `return`, and it is the last statement. A value-returning method +computes its result through `if`/`else`, a ternary or a `switch` expression. A `void` method has no +`return`; its work sits inside the condition that allows it. Throwing a specific exception for +invalid input is allowed. When conditions nest past three levels, the condition or the branch +moves into a named helper rather than gaining an early exit. Returns inside lambdas, `switch` +expression arms and anonymous classes belong to those bodies. + +## Consequences +Every method reads top to bottom with one exit, so code added before the `return` runs on every +path. Some methods gain a local result variable or one more `if` level; the nesting limit keeps +that bounded by pushing branches into named helpers. Existing code is not rewritten wholesale; a +change that touches a method brings it into line. Revisit if the nesting limit and this rule start +forcing helpers that exist only to satisfy each other. diff --git a/docs/decisions/2026-11-20-elasticsearch-and-opensearch-share-one-vector-index-service.md b/docs/decisions/2026-11-20-elasticsearch-and-opensearch-share-one-vector-index-service.md new file mode 100644 index 000000000000..38fed2af32fb --- /dev/null +++ b/docs/decisions/2026-11-20-elasticsearch-and-opensearch-share-one-vector-index-service.md @@ -0,0 +1,152 @@ +# Elasticsearch and OpenSearch share one vector index service + +- **Status:** Accepted +- **Revisions:** v1 2026-11-20 (initial); v2 2026-11-23 (an unwritable chunk index keeps the entity + embedding; the chunk generation goes live with the entity indexes, and only a missed delete + blocks it; the header's count bounds every stored chunk id); v3 2026-11-24 (ontology terms keep + the engine split of their own record) +- **Deciders:** Search and AI context maintainers +- **Guard:** `VectorChunkIndexIT` (each scenario on a real cluster of each engine), + `ChunkSetBoundTest` (trims and deletes after a write that stopped part way), + `ElasticSearchVectorServiceTest` (the Elasticsearch dialect and the promotion rule), + `EmbeddingEnricherTest` (the reindex embedding step and its retry), `DefaultRecreateHandlerTest` + (what an entity index tells the chunk generation), `StoredEmbeddingReuseIT` (both engines); + `reviewer` for a new caller that names an engine class +- **Related:** ADR:2026-11-11-reindex-reuses-an-embedding-only-when-its-fingerprint-matches, + ADR:2026-11-23-ontology-terms-have-dedicated-search-indexes, + ADR:2026-11-11-chunk-llm-context-lists-child-fields-under-columns, + ADR:2026-10-21-opensearch-vectors-stay-in-source + +## Context + +Semantic search had two implementations. `OpenSearchVectorService` held all of it: the chunk +index, its staged recreate during a full reindex, passage search within one entity, embedding +reuse and the `reembed` command. `ElasticSearchVectorService` copied part of it and embedded only +chunk 0 of each entity. + +Callers that needed the rest asked for `OpenSearchVectorService.getInstance()`, which is null on +Elasticsearch. With semantic search enabled on Elasticsearch: + +- `reembed` reported that embeddings were disabled and exited 1. +- AI context never excerpted a long knowledge item by relevance to the query. It always returned + the structural preview. The MCP `get_entity` tool returned the full body instead of passages. +- Text beyond an entity's first chunk was never embedded, and a full reindex had no chunk index to + rebuild. + +## Decision + +- **One implementation.** `AbstractVectorIndexService` holds every behaviour that does not depend + on the engine. It talks to the cluster through REST JSON only. +- **An engine class supplies its dialect and nothing else**: how to send a request, the chunk index + settings, the mapping of the embedding field and the kNN search body. OpenSearch maps + `knn_vector`. Elasticsearch maps `dense_vector` with cosine similarity and searches with a + top-level `knn` clause. +- **Callers get the service from `SearchRepository.getVectorIndexService()`.** Only + `SearchRepository.initializeVectorSearchService` names an engine class. + `OpenSearchVectorService.getInstance()` stays for downstream code compiled against it. Code in + this repository does not call it. +- **Elasticsearch has the same index layout as OpenSearch.** Chunk documents live in + `data_asset_embeddings_chunks`, are read through the `dataAssetEmbeddings` alias together with + the entity indexes, and are rebuilt by a full reindex in a staged generation + (`data_asset_embeddings_chunks_g`) that replaces the previous one in a single alias swap. +- **The reindex embedding step is shared** (`EmbeddingEnricher`) and behaves as it did on + OpenSearch. +- **A stored vector is read by naming its field.** On Elasticsearch 9.3.0 a new index has + `index.mapping.exclude_source_vectors=true`, so `_source` carries a `dense_vector` only when the + request lists that field. Every read that reuses a stored vector goes through one multi-get that + lists `embedding` in `_source_includes`. The chunk index keeps the Elasticsearch default, as the + entity indexes do. OpenSearch keeps vectors in stored source + (ADR:2026-10-21-opensearch-vectors-stay-in-source). +- **A chunk index that cannot be written never costs an entity its document embedding.** A live + edit refreshes only a stale entity-doc embedding and skips the chunk write. A reindex keeps the + spliced embedding and logs the chunk failure. No raw chunk write goes to a missing index. +- **The chunk generation goes live with the entity indexes.** The entity indexes follow the + platform rule of `DefaultRecreateHandler`: a staged index with data is promoted, because partial + data is better than none. Once every vector-indexable type has finalized, the staged chunk + generation is promoted when all their staged entity indexes were. A type whose entity index kept + its live index (it received no documents, or its swap failed) keeps the live chunks for the + whole catalog, so a type never loses its chunks while its old entities are still served. An + empty generation never replaces a live index that holds chunks, and a count that cannot be read + keeps the live index. A run whose embedding pre-flight call fails stages no generation, so the + live chunks stay: an entity edited while the provider was out keeps its old chunks live, and its + entity document has no embedding until a provider call works again, on the retry at the end of + its partition or on a later run. +- **A missed chunk write never blocks promotion.** When the run cannot write an entity's chunks + (the provider fails, its circuit is open, the cluster rejects the bulk, or a live edit's mirror + fails), the entity keeps its document embedding and the miss is recorded on that node. An entity + the run embeds afresh has no embedding yet, so the provider failing it records the same miss and + the entity is indexed without one. When the partition that missed the entity finishes and its + writes are flushed, the node retries it once, writing both the entity document's embedding and + the chunks when both were missed, and skipping the retry while the provider's circuit is open. + Another partition of the same type never retries it, because the entity's document may not be + written yet. The entity then counts as one vector success, or one vector failure if its chunks + are still missing. Each node logs one summary warning per run, and the detail per entity at + debug. An entity left without chunks gets them on its next edit or + reindex, through the fingerprint-guarded backfill. A missed mirror is not retried; it heals the + same way. +- **Only a missed delete blocks promotion.** A delete that fails in the staged generation would + bring a removed entity's chunks back, so it sets `_meta.incompleteChunkWrites` on that + generation's index. A node saves the flag once per generation. The coordinator reads it before + the alias swap and keeps the old chunks live when it is set; the next staged recreate sweeps the + unpromoted generation. The flag lives on the cluster, so a participant's failure reaches the + coordinator. A node that cannot save the flag retries it when its partition ends and, if it + still cannot, fails the partition for good, without a retry, with an error that starts with + `VectorIndexService.UNRECORDED_STAGED_DELETE`. A retry on another node could not repair the + missed delete, and nothing rewrites a FAILED row, so the error stays for the rest of the job. + Whenever a type finishes, the coordinator reads that error from the job's failed partitions and + counts the type as keeping its live chunks. Keeping live chunks wins over a later promotion of + the same type, so no callback can undo it. The type's entity index still promotes its partial + data, and the run ends with errors. A delete that + fails after the coordinator reads the flag misses the generation, and the deleted entity's + chunks stay in it until the next full recreate. +- **A live edit refreshes the entity document even when its chunk write fails.** Chunk 0 + carries the header the next update compares against, so it is written in its own request + after every other chunk and delete succeeded. A failed write leaves the old header, and the + entity's next update writes the chunks again. +- **The header's `chunkCount` bounds every chunk id stored for the entity.** Trims and deletes + go by id up to that count, so they reach writes no refresh has made searchable yet. A write + that adds ids past the count first writes chunk 0 with the new count and no fingerprint. A + write that then stops part way leaves a header that covers every id it wrote and that no + update reads as current. Only a write that grows the set pays that extra request. +- **A delete removes every chunk of the entity**, in the live index and in a staged generation: + by id up to the header's count, then by a query on `parentId` for anything a header that was + missing or behind did not cover, and chunk 0 last, so a delete that stops part way keeps the + count for its retry. That query costs one delete-by-query per entity delete; writes never run + one unless chunks are stored without a header. A delete sends nothing to a chunk index that + does not exist yet. +- **Ontology terms keep the layout their own record gives them.** + ADR:2026-11-23-ontology-terms-have-dedicated-search-indexes keeps their chunks in + `ontology_embeddings_chunks` on OpenSearch and their vectors on the term documents on + Elasticsearch, and only OpenSearch sweeps stale ontology chunks. The base class keeps that split + behind one hook, `chunksOntologyTerms`. Ontology terms are never part of the data-asset chunk + generation: its expected types are `AvailableEntityTypes.DATA_ASSET_CHUNK_TYPES`. +- **Hybrid search stays OpenSearch-only.** The RRF search pipeline lives in + `OpenSearchVectorService`, and `SearchRepository` creates and checks it only on OpenSearch. + +## Consequences + +- **A capability added to `VectorIndexService` exists on both engines.** An engine difference is a + new hook on the base class, not a second copy of the logic. +- **OpenSearch sends the same requests, creates the same mappings and retries the same way**, + with one exception. An unwritable chunk index now keeps the entity embedding instead of + dropping it. +- **A rebuild costs an entity its chunks only until that entity is written again.** A + generation promoted with misses lacks those entities' passages; the run's vector failures and + each node's summary warning name how many. A rebuild is kept from going live only by a missed + delete or by an entity index that kept its live index. +- **Upgrade cost on Elasticsearch.** No chunk documents exist before this change. The first + Search Indexing run after the upgrade creates the chunk index and embeds every chunk of each + vector-indexable entity it covers, one provider call per chunk. That includes entities whose + entity-document embedding is reused. Later runs reuse the stored chunk vectors of every entity + an earlier run embedded. +- **Before that run**, semantic search keeps reading the entity-document embeddings through the + alias. Passage search returns nothing for an entity that has not been edited since the upgrade, + so AI context and `get_entity` fall back as they did before. +- **A read that fetches whole documents gets no vector on Elasticsearch.** The reuse then embeds + the text again. That costs provider calls and shows only as an info log, so `VectorChunkIndexIT` + counts the provider calls of a recreate. +- **Elasticsearch stores more.** Every chunk is a document with its own vector. Not measured. +- **A provider outage during a reindex** indexes the entity without an embedding and counts a + vector failure, on both engines. The next reindex adds the embedding. +- **Revisit** when hybrid search is wanted on Elasticsearch. It needs its own retrieval request, + which belongs behind a hook like the kNN search body. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenSearchVectorReaderIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenSearchVectorReaderIT.java index 7b6e8235bb19..38ae0bdddff6 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenSearchVectorReaderIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenSearchVectorReaderIT.java @@ -167,7 +167,7 @@ void embeddingUpdatesSurviveConcurrentReaderRelease(boolean chunks) throws Excep private String createIndex(OpenSearchVectorService vectorService, boolean chunks) throws IOException { if (chunks) { - vectorService.writeEntityChunks("seed", List.of()); + vectorService.writeEntityChunks("seed", List.of(), null); return vectorService.getChunkIndexName(); } final String index = new TestNamespace("vector_reader").prefix("test_case_search_index"); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/VectorChunkIndexIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/VectorChunkIndexIT.java new file mode 100644 index 000000000000..206708bb0d4d --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/VectorChunkIndexIT.java @@ -0,0 +1,572 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import es.co.elastic.clients.elasticsearch.ElasticsearchClient; +import es.co.elastic.clients.json.jackson.JacksonJsonpMapper; +import es.co.elastic.clients.transport.rest5_client.Rest5ClientTransport; +import es.co.elastic.clients.transport.rest5_client.low_level.Rest5Client; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.apache.hc.core5.http.HttpHost; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.search.vector.AbstractVectorIndexService; +import org.openmetadata.service.search.vector.ElasticSearchVectorService; +import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorDocBuilder; +import org.openmetadata.service.search.vector.VectorSearchParameters; +import org.openmetadata.service.search.vector.client.EmbeddingClient; +import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; +import org.opensearch.testcontainers.OpensearchContainer; +import org.testcontainers.elasticsearch.ElasticsearchContainer; +import org.testcontainers.utility.DockerImageName; +import os.org.opensearch.client.opensearch.OpenSearchClient; +import os.org.opensearch.client.transport.httpclient5.ApacheHttpClient5TransportBuilder; + +/** + * The chunk index is one implementation for both engines, and an engine supplies only its request + * dialect. A mocked transport cannot tell whether a real engine accepts that dialect, so each + * scenario runs here against OpenSearch and against Elasticsearch. The scenarios of one engine + * share its cluster and its staged-recreate state, so they run one at a time. + */ +class VectorChunkIndexIT { + + private static final String QUESTION = "which table holds online orders"; + + /** Returns one vector for any text and counts the texts it is asked to embed. */ + private static final class CountingProvider extends EmbeddingClient { + private final AtomicInteger textsEmbedded = new AtomicInteger(); + private volatile boolean failing; + + @Override + protected float[] doEmbed(String text) { + if (failing) { + throw new IllegalStateException("provider rate limit"); + } + textsEmbedded.incrementAndGet(); + return new float[] {0.5f, 0.25f, 0.125f}; + } + + void failing(boolean failing) { + this.failing = failing; + } + + @Override + public int getDimension() { + return 3; + } + + @Override + public String getModelId() { + return "vector-chunk-index"; + } + + int textsEmbedded() { + return textsEmbedded.get(); + } + } + + @Nested + @TestInstance(TestInstance.Lifecycle.PER_CLASS) + @Execution(ExecutionMode.SAME_THREAD) + class OnOpenSearch { + private final CountingProvider provider = new CountingProvider(); + private final OpensearchContainer container = + new OpensearchContainer<>(DockerImageName.parse("opensearchproject/opensearch:3.4.0")) + .withStartupTimeout(Duration.ofMinutes(5)) + .withEnv("DISABLE_SECURITY_PLUGIN", "true") + .withEnv("DISABLE_INSTALL_DEMO_CONFIG", "true") + .withEnv("OPENSEARCH_INITIAL_ADMIN_PASSWORD", "Test@12345") + .withEnv("OPENSEARCH_JAVA_OPTS", "-Xms512m -Xmx512m"); + private OpenSearchClient client; + private OpenSearchVectorService service; + + @BeforeAll + void start() { + container.start(); + HttpHost host = new HttpHost("http", container.getHost(), container.getMappedPort(9200)); + client = + new OpenSearchClient( + ApacheHttpClient5TransportBuilder.builder(host) + .setHttpClientConfigCallback(builder -> builder.disableContentCompression()) + .build()); + service = new OpenSearchVectorService(client, provider); + } + + @AfterAll + void stop() throws Exception { + client._transport().close(); + container.stop(); + } + + @Test + void aFullRecreateServesOnlyTheEntitiesItIndexed() { + assertAFullRecreateServesOnlyTheEntitiesItIndexed(service, provider); + } + + @Test + void aMissedChunkWriteStillPromotesAndTheNextWriteHealsIt() { + assertAMissedChunkWriteStillPromotesAndTheNextWriteHealsIt(service); + } + + @Test + void aProviderOutageOnAFirstRebuildStillPromotes() { + assertAProviderOutageOnAFirstRebuildStillPromotes(service, provider); + } + + @Test + void aFailedDeleteKeepsTheLiveChunks() { + assertAFailedDeleteKeepsTheLiveChunks(service); + } + + @Test + void aGrowthWhoseHeaderFailedLeavesNoChunkBehind() { + assertAGrowthWhoseHeaderFailedLeavesNoChunkBehind(service); + } + + @Test + void aRetriedEmbeddingMergesIntoTheIndexedEntityDocument() { + assertARetriedEmbeddingMergesIntoTheIndexedEntityDocument(service); + } + } + + @Nested + @TestInstance(TestInstance.Lifecycle.PER_CLASS) + @Execution(ExecutionMode.SAME_THREAD) + class OnElasticsearch { + private final CountingProvider provider = new CountingProvider(); + private final ElasticsearchContainer container = + new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:9.3.0") + .withEnv("discovery.type", "single-node") + .withEnv("xpack.security.enabled", "false") + .withEnv("ES_JAVA_OPTS", "-Xms512m -Xmx512m") + .withStartupTimeout(Duration.ofMinutes(5)); + private Rest5Client restClient; + private ElasticSearchVectorService service; + + @BeforeAll + void start() { + container.start(); + restClient = + Rest5Client.builder( + new HttpHost("http", container.getHost(), container.getMappedPort(9200))) + .setHttpClientConfigCallback(builder -> builder.disableContentCompression()) + .build(); + service = + new ElasticSearchVectorService( + new ElasticsearchClient( + new Rest5ClientTransport(restClient, new JacksonJsonpMapper())), + provider); + } + + @AfterAll + void stop() throws Exception { + restClient.close(); + container.stop(); + } + + @Test + void aFullRecreateServesOnlyTheEntitiesItIndexed() { + assertAFullRecreateServesOnlyTheEntitiesItIndexed(service, provider); + } + + @Test + void aMissedChunkWriteStillPromotesAndTheNextWriteHealsIt() { + assertAMissedChunkWriteStillPromotesAndTheNextWriteHealsIt(service); + } + + @Test + void aProviderOutageOnAFirstRebuildStillPromotes() { + assertAProviderOutageOnAFirstRebuildStillPromotes(service, provider); + } + + @Test + void aFailedDeleteKeepsTheLiveChunks() { + assertAFailedDeleteKeepsTheLiveChunks(service); + } + + @Test + void aGrowthWhoseHeaderFailedLeavesNoChunkBehind() { + assertAGrowthWhoseHeaderFailedLeavesNoChunkBehind(service); + } + + @Test + void aRetriedEmbeddingMergesIntoTheIndexedEntityDocument() { + assertARetriedEmbeddingMergesIntoTheIndexedEntityDocument(service); + } + } + + /** + * A full recreate writes into a staged generation and swaps it in once every entity type has + * finished. An entity whose text is unchanged keeps its stored vectors, so it costs no provider + * call. An entity the run did not index was deleted without a delete event, so its chunks go with + * the generation the swap removes. + */ + private static void assertAFullRecreateServesOnlyTheEntitiesItIndexed( + AbstractVectorIndexService service, CountingProvider provider) { + Table embeddedAgain = table("orders", "Orders placed online"); + Table unchanged = table("customers", "Customers who ordered"); + Table deletedWithoutAnEvent = table("refunds", "Refunds issued"); + List seeded = List.of(embeddedAgain, unchanged, deletedWithoutAnEvent); + seeded.forEach(table -> writeChunks(service, table, null)); + refresh(service, service.getChunkIndexName()); + assertOnePassage(service, deletedWithoutAnEvent, "Refunds issued"); + assertEquals(ids(seeded), parentsFound(service)); + + String staged = service.beginStagedChunkRecreate(); + assertNotNull(staged, "A reachable embedding provider stages a generation"); + writeChunks(service, embeddedAgain, staged); + int embeddedBeforeTheCopy = provider.textsEmbedded(); + service.backfillEntityChunks(unchanged, staged); + assertEquals( + embeddedBeforeTheCopy, + provider.textsEmbedded(), + "The stored vectors of an unchanged entity are copied, not embedded again"); + refresh(service, staged); + assertEquals(ids(seeded), parentsFound(service), "Reads keep the old chunks until the swap"); + + AvailableEntityTypes.SET.forEach(type -> service.markEntityTypeReindexed(type, true, staged)); + + assertEquals(ids(List.of(embeddedAgain, unchanged)), parentsFound(service)); + assertOnePassage(service, embeddedAgain, "Orders placed online"); + assertOnePassage(service, unchanged, "Customers who ordered"); + assertEquals( + List.of(), service.searchChunksByParent(id(deletedWithoutAnEvent), QUESTION, 5, null)); + assertEquals( + Set.of(service.getChunkIndexName(), service.getIndexAlias()), aliasesOf(service, staged)); + } + + /** + * The cluster rejects one entity's chunk bulk while every entity index is promoted. The miss is + * reported to the caller, the generation still goes live with the entity indexes, and the + * entity's next chunk write gives it its chunks again. + */ + private static void assertAMissedChunkWriteStillPromotesAndTheNextWriteHealsIt( + AbstractVectorIndexService service) { + Table invoices = table("invoices", "Invoices sent"); + Table payments = table("payments", "Payments received"); + try { + writeChunks(service, invoices, null); + refresh(service, service.getChunkIndexName()); + + String staged = service.beginStagedChunkRecreate(); + assertNotNull(staged, "A reachable embedding provider stages a generation"); + writeChunks(service, payments, staged); + assertFalse( + service.writeEntityChunks(id(invoices), unindexableChunks(service, invoices), staged), + "The caller is told about the miss"); + refresh(service, staged); + AvailableEntityTypes.SET.forEach(type -> service.markEntityTypeReindexed(type, true, staged)); + + assertEquals( + Set.of(service.getChunkIndexName(), service.getIndexAlias()), aliasesOf(service, staged)); + assertEquals(Set.of(id(payments)), parentsFound(service)); + + writeChunks(service, invoices, null); + refresh(service, service.getChunkIndexName()); + assertOnePassage(service, invoices, "Invoices sent"); + } finally { + service.deleteEntityChunks(id(invoices)); + service.deleteEntityChunks(id(payments)); + refresh(service, service.getChunkIndexName()); + } + } + + /** + * A first rebuild on a catalog with no chunks yet: the provider fails for one entity, which had + * nothing live to lose, so the generation still goes live with every other entity's chunks. + */ + private static void assertAProviderOutageOnAFirstRebuildStillPromotes( + AbstractVectorIndexService service, CountingProvider provider) { + Table carriers = table("carriers", "Carriers we ship with"); + Table shipments = table("shipments", "Shipments in transit"); + try { + String staged = service.beginStagedChunkRecreate(); + assertNotNull(staged, "A reachable embedding provider stages a generation"); + writeChunks(service, carriers, staged); + provider.failing(true); + assertFalse(service.backfillEntityChunks(shipments, staged), "The miss is reported"); + provider.failing(false); + refresh(service, staged); + AvailableEntityTypes.SET.forEach(type -> service.markEntityTypeReindexed(type, true, staged)); + + assertEquals( + Set.of(service.getChunkIndexName(), service.getIndexAlias()), aliasesOf(service, staged)); + assertEquals(Set.of(id(carriers)), parentsFound(service)); + } finally { + provider.failing(false); + service.deleteEntityChunks(id(carriers)); + service.deleteEntityChunks(id(shipments)); + refresh(service, service.getChunkIndexName()); + } + } + + /** + * An entity is deleted while a rebuild runs, and the delete from the staged generation fails. The + * generation would bring the deleted entity's chunks back, so it is flagged and never promoted; + * the live chunks, from which the entity is already gone, stay. + */ + private static void assertAFailedDeleteKeepsTheLiveChunks(AbstractVectorIndexService service) { + Table orders = table("orders", "Orders placed online"); + Table refunds = table("refunds", "Refunds issued"); + String staged = null; + try { + writeChunks(service, orders, null); + writeChunks(service, refunds, null); + refresh(service, service.getChunkIndexName()); + Set liveAfterTheDelete = new HashSet<>(parentsFound(service)); + liveAfterTheDelete.remove(id(refunds)); + staged = service.beginStagedChunkRecreate(); + assertNotNull(staged, "A reachable embedding provider stages a generation"); + writeChunks(service, orders, staged); + writeChunks(service, refunds, staged); + refresh(service, staged); + writeBlock(service, staged, true); + + service.deleteEntityChunks(id(refunds)); + refresh(service, service.getChunkIndexName()); + String generation = staged; + AvailableEntityTypes.SET.forEach( + type -> service.markEntityTypeReindexed(type, true, generation)); + + assertEquals(Set.of(), aliasesOf(service, staged), "The generation is not promoted"); + assertEquals(liveAfterTheDelete, parentsFound(service), "The live chunks stay"); + assertTrue(missedDeleteFlag(service, staged), "The generation is flagged"); + } finally { + if (staged != null) { + writeBlock(service, staged, false); + } + service.deleteEntityChunks(id(orders)); + service.deleteEntityChunks(id(refunds)); + refresh(service, service.getChunkIndexName()); + } + } + + /** + * An entity grows from one chunk to three and the write of its header fails, so chunks 1 and 2 + * are stored past the count the old header recorded. A shrink back to one chunk keeps only chunk + * 0, and a delete of the entity leaves none, in the live index and in a staged generation. Stored + * ids are read in real time, so no refresh hides a chunk left behind. + */ + private static void assertAGrowthWhoseHeaderFailedLeavesNoChunkBehind( + AbstractVectorIndexService service) { + Table orders = table("orders", "Orders placed online"); + String live = service.getChunkIndexName(); + String staged = null; + try { + staged = service.beginStagedChunkRecreate(); + assertNotNull(staged, "A reachable embedding provider stages a generation"); + for (String target : Arrays.asList(null, staged)) { + String index = target == null ? live : target; + growWithTheHeaderFailing(service, orders, target, index); + writeChunks(service, orders.withDescription("Orders placed online"), target); + assertEquals(Set.of(id(orders) + "_0"), storedChunkIds(service, index, orders)); + growWithTheHeaderFailing(service, orders, target, index); + } + + service.deleteEntityChunks(id(orders)); + + assertEquals(Set.of(), storedChunkIds(service, live, orders)); + assertEquals(Set.of(), storedChunkIds(service, staged, orders)); + } finally { + if (staged != null) { + service.clearStagedChunkState(staged); + } + // Refreshed first, so the delete's query also reaches what a failed assertion left behind. + refresh(service, live); + service.deleteEntityChunks(id(orders)); + refresh(service, live); + } + } + + /** + * A reindex that could not embed an entity indexes its document without an embedding and retries + * it when the partition ends. The retry merges chunk 0's embedding fields into that document, so + * the entity ends as a first attempt that succeeded would have left it. A document the bulk never + * indexed is reported as a miss, not created. + */ + private static void assertARetriedEmbeddingMergesIntoTheIndexedEntityDocument( + AbstractVectorIndexService service) { + Table orders = table("orders", "Orders placed online"); + String entityIndex = "table_search_index_retry"; + String document = "/" + entityIndex + "/_doc/" + id(orders); + try { + service.executeGenericRequest( + "PUT", document + "?refresh=true", JsonUtils.pojoToJson(Map.of("name", "orders"))); + Map fields = + VectorDocBuilder.legacyEmbeddingFields( + VectorDocBuilder.fromEntity(orders, service.getEmbeddingClient()).getFirst()); + + assertTrue(service.writeEntityEmbedding(entityIndex, id(orders), fields)); + JsonNode source = + JsonUtils.readTree( + service.executeGenericRequest( + "GET", document + "?_source_includes=name,fingerprint,embedding", null)) + .path("_source"); + assertEquals("orders", source.path("name").asText()); + assertEquals( + VectorDocBuilder.computeFingerprintForEntity(orders), + source.path("fingerprint").asText()); + assertEquals(3, source.path("embedding").size()); + assertFalse( + service.writeEntityEmbedding(entityIndex, UUID.randomUUID().toString(), fields), + "A document the bulk never indexed is a miss"); + } finally { + service.executeGenericRequest("DELETE", "/" + entityIndex, null); + } + } + + private static void growWithTheHeaderFailing( + AbstractVectorIndexService service, Table table, String target, String index) { + writeChunks(service, table.withDescription("Orders placed online"), target); + List> threeChunks = + VectorDocBuilder.fromEntity( + table.withDescription("word ".repeat(940)), service.getEmbeddingClient()); + assertEquals(3, threeChunks.size(), "The description spans three chunks"); + List> brokenHeader = new ArrayList<>(threeChunks); + brokenHeader.set(0, withUnindexableFingerprint(threeChunks.getFirst())); + + assertFalse( + service.writeEntityChunks(id(table), brokenHeader, target), "The header write fails"); + assertEquals( + Set.of(id(table) + "_0", id(table) + "_1", id(table) + "_2"), + storedChunkIds(service, index, table), + "Chunks 1 and 2 are stored past the old count"); + } + + // A keyword field holding an object fails that bulk item on both engines. The reservation that + // precedes the other chunks carries no fingerprint, so only the final header fails. + private static Map withUnindexableFingerprint(Map chunk) { + Map broken = new HashMap<>(chunk); + broken.put("fingerprint", Map.of("not", "a keyword")); + return broken; + } + + // A multi-get is real time, so it sees writes no refresh has made searchable yet. + private static Set storedChunkIds( + AbstractVectorIndexService service, String index, Table table) { + List ids = IntStream.range(0, 5).mapToObj(i -> id(table) + "_" + i).toList(); + JsonNode docs = + JsonUtils.readTree( + service.executeGenericRequest( + "POST", + "/" + index + "/_mget?_source=false", + JsonUtils.pojoToJson(Map.of("ids", ids)))) + .path("docs"); + Set stored = new HashSet<>(); + docs.forEach( + doc -> { + if (doc.path("found").asBoolean(false)) { + stored.add(doc.path("_id").asText()); + } + }); + return stored; + } + + private static void writeBlock(AbstractVectorIndexService service, String index, boolean on) { + service.executeGenericRequest( + "PUT", "/" + index + "/_settings", "{\"index.blocks.write\":" + on + "}"); + } + + private static boolean missedDeleteFlag(AbstractVectorIndexService service, String index) { + return JsonUtils.readTree(service.executeGenericRequest("GET", "/" + index + "/_mapping", null)) + .path(index) + .path("mappings") + .path("_meta") + .path("incompleteChunkWrites") + .asBoolean(false); + } + + // An integer field holding text fails that bulk item on both engines. + private static List> unindexableChunks( + AbstractVectorIndexService service, Table table) { + return VectorDocBuilder.fromEntity(table, service.getEmbeddingClient()).stream() + .map(VectorChunkIndexIT::withTextChunkCount) + .toList(); + } + + private static Map withTextChunkCount(Map chunk) { + Map broken = new HashMap<>(chunk); + broken.put("chunkCount", "not a number"); + return broken; + } + + private static void writeChunks( + AbstractVectorIndexService service, Table table, String stagedChunkTarget) { + service.writeEntityChunks( + id(table), + VectorDocBuilder.fromEntity(table, service.getEmbeddingClient()), + stagedChunkTarget); + } + + // The service does not refresh after a write, so the scenario does before it reads. + private static void refresh(AbstractVectorIndexService service, String index) { + service.executeGenericRequest("POST", "/" + index + "/_refresh", null); + } + + private static void assertOnePassage( + AbstractVectorIndexService service, Table parent, String description) { + List passages = service.searchChunksByParent(id(parent), QUESTION, 5, null); + + assertEquals(1, passages.size(), passages::toString); + assertTrue(passages.getFirst().contains(description), passages::toString); + } + + private static Set parentsFound(AbstractVectorIndexService service) { + VectorSearchParameters anyTen = + new VectorSearchParameters(QUESTION, Map.of(), 10, 0, 10, 0.0, null, null, null); + return service.search(anyTen).getHits().stream() + .map(hit -> (String) hit.get("parentId")) + .collect(Collectors.toSet()); + } + + private static Set aliasesOf(AbstractVectorIndexService service, String index) { + JsonNode aliases = + JsonUtils.readTree(service.executeGenericRequest("GET", "/" + index + "/_alias", null)) + .path(index) + .path("aliases"); + Set names = new HashSet<>(); + aliases.fieldNames().forEachRemaining(names::add); + return names; + } + + private static Table table(String name, String description) { + return new Table() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName("svc.db.schema." + name) + .withDescription(description) + .withDeleted(false) + .withUpdatedAt(1_700_000_000_000L); + } + + private static String id(Table table) { + return table.getId().toString(); + } + + private static Set ids(List
tables) { + return tables.stream().map(VectorChunkIndexIT::id).collect(Collectors.toSet()); + } +} diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java index 59042e0cf1c5..c98c499c16ce 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java @@ -33,7 +33,6 @@ import org.openmetadata.service.jdbi3.LineageRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.lineage.LineagePermissionFilter; -import org.openmetadata.service.search.vector.OpenSearchVectorService; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.auth.CatalogSecurityContext; import org.openmetadata.service.security.mask.PIIMasker; @@ -452,7 +451,8 @@ private static boolean masksTestCaseContent(IncludeContext ctx) { * caller then gets the full body rather than nothing. */ private static List passages(IncludeContext ctx, String query) { - return OpenSearchVectorService.getInstance() + return Entity.getSearchRepository() + .getVectorIndexService() .searchChunksByParent( ctx.entity().getId().toString(), query, @@ -468,7 +468,7 @@ private static Object renderText(IncludeContext ctx, String text) { private static boolean vectorSearchEnabled() { return Entity.getSearchRepository().isVectorEmbeddingEnabled() - && OpenSearchVectorService.getInstance() != null; + && Entity.getSearchRepository().getVectorIndexService() != null; } /** Runs one include section, converting a failure into a note instead of losing the whole read. */ diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/GetEntityToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/GetEntityToolTest.java index 346313faa020..abd4b10c2183 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/GetEntityToolTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/GetEntityToolTest.java @@ -61,7 +61,7 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.search.SearchRepository; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.secrets.masker.PasswordEntityMasker; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; @@ -451,12 +451,12 @@ void testCaseContentUsesTheLinkedColumnPolicyBeforePassageRetrieval( when(authorizer.authorizePII(context, List.of())).thenReturn(authorized); SearchRepository repository = mock(SearchRepository.class); when(repository.isVectorEmbeddingEnabled()).thenReturn(true); - OpenSearchVectorService vector = mock(OpenSearchVectorService.class); + VectorIndexService vector = mock(VectorIndexService.class); when(vector.searchChunksByParent(anyString(), anyString(), anyInt(), any())) .thenReturn(List.of("Passage details")); + when(repository.getVectorIndexService()).thenReturn(vector); try (MockedStatic entities = mockStatic(Entity.class); - MockedStatic subjects = mockStatic(DefaultAuthorizer.class); - MockedStatic vectors = mockStatic(OpenSearchVectorService.class)) { + MockedStatic subjects = mockStatic(DefaultAuthorizer.class)) { entities .when(() -> Entity.getEntityByName(eq(Entity.TEST_CASE), eq(fqn), anyString(), any())) .thenReturn(testCase); @@ -470,7 +470,6 @@ void testCaseContentUsesTheLinkedColumnPolicyBeforePassageRetrieval( subjects .when(() -> DefaultAuthorizer.getSubjectContext(context)) .thenReturn(new SubjectContext(new User().withName("alice"), null, null)); - vectors.when(OpenSearchVectorService::getInstance).thenReturn(vector); Map result = new GetEntityTool() .execute( @@ -548,15 +547,15 @@ private static Map readMemoryContentWithQuery( String fqn = "alices-private-note"; ContextMemory memory = privateMemoryOwnedBy("alice", fqn); CatalogSecurityContext securityContext = securityContextFor("alice"); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); + VectorIndexService vectorService = mock(VectorIndexService.class); SearchRepository searchRepository = mock(SearchRepository.class); when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); when(vectorService.searchChunksByParent(memory.getId().toString(), "retention", 2, caller)) .thenReturn(passages); try (MockedStatic entities = mockStatic(Entity.class); - MockedStatic subjects = mockStatic(DefaultAuthorizer.class); - MockedStatic vectors = mockStatic(OpenSearchVectorService.class)) { + MockedStatic subjects = mockStatic(DefaultAuthorizer.class)) { entities .when( () -> @@ -565,7 +564,6 @@ private static Map readMemoryContentWithQuery( .thenReturn(memory); entities.when(Entity::getSearchRepository).thenReturn(searchRepository); subjects.when(() -> DefaultAuthorizer.getSubjectContext(securityContext)).thenReturn(caller); - vectors.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); return new GetEntityTool() .execute( diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SemanticSearchToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SemanticSearchToolTest.java index 1ae8513bccbb..e4dd5b263eba 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SemanticSearchToolTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SemanticSearchToolTest.java @@ -32,7 +32,7 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.service.Entity; import org.openmetadata.service.search.SearchRepository; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.search.vector.VectorSearchParameters; import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; import org.openmetadata.service.security.Authorizer; @@ -48,7 +48,7 @@ class SemanticSearchToolTest { private Authorizer authorizer; private CatalogSecurityContext securityContext; private SearchRepository searchRepository; - private OpenSearchVectorService vectorService; + private VectorIndexService vectorService; private final List knownMetrics = new ArrayList<>(); private final List requestedMetricNames = new ArrayList<>(); @@ -65,7 +65,7 @@ void setUp() { authorizer = mock(Authorizer.class); securityContext = mock(CatalogSecurityContext.class); searchRepository = mock(SearchRepository.class); - vectorService = mock(OpenSearchVectorService.class); + vectorService = mock(VectorIndexService.class); Entity.setSearchRepository(searchRepository); lenient().when(searchRepository.getVectorIndexService()).thenReturn(vectorService); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java index 368b7c2b8e3e..52abdd4527c1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java @@ -79,7 +79,7 @@ import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.TableRepository; import org.openmetadata.service.resources.context.ContextMemoryVisibility; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; @@ -324,7 +324,7 @@ private SubjectContext subjectContextOrNull() { private String queryRelevantExcerpt(KnowledgeItem item, int limit) { String result = null; try { - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + VectorIndexService vectorService = Entity.getSearchRepository().getVectorIndexService(); if (item.getType() != null && vectorService != null && Entity.getSearchRepository().isVectorEmbeddingEnabled()) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java index 2b7770b0943c..5eed043d8182 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java @@ -3,6 +3,7 @@ import java.util.List; import java.util.Map; import org.openmetadata.schema.system.StepStats; +import org.openmetadata.service.apps.bundles.searchIndex.stats.StageStatsTracker; public interface BulkSink { void write(List entities, Map contextData) throws Exception; @@ -65,6 +66,13 @@ default StepStats getVectorStats() { return null; } + /** + * Retries once the embeddings and chunk documents this sink missed for the partition tracked by + * {@code partition}, and counts each in the vector stats. Called once that partition's writes are + * flushed and before it completes. + */ + default void retryMissedChunks(StageStatsTracker partition) {} + /** * Returns the process stage statistics. This tracks document building/transformation * separately from the actual sink (bulk indexing) stats. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java index 2a59f981da2b..9b58bfac94e7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import es.co.elastic.clients.elasticsearch.ElasticsearchAsyncClient; import es.co.elastic.clients.elasticsearch._types.Refresh; import es.co.elastic.clients.elasticsearch._types.ScriptLanguage; @@ -46,7 +45,6 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.EntityTimeSeriesInterface; @@ -69,10 +67,6 @@ import org.openmetadata.service.search.indexes.ColumnSearchIndex; import org.openmetadata.service.search.indexes.DocBuildContext; import org.openmetadata.service.search.indexes.SearchIndex; -import org.openmetadata.service.search.vector.ElasticSearchVectorService; -import org.openmetadata.service.search.vector.VectorDocBuilder; -import org.openmetadata.service.search.vector.VectorIndexService; -import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; /** * Elasticsearch implementation using new Java API client with custom bulk handler @@ -207,9 +201,7 @@ public static synchronized void resetDocBuildPoolSize() { private final ConcurrentLinkedDeque> pendingColumnFutures = new ConcurrentLinkedDeque<>(); - // Vector embedding stats (incremented inline during addEntity) - private final AtomicLong vectorSuccess = new AtomicLong(0); - private final AtomicLong vectorFailed = new AtomicLong(0); + private final EmbeddingEnricher embeddingEnricher; /** * Process-wide upper bound on in-flight table column-index tasks. Each queued/running task retains @@ -268,6 +260,7 @@ public ElasticSearchBulkSink( private ElasticSearchBulkSink(SearchRepository searchRepository, BulkSinkOptions options) { this.searchRepository = searchRepository; this.searchClient = (ElasticSearchClient) searchRepository.getSearchClient(); + this.embeddingEnricher = new EmbeddingEnricher(searchRepository); this.batchSize = options.batchSize(); this.maxConcurrentRequests = options.maxConcurrentRequests(); this.maxPayloadSizeBytes = options.maxPayloadSizeBytes(); @@ -382,7 +375,7 @@ public void write(List entities, Map contextData) throws Exce } else { List> entityInterfaces = (List>) entities; - boolean embeddingsEnabled = isVectorEmbeddingEnabledForEntity(entityType); + boolean embeddingsEnabled = embeddingEnricher.isEnabledFor(entityType); // Per-entity DocBuildContext is prepared by the upstream processor stage (see // ReindexingUtil.populateDocBuildContext) and stuffed into contextData. The sink stays @@ -396,17 +389,10 @@ public void write(List entities, Map contextData) throws Exce // them into the staged doc instead of regenerating (avoids expensive embedding-provider // calls). The doc is always re-indexed via a full index op, so the embedding must be // carried on it — skipping it would strip the stored vector. - Map existingEmbeddingsById = Collections.emptyMap(); - if (embeddingsEnabled) { - Map> currentById = new HashMap<>(entityInterfaces.size()); - for (EntityInterface e : entityInterfaces) { - currentById.put( - e.getId().toString(), () -> VectorDocBuilder.computeFingerprintForEntity(e)); - } - existingEmbeddingsById = - fetchExistingEmbeddings(entityInterfaces, currentById, indexName, reindexContext); - } - Map finalEmbeddingsById = existingEmbeddingsById; + Map existingEmbeddingsById = + embeddingsEnabled + ? embeddingEnricher.reusableEmbeddings(entityInterfaces, indexName, reindexContext) + : Collections.emptyMap(); Map relationshipRevisions = (Map) @@ -426,7 +412,7 @@ public void write(List entities, Map contextData) throws Exce reindexContext, tracker, embeddingsEnabled, - finalEmbeddingsById, + existingEmbeddingsById, docBuildContexts, scriptedPartialUpdates, relationshipRevisions), @@ -500,7 +486,13 @@ private void addEntity( String json = JsonUtils.pojoToJson(searchIndexDoc); if (embeddingsEnabled) { - json = enrichWithEmbedding(entity, json, existingEmbeddingsById, tracker); + json = + embeddingEnricher.enrich( + entity, + json, + existingEmbeddingsById, + tracker, + EmbeddingTargets.of(indexName, reindexContext)); } long rawDocSize = (long) json.getBytes(StandardCharsets.UTF_8).length; @@ -1036,6 +1028,7 @@ public StepStats getProcessStats() { @Override public void close() { + embeddingEnricher.logMissedChunksSummary(); try { bulkProcessor.flush(); @@ -1144,95 +1137,14 @@ public void updateConcurrentRequests(int concurrentRequests) { LOG.info("Concurrent requests updated to: {}", concurrentRequests); } - boolean isVectorEmbeddingEnabledForEntity(String entityType) { - return searchRepository.isVectorEmbeddingEnabled() - && ElasticSearchVectorService.getInstance() != null - && AvailableEntityTypes.isVectorIndexable(entityType) - && searchRepository.getIndexMapping(entityType) != null; - } - - private String enrichWithEmbedding( - EntityInterface entity, - String json, - Map existingEmbeddingsById, - StageStatsTracker tracker) { - try { - // Per-instance gate, mirroring VectorEmbeddingHandler: the entity-type check above cannot - // see that an individual ContextMemory is Private/Shared, and the vector query path carries - // no per-document visibility filter. - if (!Entity.isVectorEmbeddable(entity)) { - return json; - } - ElasticSearchVectorService vectorService = ElasticSearchVectorService.getInstance(); - if (vectorService == null) { - return json; - } - JsonNode parsed = OBJECT_MAPPER.readTree(json); - if (!(parsed instanceof ObjectNode doc)) { - LOG.warn( - "Skipping embedding enrichment for entity {} — index doc is not a JSON object", - entity.getId()); - return json; - } - int expectedDimension = - vectorService.getEmbeddingClient() != null - ? vectorService.getEmbeddingClient().getDimension() - : -1; - JsonNode cached = existingEmbeddingsById.get(entity.getId().toString()); - if (VectorIndexService.canReuseCachedEmbedding(cached, expectedDimension)) { - // Splice the cached embedding so the full index op carries the vector instead of stripping - // it; the service-layer pre-filter only admits entries with the current fingerprint. - doc.setAll((ObjectNode) cached); - } else { - Map embeddingFields = vectorService.generateEmbeddingFields(entity); - doc.setAll((ObjectNode) OBJECT_MAPPER.valueToTree(embeddingFields)); - } - vectorSuccess.incrementAndGet(); - if (tracker != null) { - tracker.recordVector(StatsResult.SUCCESS); - } - return OBJECT_MAPPER.writeValueAsString(doc); - } catch (Exception e) { - LOG.warn( - "Failed to generate embeddings for entity {}: {}", entity.getId(), e.getMessage(), e); - vectorFailed.incrementAndGet(); - if (tracker != null) { - tracker.recordVector(StatsResult.FAILED); - } - return json; - } - } - - private Map fetchExistingEmbeddings( - List> entities, - Map> currentById, - String indexName, - ReindexContext reindexContext) { - try { - ElasticSearchVectorService vectorService = ElasticSearchVectorService.getInstance(); - if (vectorService == null || entities.isEmpty()) { - return Collections.emptyMap(); - } - String entityType = entities.getFirst().getEntityReference().getType(); - // During a recreate, read from the pre-recreate live (original) index — the staged index is - // empty by definition. Otherwise read the canonical index passed in. - String sourceIndex = - reindexContext != null - ? reindexContext.getOriginalIndex(entityType).orElse(indexName) - : indexName; - return vectorService.getExistingEmbeddingsBatch(sourceIndex, currentById); - } catch (Exception e) { - LOG.warn("Failed to fetch existing embeddings (canonical index={})", indexName, e); - return Collections.emptyMap(); - } + @Override + public StepStats getVectorStats() { + return embeddingEnricher.stats(); } @Override - public StepStats getVectorStats() { - return new StepStats() - .withTotalRecords((int) (vectorSuccess.get() + vectorFailed.get())) - .withSuccessRecords((int) vectorSuccess.get()) - .withFailedRecords((int) vectorFailed.get()); + public void retryMissedChunks(StageStatsTracker partition) { + embeddingEnricher.retryMissedChunks(partition); } public static class CustomBulkProcessor { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingEnricher.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingEnricher.java new file mode 100644 index 000000000000..928fba9e7ac2 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingEnricher.java @@ -0,0 +1,283 @@ +package org.openmetadata.service.apps.bundles.searchIndex; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.system.StepStats; +import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.bundles.searchIndex.stats.StageStatsTracker; +import org.openmetadata.service.apps.bundles.searchIndex.stats.StatsResult; +import org.openmetadata.service.search.ReindexContext; +import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.vector.StoredEmbeddingReuse; +import org.openmetadata.service.search.vector.VectorDocBuilder; +import org.openmetadata.service.search.vector.VectorIndexService; +import org.openmetadata.service.search.vector.client.EmbeddingClient; +import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; + +/** + * The embedding step of a reindex bulk sink, the same on Elasticsearch and OpenSearch: it splices + * an entity's embedding into its staged search document and writes the entity's chunk documents. + * An embedding or chunks it cannot write are retried once when their partition ends, then counted; + * see {@link MissedChunks}. + */ +@Slf4j +final class EmbeddingEnricher { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final SearchRepository searchRepository; + private final AtomicLong succeeded = new AtomicLong(); + private final AtomicLong failed = new AtomicLong(); + private final MissedChunks missedChunks = new MissedChunks(); + + /** What enriching one entity did with its embedding and its chunk documents. */ + private enum Embedded { + /** The entity document has its embedding and the chunks are written, or need no write. */ + COMPLETE, + /** The entity document has its embedding; its chunks were missed and wait for the retry. */ + CHUNKS_MISSED, + /** The provider failed or its circuit was open: no embedding and no chunks, until the retry. */ + EMBEDDING_MISSED, + /** There is no embedding client, so nothing can be embedded or retried. */ + NONE + } + + EmbeddingEnricher(SearchRepository searchRepository) { + this.searchRepository = searchRepository; + } + + boolean isEnabledFor(String entityType) { + return searchRepository.isVectorEmbeddingEnabled() + && searchRepository.getVectorIndexService() != null + && AvailableEntityTypes.isVectorIndexable(entityType) + && searchRepository.getIndexMapping(entityType) != null; + } + + /** + * The stored embeddings of {@code entities} that are still current, keyed by entity id. {@link + * #enrich} splices these instead of calling the embedding provider. + */ + Map reusableEmbeddings( + List> entities, String indexName, ReindexContext reindexContext) { + Map reusable = Collections.emptyMap(); + VectorIndexService vectorService = searchRepository.getVectorIndexService(); + if (vectorService != null && !entities.isEmpty()) { + try { + reusable = + vectorService.getExistingEmbeddingsBatch( + storedEmbeddingsIndex(entities, indexName, reindexContext), + currentFingerprints(entities)); + } catch (RuntimeException e) { + LOG.warn("Failed to fetch existing embeddings (canonical index={})", indexName, e); + } + } + return reusable; + } + + // A recreate stages an empty index, so its stored embeddings are in the index it replaces. + private static String storedEmbeddingsIndex( + List> entities, String indexName, ReindexContext reindexContext) { + String entityType = entities.getFirst().getEntityReference().getType(); + return reindexContext == null + ? indexName + : reindexContext.getOriginalIndex(entityType).orElse(indexName); + } + + private static Map> currentFingerprints( + List> entities) { + Map> currentById = new HashMap<>(entities.size()); + for (EntityInterface entity : entities) { + currentById.put( + entity.getId().toString(), () -> VectorDocBuilder.computeFingerprintForEntity(entity)); + } + return currentById; + } + + /** + * Returns {@code json} with the entity's embedding fields added, after writing its chunk + * documents to {@code targets}. A miss returns {@code json} without them, so the entity is still + * indexed, and the retry at the end of its partition writes what was missed. + */ + String enrich( + EntityInterface entity, + String json, + Map reusableById, + StageStatsTracker tracker, + EmbeddingTargets targets) { + String enriched = json; + try { + VectorIndexService vectorService = searchRepository.getVectorIndexService(); + Optional doc = embeddableDoc(entity, json, vectorService); + if (doc.isPresent()) { + JsonNode stored = reusableById.get(entity.getId().toString()); + Embedded embedded = + embed(entity, doc.get(), stored, vectorService, targets.stagedChunkTarget()); + enriched = MAPPER.writeValueAsString(doc.get()); + record(embedded, entity, tracker, targets); + } + } catch (JsonProcessingException | RuntimeException e) { + LOG.warn( + "Failed to generate embeddings for entity {}: {}", entity.getId(), e.getMessage(), e); + count(failed, tracker, StatsResult.FAILED); + } + return enriched; + } + + /** The search document as a tree, or empty when this entity gets no embedding. */ + private static Optional embeddableDoc( + EntityInterface entity, String json, VectorIndexService vectorService) + throws JsonProcessingException { + Optional doc = Optional.empty(); + // The entity-type gate cannot see one instance opting out (a restricted context memory), so + // each entity is asked, as VectorEmbeddingHandler does for live updates. + if (vectorService != null && Entity.isVectorEmbeddable(entity)) { + if (MAPPER.readTree(json) instanceof ObjectNode object) { + doc = Optional.of(object); + } else { + LOG.warn( + "Skipping embedding enrichment for entity {}: index doc is not a JSON object", + entity.getId()); + } + } + return doc; + } + + // A miss is counted once the retry decides it; the other outcomes are final now. + private void record( + Embedded embedded, + EntityInterface entity, + StageStatsTracker tracker, + EmbeddingTargets targets) { + switch (embedded) { + case COMPLETE -> count(succeeded, tracker, StatsResult.SUCCESS); + case CHUNKS_MISSED -> missedChunks.addChunks(entity, tracker, targets); + case EMBEDDING_MISSED -> missedChunks.addEmbedding(entity, tracker, targets); + case NONE -> count(failed, tracker, StatsResult.FAILED); + } + } + + private static Embedded embed( + EntityInterface entity, + ObjectNode doc, + JsonNode stored, + VectorIndexService vectorService, + String stagedChunkTarget) { + EmbeddingClient embeddingClient = vectorService.getEmbeddingClient(); + int dimension = embeddingClient == null ? -1 : embeddingClient.getDimension(); + Embedded embedded = Embedded.NONE; + if (StoredEmbeddingReuse.isSpliceable(stored, dimension)) { + // The stored chunkIndex, chunkCount and parentId are spliced too. That is safe because the + // fingerprint that admitted this entry covers the body text that decides the chunk count. + doc.setAll((ObjectNode) stored); + // Catalogs embedded before the chunk index existed have an embedding but no chunk + // documents. The backfill is fingerprint-guarded, so it is a no-op once they exist. Chunk + // documents describe committed entity state, so writing them is safe even when this run's + // staged entity index is never promoted. + embedded = chunksOutcome(vectorService.backfillEntityChunks(entity, stagedChunkTarget)); + } else if (embeddingClient != null) { + embedded = embedAfresh(entity, doc, vectorService, stagedChunkTarget); + } + return embedded; + } + + private static Embedded chunksOutcome(boolean chunksWritten) { + return chunksWritten ? Embedded.COMPLETE : Embedded.CHUNKS_MISSED; + } + + /** One provider call per chunk: chunk 0 also gives the entity document its embedding. */ + private static Embedded embedAfresh( + EntityInterface entity, + ObjectNode doc, + VectorIndexService vectorService, + String stagedChunkTarget) { + return embedChunks(entity, vectorService.getEmbeddingClient()) + .map( + chunkDocs -> + spliceAndWriteChunks(entity, doc, chunkDocs, vectorService, stagedChunkTarget)) + .orElse(Embedded.EMBEDDING_MISSED); + } + + // A provider error, or a circuit open so no call is made, is a miss: the node's summary warning + // reports it, so each entity is logged at debug only. + private static Optional>> embedChunks( + EntityInterface entity, EmbeddingClient embeddingClient) { + Optional>> chunkDocs; + try { + chunkDocs = Optional.of(VectorDocBuilder.fromEntity(entity, embeddingClient)); + } catch (RuntimeException e) { + LOG.debug( + "Could not embed {}; retrying it before the partition ends: {}", + entity.getId(), + e.getMessage()); + chunkDocs = Optional.empty(); + } + return chunkDocs; + } + + private static Embedded spliceAndWriteChunks( + EntityInterface entity, + ObjectNode doc, + List> chunkDocs, + VectorIndexService vectorService, + String stagedChunkTarget) { + boolean chunksWritten = true; + if (!chunkDocs.isEmpty()) { + Map entityFields = + VectorDocBuilder.legacyEmbeddingFields(chunkDocs.getFirst()); + doc.setAll((ObjectNode) MAPPER.valueToTree(entityFields)); + chunksWritten = + vectorService.writeEntityChunks(entity.getId().toString(), chunkDocs, stagedChunkTarget); + } + return chunksOutcome(chunksWritten); + } + + /** + * Retries once what the partition tracked by {@code partition} missed, once its writes are + * flushed, and counts each entity: a success when its embedding and chunks are now written, a + * failure when they are still missing. Other partitions of the same type sharing this sink keep + * their misses, because their entity documents may not be written yet. + */ + void retryMissedChunks(StageStatsTracker partition) { + VectorIndexService vectorService = searchRepository.getVectorIndexService(); + if (vectorService != null) { + List retried = missedChunks.retry(partition, vectorService); + for (MissedChunks.Retried entity : retried) { + count( + entity.written() ? succeeded : failed, + partition, + entity.written() ? StatsResult.SUCCESS : StatsResult.FAILED); + } + if (partition != null && !retried.isEmpty()) { + partition.flush(); + } + } + } + + void logMissedChunksSummary() { + missedChunks.logSummary(); + } + + private static void count(AtomicLong counter, StageStatsTracker tracker, StatsResult result) { + counter.incrementAndGet(); + if (tracker != null) { + tracker.recordVector(result); + } + } + + StepStats stats() { + return new StepStats() + .withTotalRecords((int) (succeeded.get() + failed.get())) + .withSuccessRecords((int) succeeded.get()) + .withFailedRecords((int) failed.get()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingTargets.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingTargets.java new file mode 100644 index 000000000000..34bd15d3695c --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingTargets.java @@ -0,0 +1,17 @@ +package org.openmetadata.service.apps.bundles.searchIndex; + +import org.openmetadata.service.search.ReindexContext; + +/** + * Where a reindex writes one entity's embedding: the index its entity document goes to, and the + * chunk generation the run staged. A null {@code stagedChunkTarget} sends the chunk documents to + * the live chunk index, because only a full recreate stages a generation. + */ +record EmbeddingTargets(String entityIndex, String stagedChunkTarget) { + + static EmbeddingTargets of(String entityIndex, ReindexContext reindexContext) { + String stagedChunkTarget = + reindexContext == null ? null : reindexContext.getStagedChunkIndex().orElse(null); + return new EmbeddingTargets(entityIndex, stagedChunkTarget); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/MissedChunks.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/MissedChunks.java new file mode 100644 index 000000000000..04abf67c0ee9 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/MissedChunks.java @@ -0,0 +1,168 @@ +package org.openmetadata.service.apps.bundles.searchIndex; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.bundles.searchIndex.stats.StageStatsTracker; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.search.vector.VectorDocBuilder; +import org.openmetadata.service.search.vector.VectorIndexService; +import org.openmetadata.service.search.vector.client.EmbeddingClient; + +/** + * The entities whose chunk documents this node's reindex sink could not write during one run, + * including those it could not embed at all. Each is retried once when the partition that missed + * it finishes, after that partition's writes are flushed, and only then counted, so a recovered entity is one vector success and an entity that + * still misses is one vector failure. A miss never blocks the chunk generation; an entity left + * without chunks gets them on its next edit or reindex. + * ADR:2026-11-20-elasticsearch-and-opensearch-share-one-vector-index-service + */ +@Slf4j +final class MissedChunks { + private static final String ALL_FIELDS = "*"; + + /** What the first attempt left out of the run's targets. */ + enum Missing { + /** The chunk documents only; the entity document has its embedding. */ + CHUNKS, + /** The entity document's embedding and the chunk documents: the provider call failed. */ + EMBEDDING + } + + /** One entity that missed, with the stats tracker of the partition that missed it. */ + record Miss( + EntityReference entity, + StageStatsTracker tracker, + EmbeddingTargets targets, + Missing missing) {} + + /** A retried miss and whether everything it missed is now written. */ + record Retried(Miss miss, boolean written) {} + + private final Map pending = new ConcurrentHashMap<>(); + private final AtomicLong missed = new AtomicLong(); + private final AtomicLong missedEmbeddings = new AtomicLong(); + private final AtomicLong recovered = new AtomicLong(); + private final AtomicLong unrecovered = new AtomicLong(); + + void addChunks(EntityInterface entity, StageStatsTracker tracker, EmbeddingTargets targets) { + add(new Miss(entity.getEntityReference(), tracker, targets, Missing.CHUNKS)); + } + + void addEmbedding( + EntityInterface entity, StageStatsTracker tracker, EmbeddingTargets targets) { + missedEmbeddings.incrementAndGet(); + add(new Miss(entity.getEntityReference(), tracker, targets, Missing.EMBEDDING)); + } + + private void add(Miss miss) { + pending.put(miss.entity().getId().toString(), miss); + missed.incrementAndGet(); + LOG.debug( + "Missed the {} of {}; retrying before the partition ends", + miss.missing(), + miss.entity().getId()); + } + + /** + * Retries the pending misses of the partition tracked by {@code partition} once, one at a time so + * the provider's own concurrency limit holds. While the provider's circuit is open nothing is + * retried and every miss stays a failure. + */ + List retry(StageStatsTracker partition, VectorIndexService vectorService) { + List misses = drain(partition); + boolean providerAvailable = providerAvailable(vectorService); + List retried = new ArrayList<>(misses.size()); + for (Miss miss : misses) { + boolean written = providerAvailable && retryOnce(miss, vectorService); + (written ? recovered : unrecovered).incrementAndGet(); + retried.add(new Retried(miss, written)); + } + return retried; + } + + // A partition's tracker is its own, so this takes only the misses whose documents that + // partition has already flushed. + private List drain(StageStatsTracker partition) { + List drained = new ArrayList<>(); + pending + .entrySet() + .removeIf( + entry -> { + boolean ofPartition = entry.getValue().tracker() == partition; + if (ofPartition) { + drained.add(entry.getValue()); + } + return ofPartition; + }); + return drained; + } + + private static boolean providerAvailable(VectorIndexService vectorService) { + EmbeddingClient embeddingClient = vectorService.getEmbeddingClient(); + return embeddingClient != null && embeddingClient.isAvailable(); + } + + // An entity deleted since its miss needs no embedding, so it is not a failure. + private static boolean retryOnce(Miss miss, VectorIndexService vectorService) { + boolean written; + try { + EntityInterface entity = Entity.getEntity(miss.entity(), ALL_FIELDS, Include.NON_DELETED); + written = + miss.missing() == Missing.EMBEDDING + ? embedAfresh(entity, miss.targets(), vectorService) + : vectorService.backfillEntityChunks(entity, miss.targets().stagedChunkTarget()); + } catch (EntityNotFoundException deleted) { + written = true; + } catch (RuntimeException e) { + LOG.debug("Retry of {} failed: {}", miss.entity().getId(), e.getMessage()); + written = false; + } + return written; + } + + /** + * Writes what a first attempt that succeeded would have written: chunk 0's embedding fields on + * the entity document, which the bulk has already indexed, and the chunk documents. Each write is + * tried even when the other fails, so a chunk index that cannot be written never costs the + * entity its document embedding. + */ + private static boolean embedAfresh( + EntityInterface entity, EmbeddingTargets targets, VectorIndexService vectorService) { + List> chunkDocs = + VectorDocBuilder.fromEntity(entity, vectorService.getEmbeddingClient()); + String entityId = entity.getId().toString(); + boolean embeddingWritten = + chunkDocs.isEmpty() + || vectorService.writeEntityEmbedding( + targets.entityIndex(), + entityId, + VectorDocBuilder.legacyEmbeddingFields(chunkDocs.getFirst())); + boolean chunksWritten = + chunkDocs.isEmpty() + || vectorService.writeEntityChunks(entityId, chunkDocs, targets.stagedChunkTarget()); + return embeddingWritten && chunksWritten; + } + + /** One warning per run on this node when anything was missed, with how the rest heal. */ + void logSummary() { + long missedCount = missed.get(); + if (missedCount > 0) { + LOG.warn( + "Search Indexing missed the chunk documents of {} entities on this node, {} of them " + + "with their entity embedding too; the retry recovered {}. {} count as vector " + + "failures and get their embeddings on their next edit or the next reindex", + missedCount, + missedEmbeddings.get(), + recovered.get(), + unrecovered.get()); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java index 07be60c814cc..c298ea02f02a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.json.stream.JsonGenerator; import java.io.StringWriter; import java.nio.charset.StandardCharsets; @@ -38,7 +37,6 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.EntityTimeSeriesInterface; @@ -61,10 +59,6 @@ import org.openmetadata.service.search.indexes.SearchIndex; import org.openmetadata.service.search.opensearch.OpenSearchClient; import org.openmetadata.service.search.opensearch.OsUtils; -import org.openmetadata.service.search.vector.OpenSearchVectorService; -import org.openmetadata.service.search.vector.VectorDocBuilder; -import org.openmetadata.service.search.vector.VectorIndexService; -import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; import os.org.opensearch.client.json.JsonData; import os.org.opensearch.client.json.jackson.JacksonJsonpMapper; import os.org.opensearch.client.opensearch.OpenSearchAsyncClient; @@ -208,9 +202,7 @@ public interface SinkStatsCallback { // Stats callback for per-entity-type reporting private volatile SinkStatsCallback statsCallback; - // Vector embedding stats (incremented inline during addEntity) - private final AtomicLong vectorSuccess = new AtomicLong(0); - private final AtomicLong vectorFailed = new AtomicLong(0); + private final EmbeddingEnricher embeddingEnricher; // Column indexing: separate bulk processor with its own lifecycle private final CustomBulkProcessor columnBulkProcessor; @@ -279,6 +271,7 @@ public OpenSearchBulkSink( private OpenSearchBulkSink(SearchRepository searchRepository, BulkSinkOptions options) { this.searchRepository = searchRepository; this.searchClient = (OpenSearchClient) searchRepository.getSearchClient(); + this.embeddingEnricher = new EmbeddingEnricher(searchRepository); this.batchSize = options.batchSize(); this.maxConcurrentRequests = options.maxConcurrentRequests(); this.maxPayloadSizeBytes = options.maxPayloadSizeBytes(); @@ -341,7 +334,7 @@ public void write(List entities, Map contextData) throws Exce Boolean.TRUE.equals(contextData.get(SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY)); // Check if embeddings are enabled for this specific entity type - boolean embeddingsEnabled = isVectorEmbeddingEnabledForEntity(entityType); + boolean embeddingsEnabled = embeddingEnricher.isEnabledFor(entityType); IndexMapping indexMapping = searchRepository.getIndexMapping(entityType); if (indexMapping == null) { @@ -409,16 +402,10 @@ public void write(List entities, Map contextData) throws Exce // them into the staged doc instead of regenerating (avoids expensive embedding-provider // calls). The service-layer two-step keeps large vector payloads off the wire for entities // that will be re-embedded anyway. - Map existingEmbeddingsById = Collections.emptyMap(); - if (embeddingsEnabled) { - Map> currentById = new HashMap<>(entityInterfaces.size()); - for (EntityInterface e : entityInterfaces) { - currentById.put( - e.getId().toString(), () -> VectorDocBuilder.computeFingerprintForEntity(e)); - } - existingEmbeddingsById = - fetchExistingEmbeddings(entityInterfaces, currentById, indexName, reindexContext); - } + Map existingEmbeddingsById = + embeddingsEnabled + ? embeddingEnricher.reusableEmbeddings(entityInterfaces, indexName, reindexContext) + : Collections.emptyMap(); Map relationshipRevisions = (Map) @@ -426,7 +413,6 @@ public void write(List entities, Map contextData) throws Exce RELATIONSHIP_REVISIONS_CONTEXT_KEY, Collections.emptyMap()); // Add entities to search index in parallel - Map finalEmbeddingsById = existingEmbeddingsById; List> futures = entityInterfaces.stream() .map( @@ -439,7 +425,7 @@ public void write(List entities, Map contextData) throws Exce reindexContext, tracker, embeddingsEnabled, - finalEmbeddingsById, + existingEmbeddingsById, docBuildContexts, scriptedPartialUpdates, relationshipRevisions), @@ -534,13 +520,13 @@ private void addEntity( String json = JsonUtils.pojoToJson(searchIndexDoc); if (embeddingsEnabled) { - // Run-scoped chunk routing: the staged chunk generation (when this run created one) is - // carried in the ReindexContext, so writes target exactly this run's generation — partial - // recreates and normal runs carry none and write to the live index. - String stagedChunkTarget = - reindexContext != null ? reindexContext.getStagedChunkIndex().orElse(null) : null; json = - enrichWithEmbedding(entity, json, existingEmbeddingsById, tracker, stagedChunkTarget); + embeddingEnricher.enrich( + entity, + json, + existingEmbeddingsById, + tracker, + EmbeddingTargets.of(indexName, reindexContext)); } String finalJson = json; @@ -1069,6 +1055,7 @@ public StepStats getStats() { @Override public void close() { + embeddingEnricher.logMissedChunksSummary(); try { bulkProcessor.flush(); @@ -1167,121 +1154,19 @@ public void updateConcurrentRequests(int concurrentRequests) { LOG.info("Concurrent requests updated to: {}", concurrentRequests); } - boolean isVectorEmbeddingEnabledForEntity(String entityType) { - return searchRepository.isVectorEmbeddingEnabled() - && OpenSearchVectorService.getInstance() != null - && AvailableEntityTypes.isVectorIndexable(entityType) - && searchRepository.getIndexMapping(entityType) != null; - } - - private String enrichWithEmbedding( - EntityInterface entity, - String json, - Map existingEmbeddingsById, - StageStatsTracker tracker, - String stagedChunkTarget) { - try { - // Per-instance gate, mirroring VectorEmbeddingHandler: the entity-type check above cannot - // see that an individual ContextMemory is Private/Shared, and the vector query path carries - // no per-document visibility filter. - if (!Entity.isVectorEmbeddable(entity)) { - return json; - } - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); - if (vectorService == null) { - return json; - } - - JsonNode parsed = OBJECT_MAPPER.readTree(json); - if (!(parsed instanceof ObjectNode doc)) { - LOG.warn( - "Skipping embedding enrichment for entity {} — index doc is not a JSON object", - entity.getId()); - return json; - } - - var embeddingClient = vectorService.getEmbeddingClient(); - int expectedDimension = embeddingClient != null ? embeddingClient.getDimension() : -1; - JsonNode cached = existingEmbeddingsById.get(entity.getId().toString()); - if (VectorIndexService.canReuseCachedEmbedding(cached, expectedDimension)) { - // Splices chunkIndex/chunkCount/parentId along with embedding — safe because the - // service-layer pre-filter only admits entries with the current fingerprint, and the - // fingerprint covers the body text that determines chunk count. - doc.setAll((ObjectNode) cached); - // Backfill: the entity content is unchanged, but the dedicated chunk index (issue #4789) - // may not hold this entity's chunk docs yet (catalogs embedded before multi-chunk - // shipped). The call is fingerprint-guarded, so it is a cheap no-op once chunks exist; - // chunk docs reflect committed entity state, so writing them mid-reindex is safe even if - // the staged index is never promoted. - vectorService.backfillEntityChunks(entity, stagedChunkTarget); - } else if (embeddingClient != null && embeddingClient.isAvailable()) { - // Build the chunk docs once (one embedding call per chunk): chunk 0's embedding fields - // are spliced into the staged entity doc for hybrid search, and the full set is written to - // the dedicated chunk index for the semantic vector path (issue #4789). Skipped when the - // provider circuit is open so a transient outage indexes without embeddings (self-heals on - // the next reindex) instead of failing every entity. - List> chunkDocs = VectorDocBuilder.fromEntity(entity, embeddingClient); - if (!chunkDocs.isEmpty()) { - doc.setAll( - (ObjectNode) - OBJECT_MAPPER.valueToTree( - OpenSearchVectorService.legacyEmbeddingFields(chunkDocs.get(0)))); - vectorService.writeEntityChunks(entity.getId().toString(), chunkDocs, stagedChunkTarget); - } - } - - vectorSuccess.incrementAndGet(); - if (tracker != null) { - tracker.recordVector(StatsResult.SUCCESS); - } - return OBJECT_MAPPER.writeValueAsString(doc); - } catch (Exception e) { - LOG.warn( - "Failed to generate embeddings for entity {}: {}", entity.getId(), e.getMessage(), e); - vectorFailed.incrementAndGet(); - if (tracker != null) { - tracker.recordVector(StatsResult.FAILED); - } - return json; - } - } - @Override public int getActiveBulkRequestCount() { return bulkProcessor.activeBulkRequests.get(); } - private Map fetchExistingEmbeddings( - List> entities, - Map> currentById, - String indexName, - ReindexContext reindexContext) { - try { - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); - if (vectorService == null) { - return Collections.emptyMap(); - } - - String entityType = entities.getFirst().getEntityReference().getType(); - // During a recreate, read embeddings from the pre-recreate live index (the staged index is - // empty by definition). Outside a recreate, read from the canonical index passed in. - String sourceIndex = - reindexContext != null - ? reindexContext.getOriginalIndex(entityType).orElse(indexName) - : indexName; - return vectorService.getExistingEmbeddingsBatch(sourceIndex, currentById); - } catch (Exception e) { - LOG.warn("Failed to fetch existing embeddings (canonical index={})", indexName, e); - return Collections.emptyMap(); - } + @Override + public StepStats getVectorStats() { + return embeddingEnricher.stats(); } @Override - public StepStats getVectorStats() { - return new StepStats() - .withTotalRecords((int) (vectorSuccess.get() + vectorFailed.get())) - .withSuccessRecords((int) vectorSuccess.get()) - .withFailedRecords((int) vectorFailed.get()); + public void retryMissedChunks(StageStatsTracker partition) { + embeddingEnricher.retryMissedChunks(partition); } @Override diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipant.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipant.java index aadbb50babba..abe7fb4a99a2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipant.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipant.java @@ -31,7 +31,7 @@ import org.openmetadata.service.search.ReindexContext; import org.openmetadata.service.search.SearchClusterMetrics; import org.openmetadata.service.search.SearchRepository; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; /** * Background service that monitors for active distributed indexing jobs and joins them to help @@ -318,9 +318,9 @@ private void processJobPartitions(SearchIndexJob job) { // into this run's generation instead of relying on lossy cluster-state discovery (a 15s // JVM-local null cache that can silently drop the mirror write). Sink writes already // receive this target via ReindexContext; this closes the same gap for the live-edit mirror - // path. Cleared in the finally below. No-op when the OpenSearch vector service is not - // initialized (Elasticsearch backend, or embeddings disabled). - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + // path. Cleared in the finally below. No-op when embeddings are disabled, as there is then + // no vector service. + VectorIndexService vectorService = searchRepository.getVectorIndexService(); if (vectorService != null) { reindexContext.getStagedChunkIndex().ifPresent(vectorService::latchParticipantStagedTarget); } @@ -488,8 +488,8 @@ private void processJobPartitions(SearchIndexJob job) { } // Drop the participant's run-scoped staged chunk latch so a later run cannot mirror or // delete into a generation that belongs to this finished (promoted or abandoned) run. - // No-op when the OpenSearch vector service was never initialized or never latched. - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + // No-op when there is no vector service or nothing was latched. + VectorIndexService vectorService = searchRepository.getVectorIndexService(); if (vectorService != null) { vectorService.clearParticipantStagedTarget(); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinator.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinator.java index f85127f7f10b..b150f4afa2d7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinator.java @@ -701,91 +701,106 @@ private void touchJobThrottled(String jobId, long now) { } /** - * Mark a partition as failed. + * Mark a partition as failed. It is queued for a retry until it has used its retries. * * @param partitionId The partition ID * @param errorMessage Error message describing the failure */ public void failPartition(UUID partitionId, String errorMessage) { - SearchIndexPartitionDAO partitionDAO = collectionDAO.searchIndexPartitionDAO(); + recordPartitionFailure(partitionId, errorMessage, true); + } - SearchIndexPartitionRecord record = partitionDAO.findById(partitionId.toString()); + /** + * Mark a partition as failed for good, without a retry: for a failure no retry on any node can + * repair, whose FAILED row and {@code errorMessage} must stay as they are for the rest of the job. + */ + public void failPartitionWithoutRetry(UUID partitionId, String errorMessage) { + recordPartitionFailure(partitionId, errorMessage, false); + } + + private void recordPartitionFailure(UUID partitionId, String errorMessage, boolean retryable) { + SearchIndexPartitionRecord record = + collectionDAO.searchIndexPartitionDAO().findById(partitionId.toString()); if (record == null) { LOG.warn("Partition not found for failure: {}", partitionId); - return; + } else if (retryable && record.retryCount() < MAX_PARTITION_RETRIES) { + requeuePartition(record, errorMessage); + } else { + failPartitionForGood(record, errorMessage); } + } - long now = System.currentTimeMillis(); - - // Status-guarded write — if requestStop already moved this row to CANCELLED, - // updateIfProcessing returns 0 and we leave the cancellation authoritative - // instead of resurrecting the row to PENDING (retry) or FAILED (terminal). - if (record.retryCount() < MAX_PARTITION_RETRIES) { - int updated = - partitionDAO.updateIfProcessing( - partitionId.toString(), - PartitionStatus.PENDING.name(), - record.cursor(), - record.processedCount(), - record.successCount(), - record.failedCount(), - null, - null, - null, - null, - now, - errorMessage, - record.retryCount() + 1); - if (updated == 0) { - LOG.info( - "Skipped retry-requeue of partition {} (entity {}) — row no longer PROCESSING " - + "(likely cancelled by Stop); leaving authoritative state intact.", - partitionId, - record.entityType()); - return; - } + // Status-guarded write: if requestStop already moved this row to CANCELLED, updateIfProcessing + // returns 0 and the cancellation stays authoritative instead of the row being resurrected. + private void requeuePartition(SearchIndexPartitionRecord record, String errorMessage) { + int updated = + collectionDAO + .searchIndexPartitionDAO() + .updateIfProcessing( + record.id(), + PartitionStatus.PENDING.name(), + record.cursor(), + record.processedCount(), + record.successCount(), + record.failedCount(), + null, + null, + null, + null, + System.currentTimeMillis(), + errorMessage, + record.retryCount() + 1); + if (updated == 0) { + LOG.info( + "Skipped retry-requeue of partition {} (entity {}) — row no longer PROCESSING " + + "(likely cancelled by Stop); leaving authoritative state intact.", + record.id(), + record.entityType()); + } else { LOG.warn( "Partition {} failed, queued for retry ({}/{}): {}", - partitionId, + record.id(), record.retryCount() + 1, MAX_PARTITION_RETRIES, errorMessage); - } else { - int updated = - partitionDAO.updateIfProcessing( - partitionId.toString(), - PartitionStatus.FAILED.name(), - record.cursor(), - record.processedCount(), - record.successCount(), - record.failedCount(), - record.assignedServer(), - record.claimedAt(), - record.startedAt(), - now, - now, - errorMessage, - record.retryCount()); - if (updated == 0) { - LOG.info( - "Skipped terminal-failure of partition {} (entity {}) — row no longer PROCESSING " - + "(likely cancelled by Stop); leaving authoritative state intact.", - partitionId, - record.entityType()); - return; - } + } + } + private void failPartitionForGood(SearchIndexPartitionRecord record, String errorMessage) { + long now = System.currentTimeMillis(); + int updated = + collectionDAO + .searchIndexPartitionDAO() + .updateIfProcessing( + record.id(), + PartitionStatus.FAILED.name(), + record.cursor(), + record.processedCount(), + record.successCount(), + record.failedCount(), + record.assignedServer(), + record.claimedAt(), + record.startedAt(), + now, + now, + errorMessage, + record.retryCount()); + if (updated == 0) { + LOG.info( + "Skipped terminal-failure of partition {} (entity {}) — row no longer PROCESSING " + + "(likely cancelled by Stop); leaving authoritative state intact.", + record.id(), + record.entityType()); + } else { LOG.error( "Partition {} permanently failed after {} retries: {}", - partitionId, - MAX_PARTITION_RETRIES, + record.id(), + record.retryCount(), errorMessage); - // Record partition completion (with failure) for per-entity index promotion if (entityTracker != null) { entityTracker.recordPartitionComplete(record.entityType(), true); } - checkAndUpdateJobCompletion(UUID.fromString(record.jobId())); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutor.java index 26a5f0bef0a0..b16d57a35ae1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutor.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutor.java @@ -50,6 +50,7 @@ import org.openmetadata.service.search.EntityReindexContext; import org.openmetadata.service.search.RecreateIndexHandler; import org.openmetadata.service.search.ReindexContext; +import org.openmetadata.service.search.vector.VectorIndexService; /** * Executor for distributed search index jobs. @@ -1392,6 +1393,7 @@ private boolean promoteEntityIndex(String entityType, boolean success) { LOG.debug("No staged index for entity '{}', skipping promotion", entityType); return true; } + entityContext.setStagedChunkDeleteUnrecorded(lostAStagedChunkDelete(entityType)); boolean promoted = false; try { @@ -1414,6 +1416,25 @@ private boolean promoteEntityIndex(String entityType, boolean success) { return promoted; } + /** + * Whether a node failed a partition of {@code entityType} because it missed a delete from the + * run's staged chunk generation and could not record it on the cluster. That partition fails + * for good without a retry, and nothing rewrites a FAILED row, so its error stays readable here + * whatever the type's other partitions did. + */ + private boolean lostAStagedChunkDelete(String entityType) { + SearchIndexJob job = currentJob; + return job != null + && coordinator.getPartitions(job.getId(), PartitionStatus.FAILED).stream() + .anyMatch( + partition -> + entityType.equals(partition.getEntityType()) + && partition.getLastError() != null + && partition + .getLastError() + .startsWith(VectorIndexService.UNRECORDED_STAGED_DELETE)); + } + /** * Result of job execution. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorker.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorker.java index 9c21f572563b..aaa6ebffb738 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorker.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorker.java @@ -38,6 +38,10 @@ import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.search.ReindexContext; +import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.vector.UnrecordedStagedChunkDeleteException; +import org.openmetadata.service.search.vector.VectorIndexService; +import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; import org.openmetadata.service.util.RestUtil; import org.openmetadata.service.workflows.searchIndex.PaginatedEntitiesSource; import org.openmetadata.service.workflows.searchIndex.PaginatedEntityTimeSeriesSource; @@ -132,29 +136,27 @@ public PartitionResult processPartition(SearchIndexPartition partition) { private PartitionResult processPartitionInternal(SearchIndexPartition partition) { String entityType = SearchIndexEntityTypes.normalizeEntityType(partition.getEntityType()); - long rangeStart = partition.getRangeStart(); - long rangeEnd = partition.getRangeEnd(); LOG.info( "Starting partition {} for entity type {} (range: {} - {})", partition.getId(), entityType, - rangeStart, - rangeEnd); + partition.getRangeStart(), + partition.getRangeEnd()); + PartitionResult result; if (stopped.get() || Thread.currentThread().isInterrupted()) { LOG.info("Skipping partition {} because worker is already stopped", partition.getId()); - return new PartitionResult(0, 0, true); + result = new PartitionResult(0, 0, true); + } else { + result = processStartedPartition(partition, entityType); } + return result; + } - AtomicLong successCount = new AtomicLong(0); - AtomicLong failedCount = new AtomicLong(0); - AtomicLong readerFailedCount = new AtomicLong(0); - AtomicLong warningsCount = new AtomicLong(0); - AtomicLong processedCount = new AtomicLong(0); - long currentOffset = rangeStart; - - // Create stats tracker for this partition + private PartitionResult processStartedPartition( + SearchIndexPartition partition, String entityType) { + PartitionCounts counts = new PartitionCounts(); StageStatsTracker statsTracker = new StageStatsTracker( partition.getJobId().toString(), @@ -162,232 +164,258 @@ private PartitionResult processPartitionInternal(SearchIndexPartition partition) entityType, coordinator.getCollectionDAO().searchIndexServerStatsDAO()); + PartitionResult result; try { - // Mark partition as started SearchIndexPartition processing = partition.toBuilder() .status(PartitionStatus.PROCESSING) .startedAt(System.currentTimeMillis()) .build(); coordinator.updatePartitionProgress(processing); + readPartition(partition, entityType, counts, statsTracker); - // Initialize keyset cursor for efficient pagination (avoids OFFSET degradation) - long cursorInitStart = System.currentTimeMillis(); - String keysetCursor = initializeKeysetCursor(partition, rangeStart); - LOG.debug( - "initializeKeysetCursor for {} offset={} took {}ms", - entityType, - rangeStart, - System.currentTimeMillis() - cursorInitStart); - - // Process in batches - while (currentOffset < rangeEnd - && !stopped.get() - && !Thread.currentThread().isInterrupted()) { - // Yield before pulling the next batch when the pod's heap is tight. AutoTune sizes batch - // and - // queue once at start from a fixed per-entity estimate; real entities (embeddings, wide - // tables) or co-tenant work can exceed it and OOM a small heap. Pausing the reader — not - // the - // writes — lets in-flight docs drain and GC reclaim, so reindex adapts to any pod size. - HeapBackpressure.awaitHeadroom(); - int currentBatchSize = (int) Math.min(batchSize, rangeEnd - currentOffset); - - try { - BatchResult batchResult = - processBatch(entityType, keysetCursor, currentBatchSize, statsTracker); - // Check for stop/interrupt after DB read completes - if (stopped.get() || Thread.currentThread().isInterrupted()) { - break; - } - successCount.addAndGet(batchResult.successCount()); - failedCount.addAndGet(batchResult.failedCount()); - warningsCount.addAndGet(batchResult.warningsCount()); - processedCount.addAndGet( - batchResult.successCount() + batchResult.failedCount() + batchResult.warningsCount()); - - currentOffset += currentBatchSize; - keysetCursor = batchResult.nextCursor(); - - // Update progress periodically - if (processedCount.get() % PROGRESS_UPDATE_INTERVAL < batchSize) { - updateProgress( - partition, + if (stopped.get()) { + LOG.info("Partition {} stopped by request", partition.getId()); + // Wait briefly for async sink operations to complete and update tracker + waitForSinkOperations(statsTracker); + result = counts.result(true); + } else { + finishPartition(partition, entityType, counts, statsTracker); + result = counts.result(false); + } + } catch (Exception e) { + LOG.error("Fatal error processing partition {}", partition.getId(), e); + failPartition(partition, e); + waitForSinkOperations(statsTracker); + result = counts.result(false); + } + return result; + } + + private void readPartition( + SearchIndexPartition partition, + String entityType, + PartitionCounts counts, + StageStatsTracker statsTracker) { + long rangeStart = partition.getRangeStart(); + long rangeEnd = partition.getRangeEnd(); + long currentOffset = rangeStart; + + // Initialize keyset cursor for efficient pagination (avoids OFFSET degradation) + long cursorInitStart = System.currentTimeMillis(); + String keysetCursor = initializeKeysetCursor(partition, rangeStart); + LOG.debug( + "initializeKeysetCursor for {} offset={} took {}ms", + entityType, + rangeStart, + System.currentTimeMillis() - cursorInitStart); + + // Process in batches + while (currentOffset < rangeEnd && !stopped.get() && !Thread.currentThread().isInterrupted()) { + // Yield before pulling the next batch when the pod's heap is tight. AutoTune sizes batch + // and + // queue once at start from a fixed per-entity estimate; real entities (embeddings, wide + // tables) or co-tenant work can exceed it and OOM a small heap. Pausing the reader — not + // the + // writes — lets in-flight docs drain and GC reclaim, so reindex adapts to any pod size. + HeapBackpressure.awaitHeadroom(); + int currentBatchSize = (int) Math.min(batchSize, rangeEnd - currentOffset); + + try { + BatchResult batchResult = + processBatch(entityType, keysetCursor, currentBatchSize, statsTracker); + // Check for stop/interrupt after DB read completes + if (stopped.get() || Thread.currentThread().isInterrupted()) { + break; + } + counts.success().addAndGet(batchResult.successCount()); + counts.failed().addAndGet(batchResult.failedCount()); + counts.warnings().addAndGet(batchResult.warningsCount()); + counts + .processed() + .addAndGet( + batchResult.successCount() + + batchResult.failedCount() + + batchResult.warningsCount()); + + currentOffset += currentBatchSize; + keysetCursor = batchResult.nextCursor(); + + // Update progress periodically + if (counts.processed().get() % PROGRESS_UPDATE_INTERVAL < batchSize) { + updateProgress( + partition, + currentOffset, + counts.processed().get(), + counts.success().get(), + counts.failed().get()); + } + + // If keyset cursor exhausted, recompute or stop + if (keysetCursor == null && currentOffset < rangeEnd) { + keysetCursor = initializeKeysetCursor(partition, currentOffset); + if (keysetCursor == null) { + LOG.debug( + "{} partition {} data exhausted at offset {} (rangeEnd: {}), " + + "missing {} records. counts.processed()={}", + entityType, + partition.getId(), currentOffset, - processedCount.get(), - successCount.get(), - failedCount.get()); + rangeEnd, + rangeEnd - currentOffset, + counts.processed().get()); + break; } + } - // If keyset cursor exhausted, recompute or stop - if (keysetCursor == null && currentOffset < rangeEnd) { - keysetCursor = initializeKeysetCursor(partition, currentOffset); - if (keysetCursor == null) { - LOG.debug( - "{} partition {} data exhausted at offset {} (rangeEnd: {}), " - + "missing {} records. processedCount={}", - entityType, - partition.getId(), - currentOffset, - rangeEnd, - rangeEnd - currentOffset, - processedCount.get()); - break; - } - } + } catch (SearchIndexException e) { + LOG.error("Error processing batch at offset {} for {}", currentOffset, entityType, e); - } catch (SearchIndexException e) { - LOG.error("Error processing batch at offset {} for {}", currentOffset, entityType, e); - - boolean isReaderFailure = - e.getIndexingError() != null - && e.getIndexingError().getErrorSource() - == org.openmetadata.schema.system.IndexingError.ErrorSource.READER; - - int batchFailedCount = - e.getIndexingError() != null && e.getIndexingError().getFailedCount() != null - ? e.getIndexingError().getFailedCount() - : currentBatchSize; - - if (isReaderFailure) { - if (statsTracker != null) { - statsTracker.recordReaderBatch(0, batchFailedCount, 0); - } - if (failureRecorder != null) { - failureRecorder.recordReaderFailure( - entityType, e.getMessage(), ExceptionUtils.getStackTrace(e)); - } - readerFailedCount.addAndGet(batchFailedCount); - } else { - if (statsTracker != null) { - statsTracker.recordSinkBatch(0, batchFailedCount); - } - if (failureRecorder != null) { - failureRecorder.recordSinkFailure( - entityType, - "BATCH", - "batch_at_offset_" + currentOffset, - e.getMessage(), - ExceptionUtils.getStackTrace(e)); - } - } + boolean isReaderFailure = + e.getIndexingError() != null + && e.getIndexingError().getErrorSource() + == org.openmetadata.schema.system.IndexingError.ErrorSource.READER; - failedCount.addAndGet(batchFailedCount); - processedCount.addAndGet(batchFailedCount); - currentOffset += currentBatchSize; + int batchFailedCount = + e.getIndexingError() != null && e.getIndexingError().getFailedCount() != null + ? e.getIndexingError().getFailedCount() + : currentBatchSize; - // Recompute keyset cursor after failure - if (currentOffset < rangeEnd) { - keysetCursor = initializeKeysetCursor(partition, currentOffset); - if (keysetCursor == null) { - break; - } + if (isReaderFailure) { + if (statsTracker != null) { + statsTracker.recordReaderBatch(0, batchFailedCount, 0); + } + if (failureRecorder != null) { + failureRecorder.recordReaderFailure( + entityType, e.getMessage(), ExceptionUtils.getStackTrace(e)); } + counts.readerFailed().addAndGet(batchFailedCount); + } else { + if (statsTracker != null) { + statsTracker.recordSinkBatch(0, batchFailedCount); + } + if (failureRecorder != null) { + failureRecorder.recordSinkFailure( + entityType, + "BATCH", + "batch_at_offset_" + currentOffset, + e.getMessage(), + ExceptionUtils.getStackTrace(e)); + } + } - updateProgress( - partition, - currentOffset, - processedCount.get(), - successCount.get(), - failedCount.get()); + counts.failed().addAndGet(batchFailedCount); + counts.processed().addAndGet(batchFailedCount); + currentOffset += currentBatchSize; + + // Recompute keyset cursor after failure + if (currentOffset < rangeEnd) { + keysetCursor = initializeKeysetCursor(partition, currentOffset); + if (keysetCursor == null) { + break; + } } - } - if (stopped.get()) { - LOG.info("Partition {} stopped by request", partition.getId()); - // Wait briefly for async sink operations to complete and update tracker - waitForSinkOperations(statsTracker); - return new PartitionResult( - successCount.get(), - failedCount.get(), - true, - readerFailedCount.get(), - warningsCount.get()); + updateProgress( + partition, + currentOffset, + counts.processed().get(), + counts.success().get(), + counts.failed().get()); } + } + } - // Wait for async sink operations to complete and flush stats to DB - // IMPORTANT: This must happen BEFORE marking partition complete, otherwise - // the coordinator may aggregate stats before they're written to the database - long waitStart = System.currentTimeMillis(); - waitForSinkOperations(statsTracker); - LOG.debug("waitForSinkOperations took {}ms", System.currentTimeMillis() - waitStart); - - // Adjust partition counts to include stage-level failures and warnings. - // BatchResult.successCount counts entities READ, not entities successfully PROCESSED. - // Process and sink results happen async and are tracked by StageStatsTracker. - long processFailed = - statsTracker != null ? statsTracker.getProcess().getCumulativeFailed().get() : 0; - long sinkFailed = - statsTracker != null ? statsTracker.getSink().getCumulativeFailed().get() : 0; - long stageFailed = processFailed + sinkFailed; - if (stageFailed > 0) { - long adjustment = Math.min(stageFailed, successCount.get()); - if (adjustment > 0) { - successCount.addAndGet(-adjustment); - failedCount.addAndGet(adjustment); - } + private void finishPartition( + SearchIndexPartition partition, + String entityType, + PartitionCounts counts, + StageStatsTracker statsTracker) { + long rangeStart = partition.getRangeStart(); + long rangeEnd = partition.getRangeEnd(); + // Wait for async sink operations to complete and flush stats to DB + // IMPORTANT: This must happen BEFORE marking partition complete, otherwise + // the coordinator may aggregate stats before they're written to the database + long waitStart = System.currentTimeMillis(); + waitForSinkOperations(statsTracker); + LOG.debug("waitForSinkOperations took {}ms", System.currentTimeMillis() - waitStart); + searchIndexSink.retryMissedChunks(statsTracker); + + // Adjust partition counts to include stage-level failures and warnings. + // BatchResult.successCount counts entities READ, not entities successfully PROCESSED. + // Process and sink results happen async and are tracked by StageStatsTracker. + long processFailed = + statsTracker != null ? statsTracker.getProcess().getCumulativeFailed().get() : 0; + long sinkFailed = statsTracker != null ? statsTracker.getSink().getCumulativeFailed().get() : 0; + long stageFailed = processFailed + sinkFailed; + if (stageFailed > 0) { + long adjustment = Math.min(stageFailed, counts.success().get()); + if (adjustment > 0) { + counts.success().addAndGet(-adjustment); + counts.failed().addAndGet(adjustment); } - long processWarnings = - statsTracker != null ? statsTracker.getProcess().getCumulativeWarnings().get() : 0; - long sinkWarnings = - statsTracker != null ? statsTracker.getSink().getCumulativeWarnings().get() : 0; - long stageWarnings = processWarnings + sinkWarnings; - if (stageWarnings > 0) { - long adjustment = Math.min(stageWarnings, successCount.get()); - if (adjustment > 0) { - successCount.addAndGet(-adjustment); - warningsCount.addAndGet(adjustment); - } + } + long processWarnings = + statsTracker != null ? statsTracker.getProcess().getCumulativeWarnings().get() : 0; + long sinkWarnings = + statsTracker != null ? statsTracker.getSink().getCumulativeWarnings().get() : 0; + long stageWarnings = processWarnings + sinkWarnings; + if (stageWarnings > 0) { + long adjustment = Math.min(stageWarnings, counts.success().get()); + if (adjustment > 0) { + counts.success().addAndGet(-adjustment); + counts.warnings().addAndGet(adjustment); } + } - // Mark partition as completed (stats are now in the database) - coordinator.completePartition( - partition.getId(), successCount.get(), failedCount.get(), warningsCount.get()); + requireStagedChunkFailuresRecorded(entityType); + // Mark partition as completed (stats are now in the database) + coordinator.completePartition( + partition.getId(), counts.success().get(), counts.failed().get(), counts.warnings().get()); - long expectedRecords = rangeEnd - rangeStart; - long actualProcessed = successCount.get() + failedCount.get() + warningsCount.get(); - LOG.info( - "Completed partition {} for entity type {} (success: {}, failed: {}, readerFailed: {}, processFailed: {}, sinkFailed: {}, processWarnings: {}, sinkWarnings: {}, warnings: {})", - partition.getId(), + long expectedRecords = rangeEnd - rangeStart; + long actualProcessed = counts.success().get() + counts.failed().get() + counts.warnings().get(); + LOG.info( + "Completed partition {} for entity type {} (success: {}, failed: {}, readerFailed: {}, processFailed: {}, sinkFailed: {}, processWarnings: {}, sinkWarnings: {}, warnings: {})", + partition.getId(), + entityType, + counts.success().get(), + counts.failed().get(), + counts.readerFailed().get(), + processFailed, + sinkFailed, + processWarnings, + sinkWarnings, + counts.warnings().get()); + if (actualProcessed < expectedRecords) { + LOG.debug( + "{} partition {} processed fewer records than expected: " + + "actual={}, expected={}, gap={}, range=[{},{})", entityType, - successCount.get(), - failedCount.get(), - readerFailedCount.get(), - processFailed, - sinkFailed, - processWarnings, - sinkWarnings, - warningsCount.get()); - if (actualProcessed < expectedRecords) { - LOG.debug( - "{} partition {} processed fewer records than expected: " - + "actual={}, expected={}, gap={}, range=[{},{})", - entityType, - partition.getId(), - actualProcessed, - expectedRecords, - expectedRecords - actualProcessed, - rangeStart, - rangeEnd); - } + partition.getId(), + actualProcessed, + expectedRecords, + expectedRecords - actualProcessed, + rangeStart, + rangeEnd); + } + } - return new PartitionResult( - successCount.get(), - failedCount.get(), - false, - readerFailedCount.get(), - warningsCount.get()); + /** Running counts of one partition, read into its {@link PartitionResult}. */ + private record PartitionCounts( + AtomicLong success, + AtomicLong failed, + AtomicLong readerFailed, + AtomicLong warnings, + AtomicLong processed) { + PartitionCounts() { + this( + new AtomicLong(), new AtomicLong(), new AtomicLong(), new AtomicLong(), new AtomicLong()); + } - } catch (Exception e) { - LOG.error("Fatal error processing partition {}", partition.getId(), e); - coordinator.failPartition(partition.getId(), e.getMessage()); - waitForSinkOperations(statsTracker); + PartitionResult result(boolean wasStopped) { return new PartitionResult( - successCount.get(), - failedCount.get(), - false, - readerFailedCount.get(), - warningsCount.get()); + success.get(), failed.get(), wasStopped, readerFailed.get(), warnings.get()); } } @@ -800,6 +828,29 @@ public boolean isStopped() { public record BatchResult( int successCount, int failedCount, int warningsCount, String nextCursor) {} + // A retry on any node cannot repair a missed staged chunk delete, and the partition's FAILED row + // is what keeps the chunk generation from going live, so that failure is final at once. + private void failPartition(SearchIndexPartition partition, Exception failure) { + if (failure instanceof UnrecordedStagedChunkDeleteException) { + coordinator.failPartitionWithoutRetry(partition.getId(), failure.getMessage()); + } else { + coordinator.failPartition(partition.getId(), failure.getMessage()); + } + } + + /** + * A delete this node missed from the run's staged chunk generation, with no flag saved to block + * its promotion, fails the partition for good instead; the coordinator then keeps the old chunks. + */ + private static void requireStagedChunkFailuresRecorded(String entityType) { + SearchRepository searchRepository = Entity.getSearchRepository(); + VectorIndexService vectorService = + searchRepository == null ? null : searchRepository.getVectorIndexService(); + if (vectorService != null && AvailableEntityTypes.isVectorIndexable(entityType)) { + vectorService.requireStagedChunkFailuresRecorded(); + } + } + public record PartitionResult( long successCount, long failedCount, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java index 4f28c9e4d38f..3dc867b45882 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java @@ -1427,7 +1427,7 @@ private StepValidation retryInitAndReportError( .withDescription(description) .withMessage( "Vector search service could not be initialized. " - + "The embedding client is configured but the OpenSearch vector service failed to start." + + "The embedding client is configured but the vector service failed to start." + errorSuffix + " " + configMessage) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java index 9204c7e0ae03..d1ddefd1b7dd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java @@ -196,6 +196,7 @@ public boolean finalizeReindex(EntityReindexContext context, boolean reindexSucc } stampPromoted(entityType); + onStagedIndexPromoted(context); promoted = true; for (String oldIndex : oldIndicesToDelete) { @@ -412,6 +413,7 @@ public boolean promoteEntityIndex(EntityReindexContext context, boolean reindexS } stampPromoted(entityType); + onStagedIndexPromoted(context); promoted = true; for (String oldIndex : oldIndicesToDelete) { @@ -447,6 +449,13 @@ public boolean promoteEntityIndex(EntityReindexContext context, boolean reindexS * reindex job stats/failures, not in mapping drift. Best-effort: a stamping failure must not * fail a promotion that already succeeded. */ + /** + * Called once a staged entity index has replaced the live one, unlike the {@code true} that + * {@link #finalizeReindex} and {@link #promoteEntityIndex} also return when an empty staged index + * is discarded and the live index stays. + */ + protected void onStagedIndexPromoted(EntityReindexContext context) {} + private void stampPromoted(String entityType) { CollectionDAO collectionDAO = Entity.getCollectionDAO(); if (collectionDAO != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java index 22ea041cccef..343345d4e064 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java @@ -20,6 +20,10 @@ public class EntityReindexContext { * callbacks must never complete or promote a stale staged generation). */ String stagedChunkIndex; + /** A node could not record a delete it missed in {@link #stagedChunkIndex} and failed one of + * this type's partitions instead, so the run's chunk generation must keep its live chunks. */ + boolean stagedChunkDeleteUnrecorded; + String canonicalAliases; Set existingAliases; Set parentAliases; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/OntologyTermBulkWrite.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/OntologyTermBulkWrite.java index 7c092442a656..aee883750477 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/OntologyTermBulkWrite.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/OntologyTermBulkWrite.java @@ -19,6 +19,7 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.search.elasticsearch.ElasticSearchClient; import org.openmetadata.service.search.indexes.OntologyTermIndex; +import org.openmetadata.service.search.vector.StoredEmbeddingReuse; import org.openmetadata.service.search.vector.VectorIndexService; import os.org.opensearch.client.opensearch._types.BuiltinScriptLanguage; import os.org.opensearch.client.opensearch._types.Script; @@ -84,7 +85,7 @@ private static Map cachedEmbeddings( final int dimension = client == null ? -1 : client.getDimension(); final var cached = vectorService.getExistingEmbeddingsBatch(source, fingerprints); return cached.entrySet().stream() - .filter(entry -> VectorIndexService.canReuseCachedEmbedding(entry.getValue(), dimension)) + .filter(entry -> StoredEmbeddingReuse.isSpliceable(entry.getValue(), dimension)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java index fe28522b358d..389e4f089cee 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java @@ -4,16 +4,21 @@ import java.io.UncheckedIOException; import java.util.Locale; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.system.EventPublisherJob; import org.openmetadata.service.Entity; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; @Slf4j public class RecreateWithEmbeddings extends DefaultRecreateHandler { + // Entity types whose staged entity index replaced the live one during the current callback. A + // type is finalized by one callback at a time, so the set never holds a type for two calls. + private final Set promotedEntityTypes = ConcurrentHashMap.newKeySet(); + @Override public ReindexContext reCreateIndexes(Set entities) { SearchRepository searchRepository = Entity.getSearchRepository(); @@ -33,8 +38,12 @@ public ReindexContext reCreateIndexes(Set entities) { return context; } + private static VectorIndexService vectorService() { + return Entity.getSearchRepository().getVectorIndexService(); + } + private void clearStagedChunkStateQuietly(String stagedChunkIndex) { - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + VectorIndexService vectorService = vectorService(); if (stagedChunkIndex != null && vectorService != null) { vectorService.clearStagedChunkState(stagedChunkIndex); } @@ -45,28 +54,30 @@ private void clearStagedChunkStateQuietly(String stagedChunkIndex) { * index, so chunks of entities that no longer exist (DB restore/wipe — no delete events) don't * survive the rebuild and keep surfacing in AI retrieval. The recreate is STAGED: the run writes * into a bare next-generation index (reusing the live generation's stored vectors for unchanged - * entities, so the rebuild does not re-embed the whole catalog), and the generation is only - * promoted — one atomic alias swap, old data removed — after every data-asset chunk type - * finalizes successfully (see {@link #finalizeReindex}); any failure before promotion leaves the - * old chunks fully live. Guarded two ways (see {@link #shouldStageChunkRecreate}): the run must + * entities, so the rebuild does not re-embed the whole catalog), and the generation goes live + * with the entity indexes — one atomic alias swap, old data removed — once every data-asset + * chunk type has finalized and its staged entity index was promoted (see {@link + * #finalizeReindex}); a type whose entity index kept its live index keeps the old chunks live. + * Guarded two ways (see {@link #shouldStageChunkRecreate}): the run must * be job-driven (the jobless ops-CLI createIndexes path must not stage), and it must cover every * vector-indexable entity type (a partial recreate must not stage a sweep of types it will not * re-embed). */ private String recreateChunkIndexIfFullRun(Set entities) { - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); - if (vectorService == null || entities == null || getJobData() == null) { - return null; - } - if (shouldStageChunkRecreate(getJobData(), entities)) { - return vectorService.beginStagedChunkRecreate(); + VectorIndexService vectorService = vectorService(); + String stagedGeneration = null; + if (vectorService != null && entities != null && getJobData() != null) { + if (shouldStageChunkRecreate(getJobData(), entities)) { + stagedGeneration = vectorService.beginStagedChunkRecreate(); + } else { + LOG.info( + "Partial recreate ({} of {} vector-indexable types) — keeping the chunk index; " + + "orphaned chunks, if any, are only swept by a full recreate", + coveredVectorTypeCount(entities), + AvailableEntityTypes.DATA_ASSET_CHUNK_TYPES.size()); + } } - LOG.info( - "Partial recreate ({} of {} vector-indexable types) — keeping the chunk index; orphaned " - + "chunks, if any, are only swept by a full recreate", - coveredVectorTypeCount(entities), - AvailableEntityTypes.DATA_ASSET_CHUNK_TYPES.size()); - return null; + return stagedGeneration; } /** @@ -102,9 +113,9 @@ public boolean promoteEntityIndex(EntityReindexContext context, boolean reindexS // Distributed full recreates promote entity indexes through this per-entity path instead of // finalizeReindex — without this hook the staged chunk generation would never reach its // completion gate on distributed runs. markEntityTypeReindexed is idempotent, so runs that - // invoke both callbacks for a type are harmless. The mark lives in a finally so a throwing - // promotion still reports the type (as failed) — otherwise the staged chunk run would wait - // forever instead of reaching a safe terminal state. + // invoke both callbacks for a type are harmless. A throwing promotion still reports the type + // (as not promoted) — otherwise the staged chunk run would wait forever instead of reaching a + // safe terminal state. boolean promoted = false; RuntimeException superFailure = null; try { @@ -112,11 +123,16 @@ public boolean promoteEntityIndex(EntityReindexContext context, boolean reindexS } catch (RuntimeException e) { superFailure = e; } - markChunkTypeOutcomeAndRethrow(context, reindexSuccess, superFailure); + markChunkTypeOutcomeAndRethrow(context, superFailure); sweepOntologyChunksAfterPromotion(context, promoted, reindexSuccess); return promoted; } + @Override + protected void onStagedIndexPromoted(EntityReindexContext context) { + promotedEntityTypes.add(context.getEntityType()); + } + @Override public boolean finalizeReindex(EntityReindexContext context, boolean reindexSuccess) { // Same shape as promoteEntityIndex: a throwing finalize must still report the type. @@ -127,7 +143,7 @@ public boolean finalizeReindex(EntityReindexContext context, boolean reindexSucc } catch (RuntimeException e) { superFailure = e; } - markChunkTypeOutcomeAndRethrow(context, reindexSuccess, superFailure); + markChunkTypeOutcomeAndRethrow(context, superFailure); sweepOntologyChunksAfterPromotion(context, promoted, reindexSuccess); if (reindexSuccess && Entity.getSearchRepository().isVectorEmbeddingEnabled()) { @@ -150,23 +166,24 @@ private void sweepOntologyChunksAfterPromotion( } /** - * Feeds the staged chunk recreate: promotes the staged generation once every vector-indexable - * type has completed successfully; a failed type (including a throwing super callback) keeps the - * old chunks live. Marks are bound to the callback's own run via the context's staged chunk - * generation, so a later run's callbacks can never complete a stale generation. When the super - * callback itself failed, a marking failure is logged rather than thrown so it cannot mask the - * original exception; otherwise (e.g. the promotion swap failing) it propagates and fails the - * job loudly. + * Feeds the staged chunk recreate with whether the type's staged entity index replaced its live + * one: the staged generation goes live once every vector-indexable type has finalized with its + * entity index promoted, and a type whose entity index stayed live keeps the old chunks live. + * Marks are bound to the callback's own run via the context's staged chunk generation, so a later + * run's callbacks can never complete a stale generation. When the super callback itself failed, + * a marking failure is logged rather than thrown so it cannot mask the original exception; + * otherwise (e.g. the promotion swap failing) it propagates and fails the job loudly. */ private void markChunkTypeOutcomeAndRethrow( - EntityReindexContext context, boolean reindexSuccess, RuntimeException superFailure) { + EntityReindexContext context, RuntimeException superFailure) { + boolean entityIndexPromoted = + promotedEntityTypes.remove(context.getEntityType()) + && !context.isStagedChunkDeleteUnrecorded(); try { - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + VectorIndexService vectorService = vectorService(); if (vectorService != null) { vectorService.markEntityTypeReindexed( - context.getEntityType(), - reindexSuccess && superFailure == null, - context.getStagedChunkIndex()); + context.getEntityType(), entityIndexPromoted, context.getStagedChunkIndex()); } } catch (RuntimeException markFailure) { if (superFailure == null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/AbstractVectorIndexService.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/AbstractVectorIndexService.java new file mode 100644 index 000000000000..3963bccfc2a2 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/AbstractVectorIndexService.java @@ -0,0 +1,2377 @@ +package org.openmetadata.service.search.vector; + +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.resilience4j.core.IntervalFunction; +import io.github.resilience4j.retry.Retry; +import io.github.resilience4j.retry.RetryConfig; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Supplier; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.context.ContextMemory; +import org.openmetadata.service.Entity; +import org.openmetadata.service.events.lifecycle.EntityLifecycleEventDispatcher; +import org.openmetadata.service.search.OntologyChunkIndex; +import org.openmetadata.service.search.OntologyTermSearch; +import org.openmetadata.service.search.SearchUtils; +import org.openmetadata.service.search.indexes.ContextMemoryIndex; +import org.openmetadata.service.search.vector.client.EmbeddingClient; +import org.openmetadata.service.search.vector.client.EmbeddingUnavailableException; +import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; +import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; +import org.openmetadata.service.security.policyevaluator.SubjectContext; + +/** + * The engine-neutral vector index: the dedicated chunk index and its staged recreate, chunk and + * entity-doc embedding writes, embedding reuse, and parent-grouped kNN search. An engine supplies + * only its dialect through the abstract hooks: how a request is sent, how the vector field is + * mapped, and how a kNN search is phrased. + */ +@Slf4j +public abstract class AbstractVectorIndexService implements VectorIndexService { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ALREADY_CLOSED_EXCEPTION = "already_closed_exception"; + private static final Retry GENERIC_REQUEST_RETRY = + Retry.of( + "vector-index-request", + RetryConfig.custom() + .maxAttempts(3) + .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2)) + .retryOnException( + error -> + error instanceof UncheckedIOException + && error.getCause() instanceof ClosedSegmentException) + .build()); + private static final int OVER_FETCH_MULTIPLIER = 2; + private static final long UNKNOWN_COUNT = -1L; + private static final String FINGERPRINT_FIELD = "fingerprint"; + private static final String PARENT_ID_FIELD = "parentId"; + private static final String ENTITY_TYPE_FILTER = "entityType"; + private static final String CHUNK_HEADER_FIELDS = + "fingerprint,chunkCount,docVersion," + + String.join( + ",", + ContextMemoryIndex.FIELD_STATUS, + ContextMemoryIndex.FIELD_ANCHOR_ID, + ContextMemoryIndex.FIELD_MEMORY_SCOPE, + ContextMemoryIndex.FIELD_MEMORY_TYPE, + ContextMemoryIndex.FIELD_PINNED); + + @Getter private final EmbeddingClient embeddingClient; + private final Function> readableAnchors; + + protected AbstractVectorIndexService( + EmbeddingClient embeddingClient, + Function> readableAnchors) { + this.embeddingClient = embeddingClient; + this.readableAnchors = readableAnchors; + } + + /** Status and body of one engine response. {@code body} is null when the engine sent none. */ + protected record RawResponse(int status, String body) {} + + /** The engine's name as it appears in error messages. */ + protected abstract String engineName(); + + /** + * Sends one request and returns whatever the engine answered, error statuses included, so the + * shared code decides what a 404 or a 5xx means. Throws only when no response arrived. + */ + protected abstract RawResponse performRequest(String method, String endpoint, String body) + throws IOException; + + /** The index-creation body that chunk mappings and aliases are added to: the engine's settings. */ + protected abstract ObjectNode chunkIndexSettings(); + + /** The mapping of the {@code embedding} field for vectors of {@code dimension}. */ + protected abstract ObjectNode embeddingFieldMapping(int dimension); + + /** A full search request body for a kNN over {@code vector}, honouring the parameters' filters. */ + protected abstract String buildKnnSearch( + float[] vector, VectorSearchParameters parameters, Set readableAnchorIds); + + /** + * Whether a kNN at {@code threshold} returns at most {@code k} hits. When it does, a larger page + * fetches nothing extra and, at larger offsets, can push from+size past {@code + * index.max_result_window}. + */ + protected abstract boolean knnReturnsAtMostK(double threshold); + + /** + * Whether ontology terms keep their chunks in {@link OntologyChunkIndex}. When they do not, a + * term's vector lives only on its term document and a kNN over ontology terms reads the term + * indexes. ADR:2026-11-23-ontology-terms-have-dedicated-search-indexes + */ + protected abstract boolean chunksOntologyTerms(); + + protected void registerVectorEmbeddingHandler() { + try { + VectorEmbeddingHandler handler = new VectorEmbeddingHandler(this); + // Replace, so a re-init hands over to the new service without a window in which entity + // writes see no vector handler at all. + EntityLifecycleEventDispatcher.getInstance().replaceHandler(handler); + LOG.info("Registered VectorEmbeddingHandler for entity lifecycle events"); + } catch (Exception e) { + LOG.error("Failed to register VectorEmbeddingHandler", e); + } + } + + @Override + public Map generateEmbeddingFields(EntityInterface entity) { + return VectorDocBuilder.buildEmbeddingFields(entity, embeddingClient); + } + + @Override + public void updateEntityEmbedding(EntityInterface entity, String entityIndexName) { + if (embeddingClient.isAvailable()) { + refreshEntityEmbedding(entity, entityIndexName); + } else { + LOG.debug("Embedding provider unavailable; skipping entity {}", entity.getId()); + } + } + + private void refreshEntityEmbedding(EntityInterface entity, String entityIndexName) { + try { + String entityId = entity.getId().toString(); + String existingFingerprint = getExistingFingerprint(entityIndexName, entityId); + String currentFingerprint = VectorDocBuilder.computeFingerprintForEntity(entity); + + if (currentFingerprint.equals(existingFingerprint)) { + LOG.debug("Skipping entity {} - fingerprint unchanged", entityId); + } else { + Map embeddingFields = generateEmbeddingFields(entity); + partialUpdateEntity(entityIndexName, entityId, embeddingFields); + } + } catch (EmbeddingUnavailableException unavailable) { + LOG.debug("Skipping embedding for entity {}: {}", entity.getId(), unavailable.getMessage()); + } catch (Exception e) { + LOG.error("Failed to update embedding for entity {}: {}", entity.getId(), e.getMessage(), e); + } + } + + private static final String CHUNK_INDEX_BASE = "data_asset_embeddings_chunks"; + private static final String INCOMPLETE_CHUNK_WRITES = "incompleteChunkWrites"; + private volatile boolean chunkIndexEnsured = false; + private volatile boolean ontologyChunkIndexEnsured; + + /** + * Name of the dedicated chunk index (issue #4789). Lives alongside the entity indices; the + * {@code dataAssetEmbeddings} alias is attached to it so the vector read path sees chunk docs + * together with legacy entity-doc embeddings during migration. + */ + public String getChunkIndexName() { + String clusterAlias = null; + try { + clusterAlias = Entity.getSearchRepository().getClusterAlias(); + } catch (Exception ignored) { + // No SearchRepository in standalone/test contexts; fall back to the unprefixed name. + } + return clusterAlias == null || clusterAlias.isEmpty() + ? CHUNK_INDEX_BASE + : clusterAlias.toLowerCase(Locale.ROOT) + "_" + CHUNK_INDEX_BASE; + } + + @Override + public void updateEntityEmbeddingChunks(EntityInterface entity) { + if (!OntologyTermSearch.isTerm(entity.getEntityReference().getType())) { + requireChunkIndexForWrite(); + updateEntityEmbeddingChunks(entity, getChunkIndexName()); + } else if (chunksOntologyTerms()) { + updateEntityEmbeddingChunks(entity, ontologyChunkWriteTarget()); + } + } + + /** + * Reindex-sink entry point for the reused-embedding backfill. During a staged recreate the write + * must go to the staged generation — chunks written to the live target die at promotion, + * silently dropping every unchanged entity from vector retrieval. The {@code recreateRun} flag + * comes from the sink's own ReindexContext, so writers of normal (non-recreate) runs never + * consult generation discovery and can never land in a crashed run's orphan. A chunk set that + * cannot be written, or needs the embedding provider while it is unavailable, is a miss the + * caller counts and retries; it never fails the entity, whose own embedding is already spliced. + */ + @Override + public boolean backfillEntityChunks(EntityInterface entity, String stagedChunkTarget) { + boolean written; + try { + String entityType = entity.getEntityReference().getType(); + written = + stagedChunkTarget == null || OntologyTermSearch.isTerm(entityType) + ? writeChunksIfStale(entity, chunkWriteTarget(entityType, null)) + : backfillStagedChunks(entity, stagedChunkTarget); + } catch (IOException | RuntimeException e) { + LOG.debug("Failed to backfill chunks for {}: {}", entity.getId(), e.getMessage()); + written = false; + } + return written; + } + + private String liveChunkWriteTarget() { + requireChunkIndexForWrite(); + return getChunkIndexName(); + } + + /** Ontology terms are not part of the data-asset chunk generation, staged or live. */ + private String chunkWriteTarget(String entityType, String stagedChunkTarget) { + return OntologyTermSearch.isTerm(entityType) + ? ontologyChunkWriteTarget() + : dataAssetChunkWriteTarget(stagedChunkTarget); + } + + private String dataAssetChunkWriteTarget(String stagedChunkTarget) { + return stagedChunkTarget == null ? liveChunkWriteTarget() : stagedChunkTarget; + } + + /** + * Created on the first write without the data-asset read alias, since ontology terms are read + * through their own index. Like the data-asset chunk index, it is only marked ensured once its + * mapping is current, and a write is refused while it is not. + */ + private String ontologyChunkWriteTarget() { + if (!chunksOntologyTerms()) { + throw new IllegalStateException(engineName() + " keeps no ontology chunk index"); + } + String index = OntologyChunkIndex.name(); + if (!ontologyChunkIndexEnsured) { + synchronized (this) { + if (!ontologyChunkIndexEnsured) { + ontologyChunkIndexEnsured = ensureOntologyChunkIndex(index); + } + } + } + if (!ontologyChunkIndexEnsured) { + throw new IllegalStateException("Ontology vector chunk index unavailable"); + } + return index; + } + + private boolean ensureOntologyChunkIndex(String index) { + String target = resolveLiveChunkTarget(index); + boolean ensured; + if (target == null) { + executeGenericRequest("PUT", "/" + index, buildChunkIndexMapping(false)); + ensured = true; + } else { + ensured = applyChunkMappingUpgradeIfStale(target); + } + return ensured; + } + + /** + * Staged-recreate variant of the sink backfill: writes the entity's chunk docs into the staged + * generation, reusing the live generation's stored vectors when the content fingerprint is + * unchanged (the sink only takes this path for unchanged entities), so a full recreate does not + * re-embed the whole catalog. Nothing is skipped — the staged generation starts empty, so every + * entity passes through exactly once ({@code stagedHeader} short-circuits retries). + */ + private boolean backfillStagedChunks(EntityInterface entity, String staged) + throws IOException { + String parentId = entity.getId().toString(); + String fingerprint = VectorDocBuilder.computeFingerprintForEntity(entity); + ChunkHeader stagedHeader = getChunkHeader(staged, parentId); + boolean written = true; + if (chunkRefresh(entity, fingerprint, stagedHeader) != ChunkRefresh.NONE) { + Optional>> chunkDocs = + stagedBackfillChunks(entity, parentId, fingerprint); + if (chunkDocs.isPresent()) { + replaceChunks(staged, parentId, chunkDocs.get(), previousCount(stagedHeader)); + } + written = chunkDocs.isPresent(); + } + return written; + } + + /** + * The entity's chunk documents, reusing the live generation's vectors when its text is + * unchanged, or empty when they need the embedding provider and it is unavailable. + */ + private Optional>> stagedBackfillChunks( + EntityInterface entity, String parentId, String fingerprint) { + String live = getChunkIndexName(); + ChunkHeader liveHeader = getChunkHeader(live, parentId); + Optional>> chunkDocs = Optional.empty(); + if (liveHeader != null && fingerprint.equals(liveHeader.fingerprint())) { + chunkDocs = Optional.of(rebuildChunksReusingEmbeddings(entity, live, parentId, liveHeader)); + } else if (embeddingClient.isAvailable()) { + chunkDocs = Optional.of(VectorDocBuilder.fromEntity(entity, embeddingClient)); + } + return chunkDocs; + } + + /** + * Single-embed dual-target write: builds the chunk documents once (one embedding call per + * chunk) and reuses chunk 0's embedding fields for the legacy entity-doc partial update, so a + * content change costs N embedding calls instead of N+1. Each target keeps its own + * fingerprint-based staleness check. + */ + @Override + public void updateEntityEmbeddings(EntityInterface entity, String entityIndexName) { + updateEntityEmbeddings(entity, entityIndexName, null); + } + + /** + * {@code ontologyBody} is the embedding text of an ontology term's active release. A term's + * embeddings are then written only while that release is still the published one, see {@link + * OntologyTermSearch#writeCurrentEmbedding}. A term without it is refused: embedding from the + * mutable working (draft) row would publish unpublished, not-in-active-release or deprecated + * terms with no publication check. Term rebuilds go through the release-aware bulk writer + * (reindex), see VectorEmbeddingHandler.refreshOntologyEmbedding and OntologyTermBulkWrite. + */ + @Override + public void updateEntityEmbeddings( + EntityInterface entity, String entityIndexName, String ontologyBody) { + boolean term = OntologyTermSearch.isTerm(entity.getEntityReference().getType()); + if (term && ontologyBody == null) { + LOG.warn( + "Skipping embedding for ontology term {} without a release body; rebuild term " + + "embeddings via the release-aware reindex path", + entity.getId()); + } else if (!embeddingClient.isAvailable()) { + LOG.debug("Embedding provider unavailable; skipping entity {}", entity.getId()); + } else if (term) { + refreshOntologyEmbeddings(entity, entityIndexName, ontologyBody); + } else { + refreshEntityEmbeddings(entity, entityIndexName); + } + } + + private void refreshOntologyEmbeddings( + EntityInterface entity, String entityIndexName, String ontologyBody) { + try { + String fingerprint = VectorDocBuilder.computeFingerprintForEntity(entity, ontologyBody); + if (chunksOntologyTerms()) { + refreshOntologyChunksAndEntityDoc(entity, entityIndexName, ontologyBody, fingerprint); + } else { + refreshOntologyEntityDoc(entity, entityIndexName, ontologyBody, fingerprint); + } + } catch (EmbeddingUnavailableException unavailable) { + LOG.debug("Skipping embeddings for entity {}: {}", entity.getId(), unavailable.getMessage()); + } catch (Exception e) { + LOG.error("Failed to update embeddings for entity {}: {}", entity.getId(), e.getMessage(), e); + } + } + + private void refreshOntologyChunksAndEntityDoc( + EntityInterface entity, String entityIndexName, String ontologyBody, String fingerprint) + throws IOException { + String parentId = entity.getId().toString(); + String chunkIndexName = ontologyChunkWriteTarget(); + boolean entityDocStale = !fingerprint.equals(getExistingFingerprint(entityIndexName, parentId)); + ChunkHeader header = getChunkHeader(chunkIndexName, parentId); + ChunkRefresh refresh = chunkRefresh(entity, fingerprint, header); + if (entityDocStale || refresh != ChunkRefresh.NONE) { + List> chunkDocs = + refresh == ChunkRefresh.RESTAMP + ? rebuildChunksReusingEmbeddings( + entity, chunkIndexName, parentId, header, ontologyBody) + : VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody); + OntologyTermSearch.writeCurrentEmbedding( + entity.getEntityReference(), + fingerprint, + () -> writeOntologyChunksAndEntityDoc(entity, fingerprint, entityIndexName, chunkDocs)); + } + } + + /** The chunk header is read again, under the term lock when the write is guarded. */ + private void writeOntologyChunksAndEntityDoc( + EntityInterface entity, + String fingerprint, + String entityIndexName, + List> chunkDocs) + throws IOException { + String parentId = entity.getId().toString(); + String chunkIndexName = ontologyChunkWriteTarget(); + ChunkHeader header = getChunkHeader(chunkIndexName, parentId); + if (chunkRefresh(entity, fingerprint, header) != ChunkRefresh.NONE) { + replaceChunks(chunkIndexName, parentId, chunkDocs, previousCount(header)); + } + if (!chunkDocs.isEmpty()) { + partialUpdateEntity( + entityIndexName, parentId, VectorDocBuilder.legacyEmbeddingFields(chunkDocs.getFirst())); + } + } + + private void refreshOntologyEntityDoc( + EntityInterface entity, String entityIndexName, String ontologyBody, String fingerprint) + throws IOException { + String entityId = entity.getId().toString(); + if (fingerprint.equals(getExistingFingerprint(entityIndexName, entityId))) { + LOG.debug("Skipping entity {} - fingerprint unchanged", entityId); + } else { + Map embeddingFields = + VectorDocBuilder.buildEmbeddingFields(entity, embeddingClient, ontologyBody); + OntologyTermSearch.writeCurrentEmbedding( + entity.getEntityReference(), + fingerprint, + () -> partialUpdateEntity(entityIndexName, entityId, embeddingFields)); + } + } + + private void refreshEntityEmbeddings(EntityInterface entity, String entityIndexName) { + try { + String parentId = entity.getId().toString(); + String currentFingerprint = VectorDocBuilder.computeFingerprintForEntity(entity); + boolean chunkIndexWritable = isChunkIndexWritable(); + boolean entityDocStale = + !currentFingerprint.equals(getExistingFingerprint(entityIndexName, parentId)); + if (chunkIndexWritable) { + refreshChunksAndEntityDoc(entity, entityIndexName, currentFingerprint, entityDocStale); + } else if (entityDocStale) { + LOG.warn( + "Vector chunk index unavailable; refreshing only the entity embedding for {}", + parentId); + refreshEntityDocOnly(entity, entityIndexName); + } + } catch (EmbeddingUnavailableException unavailable) { + LOG.debug("Skipping embeddings for entity {}: {}", entity.getId(), unavailable.getMessage()); + } catch (Exception e) { + LOG.error("Failed to update embeddings for entity {}: {}", entity.getId(), e.getMessage(), e); + } + } + + private void refreshChunksAndEntityDoc( + EntityInterface entity, + String entityIndexName, + String currentFingerprint, + boolean entityDocStale) + throws IOException { + String parentId = entity.getId().toString(); + String chunkIndexName = getChunkIndexName(); + ChunkHeader header = getChunkHeader(chunkIndexName, parentId); + ChunkRefresh refresh = chunkRefresh(entity, currentFingerprint, header); + if (entityDocStale || refresh != ChunkRefresh.NONE) { + List> chunkDocs = + refresh == ChunkRefresh.RESTAMP + ? rebuildChunksReusingEmbeddings(entity, chunkIndexName, parentId, header) + : VectorDocBuilder.fromEntity(entity, embeddingClient); + if (refresh != ChunkRefresh.NONE) { + writeLiveChunks(chunkIndexName, parentId, chunkDocs, header); + mirrorToStagedGeneration(parentId, chunkDocs); + } + if (entityDocStale && !chunkDocs.isEmpty()) { + partialUpdateEntity( + entityIndexName, + parentId, + VectorDocBuilder.legacyEmbeddingFields(chunkDocs.getFirst())); + } + } + } + + /** + * A failed chunk write leaves the old chunk header in place, so the entity's next update sees the + * chunks as stale and writes them again, even when the entity document is already current. + */ + private void writeLiveChunks( + String chunkIndexName, + String parentId, + List> chunkDocs, + ChunkHeader header) { + try { + replaceChunks(chunkIndexName, parentId, chunkDocs, previousCount(header)); + } catch (IOException | RuntimeException e) { + LOG.error( + "Failed to write chunks for {} into {}; the entity embedding is still refreshed: {}", + parentId, + chunkIndexName, + e.getMessage(), + e); + } + } + + private void refreshEntityDocOnly(EntityInterface entity, String entityIndexName) { + List> chunkDocs = VectorDocBuilder.fromEntity(entity, embeddingClient); + if (!chunkDocs.isEmpty()) { + partialUpdateEntity( + entityIndexName, + entity.getId().toString(), + VectorDocBuilder.legacyEmbeddingFields(chunkDocs.getFirst())); + } + } + + /** + * Reindex-sink chunk write. {@code stagedChunkTarget} is the staged generation created by the + * run's own reCreateIndexes call and carried in its ReindexContext — the same propagation the + * staged ENTITY indexes rely on — so writes are scoped to the current run by construction: + * partial recreates and normal runs carry no target and write to the live index, and a crashed + * run's orphan can never capture anything. + */ + @Override + public boolean writeEntityChunks( + String parentId, List> chunkDocs, String stagedChunkTarget) { + boolean written; + try { + String entityType = + chunkDocs.isEmpty() ? null : (String) chunkDocs.getFirst().get(ENTITY_TYPE_FILTER); + String target = chunkWriteTarget(entityType, stagedChunkTarget); + replaceChunks(target, parentId, chunkDocs, previousCount(getChunkHeader(target, parentId))); + written = true; + } catch (IOException | RuntimeException e) { + // The entity keeps its embedding either way; the caller counts and retries the miss. + LOG.debug("Failed to write chunk docs for {}: {}", parentId, e.getMessage()); + written = false; + } + return written; + } + + @Override + public void deleteEntityChunks(String parentId) { + // Always delete from the live index: a staged run can be abandoned, and a delete applied only + // to the staged generation would then be lost — the deleted entity's chunks would keep + // surfacing until the next full recreate, the exact staleness this feature exists to prevent. + deleteChunksFrom(getChunkIndexName(), parentId); + // Also delete from an in-flight staged generation so a promoted run does not resurrect them. + String staged = resolveChunkSinkTarget(); + if (staged != null && !deleteChunksFrom(staged, parentId)) { + blockPromotionForMissedDelete(staged); + } + } + + private boolean deleteChunksFrom(String indexName, String parentId) { + boolean deleted; + try { + ChunkHeader header = getChunkHeader(indexName, parentId); + if (header != null || !indexMissing(indexName)) { + removeChunkSet(indexName, parentId, previousCount(header)); + } + deleted = true; + } catch (Exception e) { + LOG.debug("Failed to delete chunks for {} from {}: {}", parentId, indexName, e.getMessage()); + deleted = false; + } + return deleted; + } + + /** + * Progressive disclosure for a single knowledge entity (the issue #4789 payoff): KNN over just + * this parent's chunks in the dedicated chunk index, returning the {@code textToLLMContext} of the + * top {@code k} chunks most relevant to {@code query}. Unlike {@link #search}, results are not + * collapsed by parent, so this yields several passages of one long article rather than a single + * representative — the mechanism that lets a get_asset_context bundle carry only excerpts. + * + *

Context memory visibility is resolved for {@code subjectContext} even though the parent is + * known: a parent may be a restricted memory, which yields no passages without it. + */ + @Override + public List searchChunksByParent( + String parentId, String query, int k, SubjectContext subjectContext) { + List passages = new ArrayList<>(); + try { + ensureChunkIndex(); + float[] vector = embeddingClient.embedQuery(query); + Map> filters = Map.of("parentId", List.of(parentId)); + VectorSearchParameters parameters = + new VectorSearchParameters(null, filters, k, 0, k, 0.0, null, subjectContext, null); + String queryJson = buildKnnSearch(vector, parameters, Set.of()); + String response = + executeGenericRequest("POST", "/" + getChunkIndexName() + "/_search", queryJson); + JsonNode hits = MAPPER.readTree(response).path("hits").path("hits"); + for (JsonNode hit : hits) { + String text = hit.path("_source").path("textToLLMContext").asText(null); + if (text != null && !text.isBlank()) { + passages.add(text); + } + } + } catch (Exception e) { + LOG.warn("Chunk retrieval failed for parent {}: {}", parentId, e.getMessage()); + } + return passages; + } + + // --- Staged chunk-index recreate: generation indexes promoted behind the read alias --- + // + // Full-recreate runs must sweep orphaned chunks (entities deleted without events — DB restore, + // wipe-and-remigrate), but dropping the live index up front turns any mid-run failure into a + // retrieval outage. Instead the run writes into a bare next-generation index + // ({chunk_base}_g), invisible to reads, and only when every vector-indexable entity type + // finalizes successfully, and no chunk write into the generation failed, is the generation + // promoted: one atomic _aliases call points the read and search aliases at it and removes the + // previous target. Any failure before promotion leaves the old chunks fully live; abandoned + // generations are swept at the next staged recreate. + + private final Object stagedChunkLock = new Object(); + private volatile String stagedChunkIndex; + private volatile Set stagedExpectedTypes = Set.of(); + private final Set stagedFinalizedTypes = ConcurrentHashMap.newKeySet(); + // Types whose entity index kept its live index. Any of them keeps the live chunks too. + private final Set stagedKeptLiveTypes = ConcurrentHashMap.newKeySet(); + // Generations this JVM saved, or failed to save, the missed-delete flag on. A new staged run or + // a participant leaving its run clears them. + private final Set flaggedGenerations = ConcurrentHashMap.newKeySet(); + private final Set unflaggedGenerations = ConcurrentHashMap.newKeySet(); + private final Set warnedMirrorGenerations = ConcurrentHashMap.newKeySet(); + private volatile boolean stagedDeleteMissed; + // Run-scoped staged chunk index latched by a non-coordinator participant from its ReindexContext + // (see latchParticipantStagedTarget). Null on the coordinator, which uses stagedChunkIndex; null + // on a participant whose reindex thread has not yet latched (startup race). Volatile: set by the + // participant's reindex thread, read by request threads via resolveChunkSinkTarget. + private volatile String participantStagedTarget; + + /** + * Begins a staged recreate for a full-recreate run: pre-flights the embedding client (a broken + * client would make the whole run pointless), sweeps generations orphaned by crashed runs, and + * creates the next generation bare — no aliases, so reads keep hitting the old chunks. + * + *

Returns {@code null} when the embedding client cannot serve a request, meaning "not staged": + * the caller carries on with a normal in-place reindex and the existing chunks stay live, exactly + * as they do for a partial recreate. An unreachable embedding provider is a reason not to stage a + * generation we could never finish — it is not a reason to fail the entity reindex, which does + * not need embeddings at all. Note the provider is only exercised here: client construction makes + * no call to it, and live indexing logs and continues on embedding errors, so a deployment with + * semantic search enabled but no working provider looks healthy right up until a reindex. + * + *

Also returns {@code null} when the live-target probe is indeterminate. Skipping the stage + * deletes nothing — the sweep below never runs — so an unanswerable probe is a reason to leave + * the chunk index alone, not to fail an entity reindex that does not depend on it. Throwing here + * took down the whole run before its first record. The promote path stays strict: that swap does + * remove the previous target, so it must know what the target is. + * + *

Still throws on index create — a half-made generation is a state the next run must not + * inherit silently. + */ + @Override + public String beginStagedChunkRecreate() { + String generation = null; + if (isEmbeddingAvailable()) { + synchronized (stagedChunkLock) { + generation = stageChunkGenerationIfLiveTargetKnown(); + } + } else { + LOG.warn( + "Embedding pre-flight failed — skipping the staged chunk recreate. The entity reindex " + + "continues and existing chunks stay live; orphaned chunks, if any, are swept by the " + + "next recreate that runs with a working embedding provider."); + } + return generation; + } + + /** Returns the new staged generation, or null when the live chunk target cannot be resolved. */ + private String stageChunkGenerationIfLiveTargetKnown() { + String base = getChunkIndexName(); + ResolvedLiveTarget resolved = tryResolveLiveChunkTarget(base); + String generation = null; + if (resolved.known()) { + String liveTarget = resolved.name(); + deleteOrphanChunkGenerations(base, liveTarget); + generation = nextChunkGenerationName(base); + try { + executeGenericRequest("PUT", "/" + generation, buildChunkIndexMapping(false)); + } catch (Exception e) { + throw new RuntimeException("Failed to create staged chunk index " + generation, e); + } + stagedChunkIndex = generation; + stagedExpectedTypes = AvailableEntityTypes.DATA_ASSET_CHUNK_TYPES; + stagedFinalizedTypes.clear(); + stagedKeptLiveTypes.clear(); + flaggedGenerations.clear(); + unflaggedGenerations.clear(); + stagedDeleteMissed = false; + LOG.info( + "Staged chunk index {} created; chunks stay live at {} until promotion", + generation, + liveTarget); + } + return generation; + } + + /** {@code name} is null on a fresh install; {@code known} is false when resolution failed. */ + private record ResolvedLiveTarget(boolean known, String name) {} + + private ResolvedLiveTarget tryResolveLiveChunkTarget(String base) { + ResolvedLiveTarget resolved; + try { + resolved = new ResolvedLiveTarget(true, requireResolvedLiveChunkTarget(base)); + } catch (RuntimeException e) { + LOG.warn( + "Could not determine the live chunk target for {} — skipping the staged chunk " + + "recreate. The entity reindex continues and existing chunks stay live.", + base, + e); + resolved = new ResolvedLiveTarget(false, null); + } + return resolved; + } + + /** + * Clears this JVM's staged-recreate state when the owning run dies before any type finalizes — + * without this, a later unrelated run's callbacks could complete and promote the dead + * generation. The bare generation index is left for the next staged recreate's sweep. + */ + @Override + public void clearStagedChunkState(String generation) { + synchronized (stagedChunkLock) { + if (generation.equals(stagedChunkIndex)) { + stagedChunkIndex = null; + stagedFinalizedTypes.clear(); + stagedKeptLiveTypes.clear(); + LOG.warn( + "Cleared staged chunk state for {} — its run died before finalization; the " + + "generation will be swept by the next staged recreate", + generation); + } + } + } + + /** + * Whether the embedding client can actually serve a request. Logged rather than thrown: the only + * caller treats an unavailable provider as "do not stage", and the stack trace belongs in the log + * next to the provider's own error, not wrapped in a reindex failure. + */ + private boolean isEmbeddingAvailable() { + boolean available; + try { + embeddingClient.embedQuery("chunk index recreate pre-flight"); + available = true; + } catch (Exception e) { + LOG.warn("Embedding client pre-flight failed: {}", e.getMessage(), e); + available = false; + } + return available; + } + + /** + * Records whether one entity type's staged entity index replaced its live index, for an active + * staged chunk recreate. Once every vector-indexable type has finalized, the chunk generation + * goes live with the entity indexes: it is promoted when they all were. A type whose entity index + * kept its live index keeps the live chunks too, so its chunks never vanish while its entities + * are still served. Missed per-entity chunk writes do not block promotion; they are counted, + * retried and heal later. This runs on the coordinator, the only JVM that finalizes entity types. + * No-op when no staged recreate is active or for non-vector types. + */ + @Override + public void markEntityTypeReindexed( + String entityType, boolean entityIndexPromoted, String runGeneration) { + String normalized = entityType == null ? null : entityType.toLowerCase(Locale.ROOT); + String generation = stagedChunkIndex; + if (generation != null && runGeneration != null && !generation.equals(runGeneration)) { + // Mark from a different run than the one that staged this generation — never count it. + LOG.warn( + "Ignoring chunk-type mark for {} bound to run generation {} while {} is staged", + entityType, + runGeneration, + generation); + } else if (generation != null && runGeneration == null && normalized != null) { + // A run WITHOUT chunk staging is finalizing types while staged state lingers on this JVM — + // stale leftovers of a dead run. Never count these marks toward promotion. + LOG.warn( + "Ignoring unbound chunk-type mark for {} — staged generation {} belongs to a dead run " + + "and will be swept by the next staged recreate", + entityType, + generation); + } else if (stagedChunkIndex != null + && normalized != null + && stagedExpectedTypes.contains(normalized)) { + recordTypeOutcome(normalized, entityIndexPromoted); + } + } + + // A type finalized twice keeps the live chunks once either call kept them, so a later call can + // never undo a run-level reason to keep them. + private void recordTypeOutcome(String entityType, boolean entityIndexPromoted) { + if (!entityIndexPromoted) { + stagedKeptLiveTypes.add(entityType); + } + stagedFinalizedTypes.add(entityType); + if (stagedFinalizedTypes.containsAll(stagedExpectedTypes)) { + promoteStagedChunkIndex(); + } + } + + /** + * Points the read and search aliases at the staged generation and removes the previous target in + * one atomic {@code _aliases} call — no window where reads see neither or both generations. + * Strict like the orphan sweep: a live target that cannot be resolved fails the promotion. + */ + private void promoteStagedChunkIndex() { + synchronized (stagedChunkLock) { + String generation = stagedChunkIndex; + if (generation != null) { + String base = getChunkIndexName(); + String liveTarget = requireResolvedLiveChunkTarget(base); + Optional keepLive = reasonToKeepLiveChunks(generation, liveTarget); + if (keepLive.isPresent()) { + LOG.warn( + "Staged chunk index {} is not promoted because {}; the live chunks stay and the " + + "next staged recreate sweeps it", + generation, + keepLive.get()); + } else { + swapInStagedGeneration(generation, base, liveTarget); + } + stagedChunkIndex = null; + } + } + } + + private Optional reasonToKeepLiveChunks(String generation, String liveTarget) { + Set keptLive = new TreeSet<>(stagedKeptLiveTypes); + String reason = null; + if (!keptLive.isEmpty()) { + reason = "the entity indexes of " + keptLive + " kept their live index"; + } else if (stagedDeleteMissed || isStagedGenerationIncomplete(generation)) { + reason = "a delete of a removed entity's chunks failed"; + } else if (!stagedCanReplaceLive(generation, liveTarget)) { + reason = "it holds no chunks while the live index does, or a count could not be read"; + } + return Optional.ofNullable(reason); + } + + /** An empty generation replaces only an empty live index; an unknown count keeps the live one. */ + private boolean stagedCanReplaceLive(String generation, String liveTarget) { + long staged = chunkDocCount(generation); + long live = liveTarget == null ? 0 : chunkDocCount(liveTarget); + return staged > 0 || (staged == 0 && live == 0); + } + + private long chunkDocCount(String indexName) { + long count = UNKNOWN_COUNT; + try { + executeGenericRequest("POST", "/" + indexName + "/_refresh", null); + String response = executeGenericRequest("GET", "/" + indexName + "/_count", null); + count = MAPPER.readTree(response).path("count").asLong(UNKNOWN_COUNT); + } catch (IOException | RuntimeException e) { + LOG.warn("Could not count the chunks in {}: {}", indexName, e.getMessage()); + } + return count; + } + + private void swapInStagedGeneration(String generation, String base, String oldTarget) { + try { + executeGenericRequest( + "POST", + "/_aliases", + buildChunkPromoteActions(generation, base, getIndexAlias(), oldTarget)); + } catch (RuntimeException e) { + throw new RuntimeException("Failed to promote staged chunk index " + generation, e); + } + chunkIndexEnsured = true; + LOG.info("Promoted staged chunk index {} (previous target: {})", generation, oldTarget); + } + + /** + * Any node whose delete from the generation failed flagged it on the index itself (see {@link + * #blockPromotionForMissedDelete}), so the coordinator sees participants' failures too. Strict + * like the swap: a flag that cannot be read fails the promotion. + */ + private boolean isStagedGenerationIncomplete(String generation) { + boolean incomplete; + try { + String mappingJson = executeGenericRequest("GET", "/" + generation + "/_mapping", null); + incomplete = + MAPPER + .readTree(mappingJson) + .path(generation) + .path("mappings") + .path("_meta") + .path(INCOMPLETE_CHUNK_WRITES) + .asBoolean(false); + } catch (IOException | RuntimeException e) { + throw new RuntimeException("Failed to read staged chunk index state " + generation, e); + } + return incomplete; + } + + /** + * A delete the staged generation missed would bring a removed entity's chunks back at promotion, + * so it is the one chunk failure that blocks promotion. The flag is a {@code _meta} entry rather + * than JVM state because the delete may fail on a participant while the coordinator promotes. + */ + private void blockPromotionForMissedDelete(String generation) { + if (generation.equals(stagedChunkIndex)) { + stagedDeleteMissed = true; + } + saveMissedDeleteFlagOnce(generation); + } + + private void saveMissedDeleteFlagOnce(String generation) { + if (!flaggedGenerations.contains(generation)) { + if (flagStagedGenerationIncomplete(generation)) { + flaggedGenerations.add(generation); + unflaggedGenerations.remove(generation); + } else { + unflaggedGenerations.add(generation); + } + } + } + + private boolean flagStagedGenerationIncomplete(String generation) { + boolean flagged; + try { + ObjectNode body = MAPPER.createObjectNode(); + body.set("_meta", chunkMeta().put(INCOMPLETE_CHUNK_WRITES, true)); + executeGenericRequest("PUT", "/" + generation + "/_mapping", body.toString()); + flagged = true; + } catch (RuntimeException e) { + LOG.error( + "Could not flag staged chunk index {} as missing a delete; this node's partition will " + + "fail unless a retry saves the flag: {}", + generation, + e.getMessage()); + flagged = false; + } + return flagged; + } + + /** + * Fails the caller's partition when this node missed a delete from the run's generation and + * could not save the flag that blocks its promotion. The failed partition reaches the coordinator + * through the job's partition records and keeps the type's live index, which blocks the swap. + */ + @Override + public void requireStagedChunkFailuresRecorded() { + String generation = stagedChunkIndex != null ? stagedChunkIndex : participantStagedTarget; + if (generation != null && unflaggedGenerations.contains(generation)) { + saveMissedDeleteFlagOnce(generation); + if (unflaggedGenerations.contains(generation)) { + throw new UnrecordedStagedChunkDeleteException(generation); + } + } + } + + private static final long SINK_TARGET_CACHE_MS = 15_000; + private volatile String cachedSinkTarget; + private volatile long cachedSinkTargetAt; + + /** + * Resolves the staged chunk target for the live-edit mirror ({@link #mirrorToStagedGeneration}) + * and delete ({@link #deleteEntityChunks}) paths. Resolution order: + * + *

    + *
  1. {@link #stagedChunkIndex} — the coordinator's own run-scoped generation, set by {@link + * #beginStagedChunkRecreate}. Coordinator-only; also gates promotion in {@link + * #markEntityTypeReindexed}, so it must never be set on a participant. + *
  2. {@link #participantStagedTarget} — a non-coordinator participant's run-scoped + * generation, latched from its {@code ReindexContext} by {@link + * #latchParticipantStagedTarget}. Authoritative for the run, so mirroring and deletes + * never depend on best-effort discovery — the gap that lost live edits when discovery + * cached a stale {@code null} on a participant JVM (see fd054753fa). + *
  3. Best-effort cluster-state probe ({@link #findActiveStagedGeneration}) with a short + * JVM-local cache that may hold {@code null} (no un-promoted {@code *_g*} index exists + * yet, or a transient probe failure). Reached only before a participant latches (startup + * race) or on a JVM with no run context; a {@code null} here is harmless for deletes but + * causes {@link #mirrorToStagedGeneration} to skip the mirror. + *
+ * + *

Sink writes ({@code writeEntityChunks} / {@code backfillEntityChunks}) do not use this + * helper: they receive the run-scoped target explicitly via {@code ReindexContext}. + */ + private String resolveChunkSinkTarget() { + String target = stagedChunkIndex; // coordinator-only fast path (also gates promotion) + if (target == null) { + target = participantStagedTarget; // participant latch from ReindexContext + } + if (target == null) { + long now = System.currentTimeMillis(); + if (now - cachedSinkTargetAt > SINK_TARGET_CACHE_MS) { + cachedSinkTarget = findActiveStagedGeneration(); + cachedSinkTargetAt = now; + } + target = cachedSinkTarget; + } + return target; + } + + /** + * Latches the run-scoped staged chunk index a participant received via its {@code + * ReindexContext}, so live-edit mirroring ({@link #mirrorToStagedGeneration}) and deletes ({@link + * #deleteEntityChunks}) read the authoritative run-scoped target instead of falling through to + * the best-effort probe in {@link #findActiveStagedGeneration}. That probe can hold a stale + * {@code null} for up to {@value SINK_TARGET_CACHE_MS}ms on a non-coordinator JVM (cached before + * the coordinator created the generation, or after a transient cluster-state failure), in which + * case the mirror silently no-ops and the live edit is stranded in the soon-to-be-removed old + * generation. Called once per run by {@code DistributedJobParticipant} before it streams, and + * cleared by {@link #clearParticipantStagedTarget} when the run ends. + * + *

Must NOT set {@link #stagedChunkIndex}: that field gates promotion in {@link + * #markEntityTypeReindexed} (checking {@code stagedFinalizedTypes} against {@code + * stagedExpectedTypes}) and is coordinator-only. {@code participantStagedTarget} is safe because + * the promotion path never reads it. + */ + @Override + public void latchParticipantStagedTarget(String staged) { + participantStagedTarget = staged; + } + + /** + * Clears the participant latch set by {@link #latchParticipantStagedTarget} when its run ends, so + * a later run cannot mirror or delete into a generation that belongs to a finished (promoted or + * abandoned) run. + */ + @Override + public void clearParticipantStagedTarget() { + participantStagedTarget = null; + flaggedGenerations.clear(); + unflaggedGenerations.clear(); + } + + /** Newest generation index not yet holding the read alias, or null when none exists. */ + private String findActiveStagedGeneration() { + String base = getChunkIndexName(); + String result = null; + long best = 0; + try { + JsonNode response = MAPPER.readTree(executeGenericRequest("GET", "/" + base + "_g*", null)); + Iterator names = response.fieldNames(); + while (names.hasNext()) { + String name = names.next(); + boolean promoted = response.path(name).path("aliases").has(base); + long generation = chunkGenerationNumber(name, base); + if (!promoted && generation > best) { + best = generation; + result = name; + } + } + } catch (Exception e) { + LOG.debug("Staged chunk generation lookup failed: {}", e.getMessage()); + } + return result; + } + + /** + * {@code _aliases} actions promoting a generation: attach the read alias and the search alias, + * and atomically remove the previous target (the legacy physical index on first promotion, an + * older generation afterwards). Null {@code oldTarget} (fresh install) emits no removal. + */ + static String buildChunkPromoteActions( + String generation, String readAlias, String searchAlias, String oldTarget) { + var actions = MAPPER.createArrayNode(); + actions.add( + MAPPER + .createObjectNode() + .set( + "add", MAPPER.createObjectNode().put("index", generation).put("alias", readAlias))); + actions.add( + MAPPER + .createObjectNode() + .set( + "add", + MAPPER.createObjectNode().put("index", generation).put("alias", searchAlias))); + if (oldTarget != null && !oldTarget.equals(generation)) { + actions.add( + MAPPER + .createObjectNode() + .set("remove_index", MAPPER.createObjectNode().put("index", oldTarget))); + } + ObjectNode body = MAPPER.createObjectNode(); + body.set("actions", actions); + return body.toString(); + } + + /** + * The physical index currently serving chunk reads: the alias target when the read name is an + * alias (post-promotion layout), the legacy physical index when it exists under the read name, + * or null on a fresh install. Throws when the cluster cannot answer, so callers can distinguish + * "nothing is live" from "could not tell". + * + *

Index-scoped by construction: {@code GET /{base}/_alias} names the index in the path, so a + * deployment whose search role only grants its own {@code *} prefix — every + * shared-tenancy cloud cluster — is authorized for it. The alias-scoped forms + * ({@code HEAD|GET /_alias/{base}}) name no index, so the cluster resolves them against _all and + * denies them with a 403, which can never degrade to "no alias". + * + *

One call covers both layouts because the response is keyed by physical index: the staged + * generation when {@code base} is the read alias, {@code base} itself when it is still the + * legacy physical index. A 404 means neither exists yet. + */ + private String resolveLiveChunkTargetStrict(String base) throws IOException { + RawResponse response = performRequest("GET", "/" + base + "/_alias", null); + String target = null; + if (response.status() == 404) { + LOG.debug("No chunk index or alias named {} — fresh install", base); + } else if (response.status() >= 400) { + throw failedRequest(response); + } else { + Iterator names = MAPPER.readTree(bodyOrEmptyObject(response)).fieldNames(); + target = names.hasNext() ? names.next() : null; + } + return target; + } + + /** + * Lenient resolution for the ensure/create path: a wrongly-null target there can only make an + * index create attempt fail and be retried — it can never delete anything. + */ + private String resolveLiveChunkTarget(String base) { + String target = null; + try { + target = resolveLiveChunkTargetStrict(base); + } catch (Exception e) { + LOG.warn("Could not resolve live chunk target for {}: {}", base, e.getMessage()); + } + return target; + } + + /** + * Strict resolution for destructive paths (orphan sweep, alias swap): an indeterminate probe + * aborts the operation, because a null target would read as "nothing is live" and let the sweep + * delete the live generation. + */ + private String requireResolvedLiveChunkTarget(String base) { + try { + return resolveLiveChunkTargetStrict(base); + } catch (Exception e) { + throw new RuntimeException("Cannot determine the live chunk target for " + base, e); + } + } + + /** + * Sweeps generation indexes that are not the live target — leftovers of crashed or never-promoted + * staged runs. Runs before creating the next generation, so an orphan can never swallow writes. + */ + private void deleteOrphanChunkGenerations(String base, String liveTarget) { + try { + String response = executeGenericRequest("GET", "/" + base + "_g*", null); + Iterator names = MAPPER.readTree(response).fieldNames(); + while (names.hasNext()) { + String name = names.next(); + if (!name.equals(liveTarget)) { + deleteOrphanGeneration(name); + } + } + } catch (Exception e) { + LOG.warn("Orphaned chunk generation sweep failed: {}", e.getMessage()); + } + } + + private void deleteOrphanGeneration(String name) { + try { + executeGenericRequest("DELETE", "/" + name, null); + LOG.info("Deleted orphaned staged chunk index {}", name); + } catch (Exception e) { + LOG.warn("Failed to delete orphaned staged chunk index {}: {}", name, e.getMessage()); + } + } + + /** Generation stamp of a chunk index name, or 0 for the legacy physical / non-generation name. */ + static long chunkGenerationNumber(String indexName, String chunkBase) { + long number = 0; + String prefix = chunkBase + "_g"; + if (indexName != null && indexName.startsWith(prefix)) { + try { + number = Long.parseLong(indexName.substring(prefix.length())); + } catch (NumberFormatException e) { + number = 0; + } + } + return number; + } + + /** + * Run-unique generation name (epoch-millis stamp) so a pending promote from a superseded run + * fails loudly on a missing index rather than silently aliasing another run's half-built one. + */ + static String nextChunkGenerationName(String chunkBase) { + return chunkBase + "_g" + System.currentTimeMillis(); + } + + /** + * Write-path gate: throws when the chunk index could not be ensured. A raw write against a + * missing index would auto-create it with dynamic mappings ({@code embedding} as float, not a + * vector field), permanently wedging vector search until manual index surgery — worse than the + * skipped write. Read paths stay lenient: reads cannot auto-create an index. + */ + private void requireChunkIndexForWrite() { + ensureChunkIndex(); + if (!chunkIndexEnsured) { + throw new IllegalStateException( + "Vector chunk index unavailable (create/upgrade failed); refusing chunk write that " + + "would auto-create it with a non-knn mapping"); + } + } + + private boolean isChunkIndexWritable() { + ensureChunkIndex(); + return chunkIndexEnsured; + } + + private void ensureChunkIndex() { + if (!chunkIndexEnsured) { + synchronized (this) { + if (!chunkIndexEnsured) { + // Only latch on success so a transient failure (e.g. a cluster outage during startup) + // is retried on the next write instead of disabling chunk indexing until restart. + chunkIndexEnsured = createChunkIndexIfAbsent(); + } + } + } + } + + private boolean createChunkIndexIfAbsent() { + String base = getChunkIndexName(); + boolean ensured = false; + try { + // Post-promotion the read name is an alias over the live generation; operate on the + // resolved physical target. On a fresh install, create the legacy physical layout — + // generations appear at the first staged recreate. + String target = resolveLiveChunkTarget(base); + if (target == null) { + executeGenericRequest("PUT", "/" + base, buildChunkIndexMapping(true)); + LOG.info("Created dedicated vector chunk index {}", base); + ensured = true; + } else { + // The search alias is normally attached at creation, but an index left over from a partial + // or manual setup may miss it — and reads via the alias would then silently skip all chunk + // docs. The alias PUT is idempotent. Only report "ensured" once the mapping is at the + // current version so a failed upgrade does not latch (and so docs are not stamped with the + // new docVersion into a still-stale mapping). + executeGenericRequest("PUT", "/" + target + "/_alias/" + getIndexAlias(), "{}"); + ensured = applyChunkMappingUpgradeIfStale(target); + } + } catch (Exception e) { + LOG.error("Failed to ensure chunk index {}: {}", base, e.getMessage()); + } + return ensured; + } + + /** + * When the chunk index already exists, compare its {@code _meta.chunkDocVersion} against the code + * {@link VectorDocBuilder#CHUNK_DOC_VERSION}; if the index is older, apply the additive + * {@code PUT _mapping} so the new denormalized fields become mappable. This is legal on a + * {@code dynamic:false} index and safe pre-backfill: old docs simply lack the new fields until a + * Search Reindex re-materializes them (the reindex reuses embeddings, so there is no re-embed + * cost — see {@link #updateEntityEmbeddingChunks(EntityInterface, String)}). + * + * @return {@code true} when the index is (already or now) at the current version; {@code false} + * when the upgrade could not be applied, so the caller leaves the index un-ensured and the + * PUT is retried on the next write rather than silently proceeding with a stale mapping. + */ + private boolean applyChunkMappingUpgradeIfStale(String indexName) { + boolean upgraded; + try { + String mappingJson = executeGenericRequest("GET", "/" + indexName + "/_mapping", null); + JsonNode mappings = MAPPER.readTree(mappingJson).path(indexName).path("mappings"); + int existingVersion = mappings.path("_meta").path("chunkDocVersion").asInt(0); + if (existingVersion < VectorDocBuilder.CHUNK_DOC_VERSION) { + executeGenericRequest("PUT", "/" + indexName + "/_mapping", buildChunkMappingUpgradeBody()); + LOG.info( + "Upgraded chunk index {} mapping chunkDocVersion {} -> {} (denormalized fields " + + "backfill on next Search Reindex)", + indexName, + existingVersion, + VectorDocBuilder.CHUNK_DOC_VERSION); + } + upgraded = true; + } catch (Exception e) { + LOG.error( + "Failed to upgrade chunk index {} mapping; leaving it un-ensured to retry on the next " + + "write rather than stamping docs with the new docVersion into a stale mapping: {}", + indexName, + e.getMessage()); + upgraded = false; + } + return upgraded; + } + + private String buildChunkIndexMapping(boolean withSearchAlias) { + var mappings = MAPPER.createObjectNode().put("dynamic", false); + mappings.set("properties", buildChunkProperties()); + mappings.set("_meta", chunkMeta()); + var root = chunkIndexSettings(); + root.set("mappings", mappings); + // Staged generations are created bare: attaching the search alias before promotion would make + // the half-built generation searchable alongside the live one. + if (withSearchAlias) { + root.set( + "aliases", MAPPER.createObjectNode().set(getIndexAlias(), MAPPER.createObjectNode())); + } + return root.toString(); + } + + /** + * Additive {@code PUT _mapping} body applied by {@link #applyChunkMappingUpgradeIfStale}. Sends the + * property set minus the {@code embedding} vector field plus the bumped + * {@code _meta.chunkDocVersion}. Re-declaring the existing vector field is rejected by some + * OpenSearch versions/plugins even with identical parameters; because {@code PUT _mapping} is + * atomic, that would fail the whole request and silently leave the genuinely new denormalized + * fields unmapped (on a {@code dynamic:false} index) while docs are still stamped with the new + * {@code docVersion} — defeating the rollout. Omitting the unchanged vector avoids that + * all-or-nothing failure; the remaining fields are additive (new fields) or legal no-ops + * (unchanged keyword/text/integer). + * + *

Absent-on-old-docs fields are inert for anything that merely scores or widens on them, so + * those upgrades carry no regression before the backfill runs. That is not true of a field a + * filter restricts on: {@code visibility}, {@code entityStatus} and {@code anchorId} are required + * by the context memory clause in {@link VectorSearchQueryBuilder}, where absence means exclusion + * rather than indifference. Memory chunks written before they were stamped therefore stay out of + * every KNN result, for admins too, until a Search Reindex restamps them — deliberately, since an + * unstamped document may be a Private, retired or anchored memory. {@code memoryScope}, + * {@code memoryType} and {@code pinned} (v8) restrict only a query that asks for them, so before + * the backfill such a query loses those memories' vector hits and never gains a wrong one. Weigh + * that before making any future field a filter depends on. + */ + private String buildChunkMappingUpgradeBody() { + ObjectNode properties = buildChunkProperties(); + properties.remove("embedding"); + var body = MAPPER.createObjectNode(); + body.set("properties", properties); + body.set("_meta", chunkMeta()); + return body.toString(); + } + + private ObjectNode chunkMeta() { + return MAPPER.createObjectNode().put("chunkDocVersion", VectorDocBuilder.CHUNK_DOC_VERSION); + } + + private ObjectNode buildChunkProperties() { + var properties = MAPPER.createObjectNode(); + properties.set("embedding", embeddingFieldMapping(embeddingClient.getDimension())); + // The three metric enums are mapped as real keywords, not source-only: they are cheap to index + // and are the natural facets to filter a metric search on (granularity DAY vs MONTH). + // Memory privacy and lifecycle fields must be filterable on every chunk. + for (String keyword : + List.of( + "parentId", + "fingerprint", + "entityType", + "fullyQualifiedName", + "serviceType", + "metricType", + "granularity", + "unitOfMeasurement", + "customUnitOfMeasurement", + "visibility", + "sharedWithIds", + ContextMemoryIndex.FIELD_ANCHOR_ID, + ContextMemoryIndex.FIELD_STATUS, + ContextMemoryIndex.FIELD_MEMORY_SCOPE, + ContextMemoryIndex.FIELD_MEMORY_TYPE)) { + properties.set(keyword, MAPPER.createObjectNode().put("type", "keyword")); + } + // name/displayName keep a keyword root but gain a `.keyword` subfield so the shard-fair exact + // (case_insensitive term) clauses, which target `.keyword`, resolve on chunk docs. + for (String keywordWithSub : List.of("name", "displayName")) { + properties.set(keywordWithSub, keywordWithKeywordSubfield()); + } + for (String integer : List.of("chunkIndex", "chunkCount", "docVersion")) { + properties.set(integer, MAPPER.createObjectNode().put("type", "integer")); + } + // Analyzed lexical parity fields. The dedicated chunk index defines no custom analyzers, so + // these use the default standard analyzer; full om_analyzer/compound parity is a Phase 4 + // index recreate. + for (String text : + List.of("textToEmbed", "textToLLMContext", "description", "fqnParts", "synonyms")) { + properties.set(text, MAPPER.createObjectNode().put("type", "text")); + } + properties.set("deleted", MAPPER.createObjectNode().put("type", "boolean")); + properties.set( + ContextMemoryIndex.FIELD_PINNED, MAPPER.createObjectNode().put("type", "boolean")); + properties.set("tags", objectKeyword("tagFQN")); + properties.set("domains", objectKeyword("name")); + properties.set("tier", objectKeyword("tagFQN")); + properties.set("certification", certificationMapping()); + // owners is a `nested` type: NLQ owner filters run a nested query over owners.name, and the + // context memory visibility filter runs one over owners.id. + properties.set("owners", nestedOwnersMapping()); + properties.set("service", nameDisplayNameObject()); + properties.set("database", nameDisplayNameObject()); + // Map name+displayName like service/database: buildDenormalizedFields copies both onto the + // chunk doc, so mapping only `name` would leave the denormalized displayName in _source but + // unindexed (dynamic:false), silently unfilterable and inconsistent with the entity index. + properties.set("databaseSchema", nameDisplayNameObject()); + properties.set("columns", columnsMapping()); + properties.set( + "relatedTerms", MAPPER.createObjectNode().put("type", "object").put("enabled", false)); + // Display-only: semantic_search returns a metric's expression, nothing filters or scores on it, + // and the code is already searchable through textToEmbed. `enabled: false` keeps it in _source + // without paying to index it on a dynamic:false index. + properties.set( + "metricExpression", MAPPER.createObjectNode().put("type", "object").put("enabled", false)); + return properties; + } + + private ObjectNode keywordWithKeywordSubfield() { + return (ObjectNode) + MAPPER + .createObjectNode() + .put("type", "keyword") + .set( + "fields", + MAPPER + .createObjectNode() + .set("keyword", MAPPER.createObjectNode().put("type", "keyword"))); + } + + private ObjectNode objectKeyword(String field) { + return (ObjectNode) + MAPPER + .createObjectNode() + .set( + "properties", + MAPPER + .createObjectNode() + .set(field, MAPPER.createObjectNode().put("type", "keyword"))); + } + + private ObjectNode nestedOwnersMapping() { + var properties = MAPPER.createObjectNode(); + properties.set("name", MAPPER.createObjectNode().put("type", "keyword")); + properties.set("id", MAPPER.createObjectNode().put("type", "keyword")); + return (ObjectNode) + MAPPER.createObjectNode().put("type", "nested").set("properties", properties); + } + + private ObjectNode nameDisplayNameObject() { + var props = MAPPER.createObjectNode(); + props.set("name", MAPPER.createObjectNode().put("type", "keyword")); + props.set("displayName", MAPPER.createObjectNode().put("type", "keyword")); + return (ObjectNode) MAPPER.createObjectNode().set("properties", props); + } + + private ObjectNode certificationMapping() { + var tagLabel = objectKeyword("tagFQN"); + return (ObjectNode) + MAPPER + .createObjectNode() + .put("type", "object") + .set("properties", MAPPER.createObjectNode().set("tagLabel", tagLabel)); + } + + private ObjectNode columnsMapping() { + var name = keywordWithKeywordSubfield(); + return (ObjectNode) + MAPPER.createObjectNode().set("properties", MAPPER.createObjectNode().set("name", name)); + } + + /** + * Multi-chunk write path (issue #4789): index one standalone document per body chunk into the + * dedicated chunk index, keyed {@code _}. Skips work when the whole-body + * fingerprint is unchanged. Chunk ids are deterministic, so a shrinking body is handled by + * bulk-deleting the trailing stale ids in the same request — no delete-by-query and no forced + * refresh on this hot path; visibility follows the index refresh interval. + */ + public void updateEntityEmbeddingChunks(EntityInterface entity, String chunkIndexName) { + try { + if (!writeChunksIfStale(entity, chunkIndexName)) { + LOG.debug("Embedding provider unavailable; skipping chunks of {}", entity.getId()); + } + } catch (EmbeddingUnavailableException unavailable) { + LOG.debug("Skipping chunk embeddings for {}: {}", entity.getId(), unavailable.getMessage()); + } catch (Exception e) { + LOG.error("Failed to update chunk embeddings for {}: {}", entity.getId(), e.getMessage(), e); + } + } + + /** + * Writes the entity's chunks into {@code chunkIndexName} when they are stale. Returns false, + * without calling the provider, when they need re-embedding while the provider is unavailable. + */ + private boolean writeChunksIfStale(EntityInterface entity, String chunkIndexName) + throws IOException { + String parentId = entity.getId().toString(); + ChunkHeader header = getChunkHeader(chunkIndexName, parentId); + String currentFingerprint = VectorDocBuilder.computeFingerprintForEntity(entity); + ChunkRefresh refresh = chunkRefresh(entity, currentFingerprint, header); + boolean written = refresh != ChunkRefresh.REEMBED || embeddingClient.isAvailable(); + if (refresh == ChunkRefresh.NONE) { + LOG.debug("Skipping chunk embedding for {} - content and filters current", parentId); + } else if (written) { + List> chunkDocs = + refresh == ChunkRefresh.RESTAMP + ? rebuildChunksReusingEmbeddings(entity, chunkIndexName, parentId, header) + : VectorDocBuilder.fromEntity(entity, embeddingClient); + replaceChunks(chunkIndexName, parentId, chunkDocs, previousCount(header)); + } + return written; + } + + /** + * Rebuild an entity's chunk docs for a docVersion migration by reusing the embeddings already + * stored on those chunk docs (fingerprint unchanged ⇒ same body ⇒ same chunking ⇒ 1:1 reusable + * vectors), so only the denormalized fields and {@code docVersion} change and no embedding call is + * made. Falls back to a full re-embed if the cached vectors can't all be recovered (partial/corrupt + * chunk set) or the re-chunk disagrees with the cached count. + */ + private List> rebuildChunksReusingEmbeddings( + EntityInterface entity, String chunkIndexName, String parentId, ChunkHeader header) { + return rebuildChunksReusingEmbeddings(entity, chunkIndexName, parentId, header, null); + } + + private List> rebuildChunksReusingEmbeddings( + EntityInterface entity, + String chunkIndexName, + String parentId, + ChunkHeader header, + String ontologyBody) { + Map vectors = + fetchExistingChunkVectors(chunkIndexName, parentId, header.chunkCount()); + List> chunkDocs; + if (vectors.size() == header.chunkCount()) { + chunkDocs = reuseEmbeddingsOrReembed(entity, parentId, vectors, ontologyBody); + } else { + LOG.info( + "Chunk docVersion rebuild for {} recovered {}/{} cached vectors; re-embedding", + parentId, + vectors.size(), + header.chunkCount()); + chunkDocs = VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody); + } + return chunkDocs; + } + + private List> reuseEmbeddingsOrReembed( + EntityInterface entity, + String parentId, + Map vectors, + String ontologyBody) { + List> chunkDocs; + try { + chunkDocs = VectorDocBuilder.fromEntityReusingEmbeddings(entity, vectors, ontologyBody); + } catch (RuntimeException e) { + LOG.info( + "Chunk docVersion rebuild for {} fell back to re-embedding: {}", + parentId, + e.getMessage()); + chunkDocs = VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody); + } + return chunkDocs; + } + + /** + * Batch-fetch the stored embedding vectors for an entity's chunk docs ({@code _0..N-1}), + * keyed by {@code chunkIndex}. Pulls only {@code embedding}+{@code chunkIndex} so the large vector + * payload is the only thing on the wire. + */ + private Map fetchExistingChunkVectors( + String chunkIndexName, String parentId, int chunkCount) { + Map vectors = new HashMap<>(); + if (chunkCount > 0) { + try { + List ids = new ArrayList<>(chunkCount); + for (int i = 0; i < chunkCount; i++) { + ids.add(parentId + "_" + i); + } + List sourceFields = List.of("embedding", "chunkIndex"); + for (JsonNode source : multiGetSources(chunkIndexName, ids, sourceFields).values()) { + float[] vector = toFloatArray(source.path("embedding")); + if (vector != null) { + vectors.put(source.path("chunkIndex").asInt(0), vector); + } + } + } catch (Exception e) { + LOG.warn( + "Failed to fetch existing chunk vectors for {}; will re-embed: {}", + parentId, + e.getMessage(), + e); + } + } + return vectors; + } + + private static float[] toFloatArray(JsonNode node) { + float[] out = null; + if (node != null && node.isArray() && !node.isEmpty()) { + out = new float[node.size()]; + for (int i = 0; i < node.size(); i++) { + out[i] = (float) node.get(i).asDouble(); + } + } + return out; + } + + /** Header of an entity's chunk set, read from chunk 0. */ + record ChunkHeader( + String fingerprint, + int chunkCount, + int docVersion, + String status, + String anchorId, + MemoryKind memoryKind) {} + + /** The memory kind a chunk was stamped with; filters read it, the fingerprint does not see it. */ + record MemoryKind(String scope, String type, boolean pinned) { + static MemoryKind of(ContextMemory memory) { + return new MemoryKind( + ContextMemoryIndex.memoryScopeValue(memory), + ContextMemoryIndex.memoryTypeValue(memory), + Boolean.TRUE.equals(memory.getPinned())); + } + + static MemoryKind read(JsonNode source) { + return new MemoryKind( + source.path(ContextMemoryIndex.FIELD_MEMORY_SCOPE).asText(null), + source.path(ContextMemoryIndex.FIELD_MEMORY_TYPE).asText(null), + source.path(ContextMemoryIndex.FIELD_PINNED).asBoolean(false)); + } + } + + /** How an entity's stored chunks must be brought up to date. */ + enum ChunkRefresh { + NONE, + /** Same embedded text: rewrite the metadata around the stored vectors, at no embedding cost. */ + RESTAMP, + REEMBED + } + + static ChunkRefresh chunkRefresh( + EntityInterface entity, String fingerprint, ChunkHeader header) { + ChunkRefresh refresh = ChunkRefresh.NONE; + if (header == null || !fingerprint.equals(header.fingerprint())) { + refresh = ChunkRefresh.REEMBED; + } else if (docVersionStale(header) || memoryFilterChanged(entity, header)) { + refresh = ChunkRefresh.RESTAMP; + } + return refresh; + } + + // Status and anchor gate memory visibility, and the kind narrows a filtered recall; none of them + // is embedded text, so the fingerprint cannot see them change. + private static boolean memoryFilterChanged(EntityInterface entity, ChunkHeader header) { + return entity instanceof ContextMemory memory + && (!Objects.equals(ContextMemoryIndex.statusValue(memory), header.status()) + || !ContextMemoryIndex.anchorId(memory).equals(header.anchorId()) + || !MemoryKind.of(memory).equals(header.memoryKind())); + } + + /** + * A recreate in flight would otherwise promote the chunks it copied before this update, the same + * staleness {@link #deleteEntityChunks} guards against for deletes. + */ + private void mirrorToStagedGeneration(String parentId, List> chunkDocs) { + String staged = resolveChunkSinkTarget(); + if (staged == null) { + LOG.debug("No staged chunk generation to mirror the live update for {}", parentId); + } else { + try { + replaceChunks(staged, parentId, chunkDocs, previousCount(getChunkHeader(staged, parentId))); + } catch (IOException | RuntimeException e) { + logMissedMirror(staged, parentId, e); + } + } + } + + /** + * A missed mirror leaves the generation with the chunks the reindex wrote for the entity, which + * the entity's next edit or the next reindex refreshes, so it never blocks promotion. The first + * miss per generation on this node is a warning; the rest are debug. + */ + private void logMissedMirror(String staged, String parentId, Exception failure) { + if (warnedMirrorGenerations.add(staged)) { + LOG.warn( + "Could not mirror a live edit of {} into staged chunk index {}: {}. It keeps the chunks " + + "the reindex wrote until the entity's next edit or the next reindex; later missed " + + "mirrors into it are logged at debug", + parentId, + staged, + failure.getMessage()); + } else { + LOG.debug("Could not mirror {} into staged {}: {}", parentId, staged, failure.getMessage()); + } + } + + private static boolean docVersionStale(ChunkHeader header) { + return header != null && header.docVersion() < VectorDocBuilder.CHUNK_DOC_VERSION; + } + + private static int previousCount(ChunkHeader header) { + return header == null ? 0 : header.chunkCount(); + } + + /** + * Real-time by-id GET of chunk 0's content and filter metadata. It sees unrefreshed writes and + * avoids a search request on each entity update. + */ + private ChunkHeader getChunkHeader(String indexName, String parentId) { + ChunkHeader header = null; + try { + String endpoint = + "/" + indexName + "/_doc/" + parentId + "_0?_source_includes=" + CHUNK_HEADER_FIELDS; + RawResponse response = performRequest("GET", endpoint, null); + JsonNode root = + response.status() < 400 + ? MAPPER.readTree(bodyOrEmptyObject(response)) + : MAPPER.missingNode(); + if (root.path("found").asBoolean(false)) { + JsonNode source = root.path("_source"); + header = + new ChunkHeader( + source.path("fingerprint").asText(null), + source.path("chunkCount").asInt(0), + source.path("docVersion").asInt(0), + source.path(ContextMemoryIndex.FIELD_STATUS).asText(null), + source.path(ContextMemoryIndex.FIELD_ANCHOR_ID).asText(null), + MemoryKind.read(source)); + } + } catch (Exception e) { + LOG.debug("No chunk header for {} in {}: {}", parentId, indexName, e.getMessage()); + } + return header; + } + + /** + * Overwrites chunk ids {@code 0..N-1} and deletes the trailing stale ids {@code + * N..previousCount-1} left behind by a shrinking body. Deletes are by id, so they do not depend + * on search visibility of prior writes. An empty set removes the parent's chunks. + */ + private void replaceChunks( + String indexName, String parentId, List> chunkDocs, int previousCount) + throws IOException { + if (chunkDocs.isEmpty()) { + removeChunkSet(indexName, parentId, previousCount); + } else { + if (previousCount == 0) { + cleanOrphanChunks(indexName, parentId); + } + writeChunkBulk(indexName, parentId, chunkDocs, previousCount); + } + } + + /** + * Chunk 0 carries the header the next update compares against, and a bulk request is not atomic. + * So the other chunks and the trailing deletes go first, and chunk 0 follows only when they all + * succeeded: a rejected chunk leaves the old header, and the next update writes the set again. + * + *

The header's {@code chunkCount} is also the bound every trim and delete trusts: no chunk id + * at or past it may be stored. A write that adds ids past the bound first raises it, see {@link + * #reserveChunkIds}. + */ + private void writeChunkBulk( + String indexName, String parentId, List> chunkDocs, int previousCount) + throws IOException { + if (chunkDocs.size() > Math.max(previousCount, 1)) { + reserveChunkIds(indexName, parentId, chunkDocs.getFirst()); + } + StringBuilder bodyChunks = new StringBuilder(); + for (int i = 1; i < chunkDocs.size(); i++) { + appendChunkIndex(bodyChunks, indexName, parentId, i, chunkDocs.get(i)); + } + appendChunkDeletes(bodyChunks, indexName, parentId, chunkDocs.size(), previousCount); + sendChunkBulk(indexName, parentId, bodyChunks); + if (!chunkDocs.isEmpty()) { + StringBuilder header = new StringBuilder(); + appendChunkIndex(header, indexName, parentId, 0, chunkDocs.getFirst()); + sendChunkBulk(indexName, parentId, header); + } + } + + /** + * Writes chunk 0 with the new {@code chunkCount} and no fingerprint before the ids past the old + * bound. A write that then stops part way leaves a header that covers every id it wrote, so a + * later trim or delete reaches them, and that no update reads as current, so the next one writes + * the set again. + */ + private void reserveChunkIds(String indexName, String parentId, Map header) + throws IOException { + Map pending = new LinkedHashMap<>(header); + pending.remove(FINGERPRINT_FIELD); + StringBuilder bulk = new StringBuilder(); + appendChunkIndex(bulk, indexName, parentId, 0, pending); + sendChunkBulk(indexName, parentId, bulk); + } + + /** + * Deletes every chunk of a parent. By id up to the header's bound first, which reaches writes the + * index has not refreshed yet, then by query for anything a header that was missing or behind + * did not cover. Chunk 0 goes last, so a delete that stops part way keeps the header and its + * bound for the retry. + */ + private void removeChunkSet(String indexName, String parentId, int previousCount) { + StringBuilder trailing = new StringBuilder(); + appendChunkDeletes(trailing, indexName, parentId, 1, previousCount); + sendChunkBulk(indexName, parentId, trailing); + deleteTrailingChunksByQuery(indexName, parentId); + StringBuilder header = new StringBuilder(); + appendChunkDeletes(header, indexName, parentId, 0, 1); + sendChunkBulk(indexName, parentId, header); + } + + /** Deletes the parent's chunks other than chunk 0 that a refreshed search can see. */ + private void deleteTrailingChunksByQuery(String indexName, String parentId) { + ObjectNode bool = MAPPER.createObjectNode(); + bool.putArray("filter").addObject().putObject("term").put(PARENT_ID_FIELD, parentId); + bool.putArray("must_not").addObject().putObject("ids").putArray("values").add(parentId + "_0"); + ObjectNode body = MAPPER.createObjectNode(); + body.putObject("query").set("bool", bool); + String response = + executeGenericRequest( + "POST", "/" + indexName + "/_delete_by_query?conflicts=proceed", body.toString()); + failOnDeleteByQueryFailures(indexName, parentId, response); + } + + private void failOnDeleteByQueryFailures(String indexName, String parentId, String response) { + JsonNode failures; + try { + failures = MAPPER.readTree(response).path("failures"); + } catch (IOException e) { + throw new IllegalStateException( + "Chunk delete for " + parentId + " in " + indexName + " returned an unparseable response", + e); + } + if (!failures.isEmpty()) { + throw new IllegalStateException( + "Chunk delete for " + parentId + " in " + indexName + " had failures: " + failures); + } + } + + private static void appendChunkIndex( + StringBuilder bulk, String indexName, String parentId, int index, Map doc) + throws IOException { + bulk.append("{\"index\":{\"_index\":\"") + .append(indexName) + .append("\",\"_id\":\"") + .append(parentId) + .append('_') + .append(index) + .append("\"}}\n") + .append(MAPPER.writeValueAsString(doc)) + .append('\n'); + } + + private void sendChunkBulk(String indexName, String parentId, StringBuilder bulk) { + if (!bulk.isEmpty()) { + String response = executeGenericRequest("POST", "/_bulk", bulk.toString()); + failOnBulkItemErrors(indexName, parentId, response); + } + } + + /** + * The bulk API reports per-item failures (rejected executions under load, mapping conflicts) as + * HTTP 200 with {@code errors:true} — exactly the failure class a heavy reindex produces. + * Silently accepting them would leave holes with no log trail; throwing surfaces the failure to + * the callers' catch-and-log so a partially-written entity is at least visible in the logs. + */ + private void failOnBulkItemErrors(String indexName, String parentId, String response) { + try { + JsonNode root = MAPPER.readTree(response); + if (root.path("errors").asBoolean(false)) { + throw new IllegalStateException( + "Bulk chunk write for " + + parentId + + " into " + + indexName + + " had item failures: " + + firstBulkItemErrors(root)); + } + } catch (IllegalStateException e) { + throw e; + } catch (Exception parseFailure) { + // Conservative: an unparseable 200 could be hiding item failures, and in a staged + // generation silently accepting it becomes a chunk drop at promotion. + throw new IllegalStateException( + "Bulk chunk write for " + + parentId + + " into " + + indexName + + " returned an unparseable response", + parseFailure); + } + } + + private static StringBuilder firstBulkItemErrors(JsonNode root) { + StringBuilder reasons = new StringBuilder(); + int reported = 0; + for (JsonNode item : root.path("items")) { + // replaceChunks emits index AND delete actions (trailing-chunk cleanup); create for + // completeness — each item is keyed by whichever action it was. + for (String action : BULK_ACTIONS) { + JsonNode error = item.path(action).path("error"); + if (!error.isMissingNode() && reported < 3) { + reasons.append(action).append(' '); + reasons.append(error.path("type").asText("?")).append(": "); + reasons.append(error.path("reason").asText("?")).append("; "); + reported++; + } + } + } + return reasons; + } + + private static final List BULK_ACTIONS = List.of("index", "delete", "create"); + + /** + * Belt-and-braces for a chunk set stored without its chunk-0 header, which only a write from + * before {@link #reserveChunkIds} can leave. {@code previousCount == 0} is overwhelmingly the + * brand-new-entity case on the write and reindex-backfill hot paths, so the guard is the cheapest + * primitive available — a real-time by-id existence probe of chunk 1 that never touches the + * search layer. Only when a trailing chunk survived without its header do we pay a + * delete-by-query heal. (A set missing both chunk 0 and chunk 1 evades the probe; a delete of the + * parent still removes it.) + */ + private void cleanOrphanChunks(String indexName, String parentId) { + try { + if (chunkDocExists(indexName, parentId + "_1")) { + LOG.warn("Healing orphan chunk docs for parent {} with missing chunk-0 header", parentId); + deleteTrailingChunksByQuery(indexName, parentId); + } + } catch (Exception e) { + LOG.debug("Orphan chunk cleanup skipped for {}: {}", parentId, e.getMessage()); + } + } + + /** + * A chunk index is created by the first write, so an entity deleted before that has nothing to + * delete. Only a 404 counts as missing: a probe that fails sends the delete, which reports its own + * failure. + */ + private boolean indexMissing(String indexName) { + boolean missing; + try { + missing = performRequest("HEAD", "/" + indexName, null).status() == 404; + } catch (IOException e) { + LOG.debug("Index existence probe failed for {}: {}", indexName, e.getMessage()); + missing = false; + } + return missing; + } + + private boolean chunkDocExists(String indexName, String docId) { + boolean exists = false; + try { + String endpoint = "/" + indexName + "/_doc/" + docId + "?_source=false"; + exists = performRequest("HEAD", endpoint, null).status() < 300; + } catch (Exception e) { + LOG.debug("Chunk existence probe failed for {}: {}", docId, e.getMessage()); + } + return exists; + } + + private static void appendChunkDeletes( + StringBuilder bulk, String indexName, String parentId, int fromIndex, int toExclusive) { + for (int i = fromIndex; i < toExclusive; i++) { + bulk.append("{\"delete\":{\"_index\":\"") + .append(indexName) + .append("\",\"_id\":\"") + .append(parentId) + .append('_') + .append(i) + .append("\"}}\n"); + } + } + + @Override + @SuppressWarnings("unchecked") + public VectorSearchResponse search(VectorSearchParameters parameters) { + String query = parameters.query(); + int size = parameters.size(); + int from = parameters.from(); + int k = parameters.k(); + double threshold = parameters.threshold(); + long start = System.currentTimeMillis(); + try { + float[] queryVector = embeddingClient.embedQuery(query); + LinkedHashMap>> byParent = new LinkedHashMap<>(); + int rawOffset = 0; + long totalHits = -1L; + boolean exhausted = false; + int requestedParents = from + size + 1; // Fetch one extra parent so hasMore is accurate. + int overFetchSize = Math.max(requestedParents * OVER_FETCH_MULTIPLIER, OVER_FETCH_MULTIPLIER); + if (knnReturnsAtMostK(threshold)) { + overFetchSize = Math.min(overFetchSize, k); + } + + String aliasName = vectorSearchTarget(parameters.filters()); + Set readableAnchorIds = readableAnchors.apply(parameters); + while (!exhausted && byParent.size() < requestedParents) { + String queryJson = + buildKnnSearch( + queryVector, + parameters.withPagination(overFetchSize, rawOffset), + readableAnchorIds); + String endpoint = + SearchUtils.appendPreferenceParam( + "/" + aliasName + "/_search", parameters.preference()); + if (aliasName.contains(OntologyChunkIndex.name())) { + // The ontology chunk index is created only by the first ontology embedding write. + endpoint += (endpoint.contains("?") ? "&" : "?") + "ignore_unavailable=true"; + } + String responseBody = executeGenericRequest("POST", endpoint, queryJson); + + JsonNode root = MAPPER.readTree(responseBody); + JsonNode hitsNode = root.path("hits").path("hits"); + totalHits = extractTotalHits(root); + + int pageHitCount = collectSearchHits(hitsNode, threshold, byParent); + if (pageHitCount == 0) { + exhausted = true; + break; + } + + rawOffset += pageHitCount; + exhausted = totalHits >= 0 ? rawOffset >= totalHits : pageHitCount < overFetchSize; + } + + List> results = new ArrayList<>(); + int parentCount = 0; + int skipped = 0; + for (List> chunks : byParent.values()) { + if (skipped < from) { + skipped++; + continue; + } + if (parentCount >= size) { + break; + } + results.addAll(chunks); + parentCount++; + } + + boolean hasMore = byParent.size() > (from + parentCount); + long tookMillis = System.currentTimeMillis() - start; + return new VectorSearchResponse( + tookMillis, results, totalHits >= 0 ? totalHits : null, hasMore); + } catch (Exception e) { + LOG.error("Vector search failed: {}", e.getMessage(), e); + throw new RuntimeException("Vector search failed", e); + } + } + + /** + * The data-asset alias, or the ontology terms' vector target when the filter asks for ontology + * terms. A filter that mixes both reads both. + */ + String vectorSearchTarget(Map> filters) { + List types = filters == null ? null : filters.get(ENTITY_TYPE_FILTER); + String target = getIndexAlias(); + if (types != null && types.stream().anyMatch(OntologyTermSearch::isTerm)) { + String ontologyTarget = ontologyVectorTarget(); + target = + types.stream().allMatch(OntologyTermSearch::isTerm) + ? ontologyTarget + : getIndexAlias() + "," + ontologyTarget; + } + return target; + } + + private String ontologyVectorTarget() { + return chunksOntologyTerms() + ? OntologyChunkIndex.name() + : Entity.getSearchRepository().getIndexOrAliasName(OntologyTermSearch.ALIAS); + } + + private static int collectSearchHits( + JsonNode hitsNode, + double threshold, + LinkedHashMap>> byParent) { + int pageHitCount = 0; + for (JsonNode hit : hitsNode) { + pageHitCount++; + double score = hit.path("_score").asDouble(0.0); + // OpenSearch applies a positive threshold as min_score in the query. Elasticsearch's kNN + // has no such option, and k-based retrieval on either engine returns low-scoring + // neighbors to fill the k count, so the threshold is enforced here as well. + if (score < threshold) { + continue; + } + + Map hitMap = MAPPER.convertValue(hit.path("_source"), Map.class); + hitMap.put("_score", score); + + String parentId = (String) hitMap.getOrDefault("parentId", hit.path("_id").asText()); + // Persist the fallback into the result map so consumers (e.g. SemanticSearchTool collapsing + // chunks by entity) see the same parentId this grouping used, matching the ES service. + hitMap.put("parentId", parentId); + List> group = + byParent.computeIfAbsent(parentId, ignored -> new ArrayList<>()); + // During chunk-index migration the same chunk can surface twice — once from the legacy + // entity-doc embedding and once from the dedicated chunk index. Keep the first (higher + // scoring) occurrence per chunkIndex. + if (!isDuplicateChunk(group, hitMap.get("chunkIndex"))) { + group.add(hitMap); + } + } + return pageHitCount; + } + + private static boolean isDuplicateChunk(List> group, Object chunkIndex) { + boolean duplicate = false; + Object key = normalizeChunkIndex(chunkIndex); + for (Map member : group) { + if (key.equals(normalizeChunkIndex(member.get("chunkIndex")))) { + duplicate = true; + break; + } + } + return duplicate; + } + + /** + * Every embedding writer (legacy entity-doc and chunk-index) sets {@code chunkIndex} — 0 for the + * legacy single-doc format — so a missing value can only come from exotic/manual docs. Treat it + * as chunk 0 so such a doc still dedupes against the real chunk 0 during dual-write migration. + */ + private static Object normalizeChunkIndex(Object chunkIndex) { + return chunkIndex == null ? 0 : chunkIndex; + } + + private static long extractTotalHits(JsonNode root) { + JsonNode totalNode = root.path("hits").path("total"); + long total = -1L; + if (totalNode.isIntegralNumber()) { + total = totalNode.asLong(-1L); + } else if (totalNode.isObject()) { + total = totalNode.path("value").asLong(-1L); + } + return total; + } + + @Override + public String getExistingFingerprint(String indexName, String entityId) { + String fingerprint = null; + try { + String query = + "{\"size\":1,\"_source\":[\"fingerprint\"]," + + "\"query\":{\"term\":{\"_id\":\"" + + VectorSearchQueryBuilder.escape(entityId) + + "\"}}}"; + String response = executeGenericRequest("POST", "/" + indexName + "/_search", query); + JsonNode root = MAPPER.readTree(response); + JsonNode hits = root.path("hits").path("hits"); + if (hits.isArray() && !hits.isEmpty()) { + fingerprint = hits.get(0).path("_source").path("fingerprint").asText(null); + } + } catch (Exception e) { + LOG.debug( + "Failed to get fingerprint for entityId={} in index={}: {}", + entityId, + indexName, + e.getMessage()); + } + return fingerprint; + } + + @Override + public Map getExistingFingerprintsBatch( + String indexName, List entityIds) { + Map result = Collections.emptyMap(); + if (entityIds != null && !entityIds.isEmpty()) { + try { + result = searchFingerprints(indexName, entityIds); + } catch (Exception e) { + LOG.error("Failed to batch get fingerprints in index={}: {}", indexName, e.getMessage(), e); + } + } + return result; + } + + private Map searchFingerprints(String indexName, List entityIds) + throws IOException { + StringBuilder idsArray = new StringBuilder("["); + for (int i = 0; i < entityIds.size(); i++) { + if (i > 0) idsArray.append(','); + idsArray.append("\"").append(VectorSearchQueryBuilder.escape(entityIds.get(i))).append("\""); + } + idsArray.append("]"); + + String query = + "{\"size\":" + + entityIds.size() + + ",\"_source\":[\"fingerprint\"]" + + ",\"query\":{\"ids\":{\"values\":" + + idsArray + + "}}}"; + + String response = executeGenericRequest("POST", "/" + indexName + "/_search", query); + JsonNode root = MAPPER.readTree(response); + JsonNode hits = root.path("hits").path("hits"); + + Map result = new HashMap<>(); + for (JsonNode hit : hits) { + String id = hit.path("_id").asText(); + String fp = hit.path("_source").path("fingerprint").asText(null); + if (id != null && fp != null) { + result.put(id, fp); + } + } + return result; + } + + /** + * Two-step batch fetch of the stored embeddings a reindex may reuse, keyed by entity id. Designed + * to keep large vector payloads off the wire for entities that will be re-embedded anyway. + * + *

Step 1 — {@code mget} only the stored {@code fingerprint} for every requested ID and keep + * the IDs whose fingerprint equals the current one (see {@link StoredEmbeddingReuse}). + * + *

Step 2 — issue a second {@code mget} that pulls the full embedding {@code _source} only for + * matching IDs. Entries that don't match are dropped, and the caller can rely on every returned + * value being safe to splice into a staged index document. + * + * @param currentFingerprintById each entity's current fingerprint, computed only when a stored + * one exists + */ + @Override + public Map getExistingEmbeddingsBatch( + String indexName, Map> currentFingerprintById) { + Map reusable = Collections.emptyMap(); + if (!nullOrEmpty(currentFingerprintById)) { + try { + List matchingIds = idsWithCurrentFingerprint(indexName, currentFingerprintById); + if (!matchingIds.isEmpty()) { + reusable = + multiGetSources(indexName, matchingIds, VectorDocBuilder.EMBEDDING_SOURCE_FIELDS); + reusable.values().removeIf(cached -> !StoredEmbeddingReuse.isSpliceable(cached)); + } + } catch (Exception e) { + LOG.error("Failed to batch get embeddings in index={}", indexName, e); + reusable = Collections.emptyMap(); + } + } + return reusable; + } + + private List idsWithCurrentFingerprint( + String indexName, Map> currentFingerprintById) throws IOException { + List entityIds = new ArrayList<>(currentFingerprintById.keySet()); + List matchingIds = new ArrayList<>(); + multiGetSources(indexName, entityIds, StoredEmbeddingReuse.HEADER_FIELDS) + .forEach( + (id, header) -> { + Supplier currentFingerprint = currentFingerprintById.get(id); + if (currentFingerprint != null + && StoredEmbeddingReuse.fingerprintMatches(id, header, currentFingerprint)) { + matchingIds.add(id); + } + }); + return matchingIds; + } + + /** + * Realtime {@code _mget} of {@code sourceFields} for {@code ids}, keyed by document id. Ids with + * no stored document are absent. One attempt, like the by-id reads around it. + * + *

Naming the fields is what brings a stored vector back on Elasticsearch, which leaves a + * {@code dense_vector} out of {@code _source} unless the request asks for it. + */ + private Map multiGetSources( + String indexName, List ids, List sourceFields) throws IOException { + String endpoint = "/" + indexName + "/_mget?_source_includes=" + String.join(",", sourceFields); + ObjectNode body = MAPPER.createObjectNode(); + body.set("ids", MAPPER.valueToTree(ids)); + Map sources = new HashMap<>(); + JsonNode docs = MAPPER.readTree(requestOnce("POST", endpoint, body.toString())).path("docs"); + for (JsonNode doc : docs) { + JsonNode source = doc.path("_source"); + if (doc.path("found").asBoolean(false) && source.isObject()) { + sources.put(doc.path("_id").asText(), source); + } + } + return sources; + } + + public void partialUpdateEntity( + String indexName, String entityId, Map embeddingFields) { + try { + sendEmbeddingUpdate(indexName, entityId, embeddingFields); + } catch (Exception e) { + LOG.error( + "Failed to partial update entity {} in {}: {}", entityId, indexName, e.getMessage(), e); + } + } + + @Override + public boolean writeEntityEmbedding( + String entityIndexName, String entityId, Map embeddingFields) { + boolean written; + try { + sendEmbeddingUpdate(entityIndexName, entityId, embeddingFields); + written = true; + } catch (JsonProcessingException | RuntimeException e) { + LOG.debug( + "Failed to write the embedding of {} into {}: {}", + entityId, + entityIndexName, + e.getMessage()); + written = false; + } + return written; + } + + private void sendEmbeddingUpdate( + String indexName, String entityId, Map embeddingFields) + throws JsonProcessingException { + String updateBody = "{\"doc\":" + MAPPER.writeValueAsString(embeddingFields) + "}"; + executeGenericRequest( + "POST", "/" + indexName + "/_update/" + entityId + "?retry_on_conflict=3", updateBody); + } + + @Override + public void clearEntityEmbedding(String entityIndexName, String entityId) { + // A doc merge cannot delete keys, so removal has to go through a script. + try { + String fieldsJson = MAPPER.writeValueAsString(VectorDocBuilder.EMBEDDING_SOURCE_FIELDS); + String updateBody = + "{\"script\":{\"source\":\"for (field in params.fields) { ctx._source.remove(field) }\"," + + "\"params\":{\"fields\":" + + fieldsJson + + "}}}"; + executeGenericRequest( + "POST", + "/" + entityIndexName + "/_update/" + entityId + "?retry_on_conflict=3", + updateBody); + } catch (Exception e) { + LOG.error( + "Failed to clear embedding for entity {} in {}: {}", + entityId, + entityIndexName, + e.getMessage(), + e); + } + } + + @Override + public String executeGenericRequest(String method, String endpoint, String body) { + try { + return GENERIC_REQUEST_RETRY.executeSupplier( + () -> executeGenericRequestAttempt(method, endpoint, body)); + } catch (RuntimeException e) { + Throwable cause = e instanceof UncheckedIOException ? e.getCause() : e; + LOG.error("Generic request failed: {} {}", method, endpoint, cause); + throw new RuntimeException(engineName() + " generic request failed", cause); + } + } + + private String executeGenericRequestAttempt(String method, String endpoint, String body) { + try { + return requestOnce(method, endpoint, body); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private String requestOnce(String method, String endpoint, String body) throws IOException { + RawResponse response = performRequest(method, endpoint, body); + if (response.status() >= 400) { + throw failedRequest(response); + } + return bodyOrEmptyObject(response); + } + + private IOException failedRequest(RawResponse response) { + String errorBody = Objects.requireNonNullElse(response.body(), "no body"); + String message = + engineName() + " request failed with status " + response.status() + ": " + errorBody; + return response.status() >= 500 && errorBody.contains(ALREADY_CLOSED_EXCEPTION) + ? new ClosedSegmentException(message) + : new IOException(message); + } + + private static String bodyOrEmptyObject(RawResponse response) { + return Objects.requireNonNullElse(response.body(), "{}"); + } + + private static final class ClosedSegmentException extends IOException { + private ClosedSegmentException(String message) { + super(message); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/ElasticSearchVectorService.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/ElasticSearchVectorService.java index ec91a02dbbc7..bbec79e6c882 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/ElasticSearchVectorService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/ElasticSearchVectorService.java @@ -1,7 +1,7 @@ package org.openmetadata.service.search.vector; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import es.co.elastic.clients.elasticsearch.ElasticsearchClient; import es.co.elastic.clients.transport.ElasticsearchTransport; import es.co.elastic.clients.transport.rest5_client.Rest5ClientTransport; @@ -9,41 +9,33 @@ import es.co.elastic.clients.transport.rest5_client.low_level.Response; import es.co.elastic.clients.transport.rest5_client.low_level.ResponseException; import es.co.elastic.clients.transport.rest5_client.low_level.Rest5Client; +import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import java.util.Set; import java.util.function.Function; -import java.util.function.Supplier; -import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.EntityInterface; -import org.openmetadata.service.Entity; -import org.openmetadata.service.events.lifecycle.EntityLifecycleEventDispatcher; -import org.openmetadata.service.search.OntologyTermSearch; -import org.openmetadata.service.search.SearchUtils; +import org.apache.hc.core5.http.HttpEntity; import org.openmetadata.service.search.elasticsearch.MeteredElasticsearchTransport; import org.openmetadata.service.search.vector.client.EmbeddingClient; -import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; -import org.openmetadata.service.security.policyevaluator.SubjectContext; +/** + * The Elasticsearch dialect of the vector index: {@code dense_vector} mapping and the native + * top-level {@code knn} search. Elasticsearch has no search pipelines, so hybrid RRF ranking stays + * with {@link OpenSearchVectorService}. + */ @Slf4j -public class ElasticSearchVectorService implements VectorIndexService { +public class ElasticSearchVectorService extends AbstractVectorIndexService { private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final int OVER_FETCH_MULTIPLIER = 2; private static volatile ElasticSearchVectorService instance; - private final ElasticsearchClient client; private final Rest5Client restClient; - @Getter private final EmbeddingClient embeddingClient; private final int knnNumCandidatesMultiplier; - private final Function> readableAnchors; + + public ElasticSearchVectorService(ElasticsearchClient client, EmbeddingClient embeddingClient) { + this(client, embeddingClient, VectorSearchQueryBuilder.DEFAULT_KNN_NUM_CANDIDATES_MULTIPLIER); + } public ElasticSearchVectorService( ElasticsearchClient client, EmbeddingClient embeddingClient, int knnNumCandidatesMultiplier) { @@ -59,20 +51,14 @@ public ElasticSearchVectorService( EmbeddingClient embeddingClient, int knnNumCandidatesMultiplier, Function> readableAnchors) { - this.client = client; + super(embeddingClient, readableAnchors); this.restClient = extractRestClient(client); - this.embeddingClient = embeddingClient; - this.readableAnchors = readableAnchors; this.knnNumCandidatesMultiplier = knnNumCandidatesMultiplier > 0 ? knnNumCandidatesMultiplier : VectorSearchQueryBuilder.DEFAULT_KNN_NUM_CANDIDATES_MULTIPLIER; } - public ElasticSearchVectorService(ElasticsearchClient client, EmbeddingClient embeddingClient) { - this(client, embeddingClient, VectorSearchQueryBuilder.DEFAULT_KNN_NUM_CANDIDATES_MULTIPLIER); - } - private static Rest5Client extractRestClient(ElasticsearchClient client) { ElasticsearchTransport transport = MeteredElasticsearchTransport.unwrap(client._transport()); if (!(transport instanceof Rest5ClientTransport rest5)) { @@ -98,480 +84,78 @@ public static synchronized void init( embeddingClient.getDimension()); } - public static synchronized void init( - ElasticsearchClient client, EmbeddingClient embeddingClient) { - init(client, embeddingClient, VectorSearchQueryBuilder.DEFAULT_KNN_NUM_CANDIDATES_MULTIPLIER); - } - public static ElasticSearchVectorService getInstance() { return instance; } - private void registerVectorEmbeddingHandler() { - try { - VectorEmbeddingHandler handler = new VectorEmbeddingHandler(this); - // Replace, so a re-init hands over to the new service without a window in which entity - // writes see no vector handler at all. - EntityLifecycleEventDispatcher.getInstance().replaceHandler(handler); - LOG.info("Registered VectorEmbeddingHandler for entity lifecycle events"); - } catch (Exception e) { - LOG.error("Failed to register VectorEmbeddingHandler", e); - } - } - @Override - @SuppressWarnings("unchecked") - public VectorSearchResponse search( - String query, - Map> filters, - int size, - int from, - int k, - double threshold, - String preference, - SubjectContext subjectContext) { - return search( - new VectorSearchParameters( - query, filters, size, from, k, threshold, preference, subjectContext, null)); + protected String engineName() { + return "Elasticsearch"; } @Override - @SuppressWarnings("unchecked") - public VectorSearchResponse search(VectorSearchParameters parameters) { - String query = parameters.query(); - int size = parameters.size(); - int from = parameters.from(); - int k = parameters.k(); - double threshold = parameters.threshold(); - long start = System.currentTimeMillis(); - try { - // embedQuery, not embed: providers that distinguish the two (Cohere's search_query vs - // search_document input type) produce a worse vector for a question embedded as a - // document. The OpenSearch path already does this. - float[] queryVector = embeddingClient.embedQuery(query); - LinkedHashMap>> byParent = new LinkedHashMap<>(); - int rawOffset = 0; - long totalHits = -1L; - boolean exhausted = false; - int requestedParents = from + size + 1; - int overFetchSize = Math.max(requestedParents * OVER_FETCH_MULTIPLIER, OVER_FETCH_MULTIPLIER); - // ES native kNN never returns more than k hits (threshold is applied client-side in - // collectSearchHits), so a size larger than k fetches nothing extra and, for larger from, - // can push from+size past index.max_result_window and 400 the request. Clamp unconditionally. - overFetchSize = Math.min(overFetchSize, k); - - String indexName = vectorSearchTarget(parameters); - Set readableAnchorIds = readableAnchors.apply(parameters); - while (!exhausted && byParent.size() < requestedParents) { - String queryJson = - VectorSearchQueryBuilder.buildNativeESQuery( - queryVector, - parameters.withPagination(overFetchSize, rawOffset), - knnNumCandidatesMultiplier, - readableAnchorIds); - String endpoint = - SearchUtils.appendPreferenceParam( - "/" + indexName + "/_search", parameters.preference()); - String responseBody = executeGenericRequest("POST", endpoint, queryJson); - - JsonNode root = MAPPER.readTree(responseBody); - JsonNode hitsNode = root.path("hits").path("hits"); - totalHits = extractTotalHits(root); - - int pageHitCount = collectSearchHits(hitsNode, threshold, byParent); - if (pageHitCount == 0) { - exhausted = true; - break; - } - - rawOffset += pageHitCount; - exhausted = totalHits >= 0 ? rawOffset >= totalHits : pageHitCount < overFetchSize; - } - - List> results = new ArrayList<>(); - int parentCount = 0; - int skipped = 0; - for (List> chunks : byParent.values()) { - if (skipped < from) { - skipped++; - continue; - } - if (parentCount >= size) { - break; - } - results.addAll(chunks); - parentCount++; - } - - boolean hasMore = byParent.size() > (from + parentCount); - long tookMillis = System.currentTimeMillis() - start; - return new VectorSearchResponse( - tookMillis, results, totalHits >= 0 ? totalHits : null, hasMore); - } catch (Exception e) { - LOG.error("Vector search failed: {}", e.getMessage(), e); - throw new RuntimeException("Vector search failed", e); - } - } - - private static int collectSearchHits( - JsonNode hitsNode, - double threshold, - LinkedHashMap>> byParent) { - int pageHitCount = 0; - for (JsonNode hit : hitsNode) { - pageHitCount++; - double score = hit.path("_score").asDouble(0.0); - if (score < threshold) { - continue; - } - Map hitMap = MAPPER.convertValue(hit.path("_source"), Map.class); - hitMap.put("_score", score); - String parentId = (String) hitMap.getOrDefault("parentId", hit.path("_id").asText()); - // Persist the fallback into the result map so consumers (e.g. SemanticSearchTool - // via copyIfPresent) always see a populated parentId, not just the grouping key. - hitMap.put("parentId", parentId); - byParent.computeIfAbsent(parentId, ignored -> new ArrayList<>()).add(hitMap); + protected RawResponse performRequest(String method, String endpoint, String body) + throws IOException { + Request request = new Request(method, endpoint); + if (body != null) { + request.setJsonEntity(body); } - return pageHitCount; + Response response = respond(request); + return new RawResponse(response.getStatusCode(), readEntityBody(response.getEntity())); } - private static long extractTotalHits(JsonNode root) { - JsonNode totalNode = root.path("hits").path("total"); - if (totalNode.isIntegralNumber()) { - return totalNode.asLong(-1L); - } - if (totalNode.isObject()) { - return totalNode.path("value").asLong(-1L); - } - return -1L; - } - - @Override - public String executeGenericRequest(String method, String endpoint, String body) { + /** Rest5Client returns 4xx responses and throws 5xx ones; here both are just the response. */ + private Response respond(Request request) throws IOException { + Response response; try { - Request request = new Request(method, endpoint); - if (body != null) { - request.setJsonEntity(body); - } - // Rest5Client.performRequest only throws ResponseException on 5xx (its internal - // isCorrectServerResponse is `code < 500`). 4xx responses are returned normally, - // so we still need a manual status-code check below for client errors. - Response response = restClient.performRequest(request); - int statusCode = response.getStatusCode(); - String responseBody = readEntityBody(response.getEntity()); - if (statusCode >= 400) { - // 4xx path: Rest5Client returns these normally, so we surface the status - // and body in the exception message — symmetric to the OS path. - LOG.error("Generic request failed: {} {} status={}", method, endpoint, statusCode); - throw new RuntimeException( - "Elasticsearch request failed with status " + statusCode + ": " + responseBody); - } - return responseBody; + response = restClient.performRequest(request); } catch (ResponseException e) { - // 5xx path: format symmetrically with the OS generic-client error message. - int statusCode = e.getResponse().getStatusCode(); - String errorBody = readEntityBody(e.getResponse().getEntity()); - LOG.error("Generic request failed: {} {}", method, endpoint, e); - throw new RuntimeException( - "Elasticsearch request failed with status " + statusCode + ": " + errorBody, e); - } catch (RuntimeException e) { - // Already a RuntimeException with a meaningful message (e.g. our 4xx-status - // surface). Don't double-wrap and lose the message. - throw e; - } catch (Exception e) { - LOG.error("Generic request failed: {} {}", method, endpoint, e); - throw new RuntimeException("Elasticsearch generic request failed", e); - } - } - - private String vectorSearchTarget(VectorSearchParameters parameters) { - final var types = parameters.filters() == null ? null : parameters.filters().get("entityType"); - if (types == null || types.stream().noneMatch(OntologyTermSearch::isTerm)) { - return getIndexAlias(); + response = e.getResponse(); } - final var ontologyAlias = - Entity.getSearchRepository().getIndexOrAliasName(OntologyTermSearch.ALIAS); - return types.stream().allMatch(OntologyTermSearch::isTerm) - ? ontologyAlias - : getIndexAlias() + "," + ontologyAlias; - } - - /** - * Read an HttpEntity body as UTF-8, tolerating a null or unreadable entity. Some ES - * endpoints return no body on 4xx; dereferencing entity.getContent() unconditionally - * would NPE and mask the real HTTP status. - */ - private static String readEntityBody(org.apache.hc.core5.http.HttpEntity entity) { - if (entity == null) { - return ""; - } - try (InputStream is = entity.getContent()) { - return new String(is.readAllBytes(), StandardCharsets.UTF_8); - } catch (Exception ignored) { - return ""; - } - } - - @Override - public Map generateEmbeddingFields(EntityInterface entity) { - return generateEmbeddingFields(entity, null); + return response; } - public Map generateEmbeddingFields( - EntityInterface entity, String ontologyBody) { - return VectorDocBuilder.buildEmbeddingFields(entity, embeddingClient, ontologyBody); - } - - @Override - public void updateEntityEmbedding(EntityInterface entity, String entityIndexName) { - updateEntityEmbeddings(entity, entityIndexName, null); - } - - @Override - public void updateEntityEmbeddings( - EntityInterface entity, String entityIndexName, String ontologyBody) { - try { - String entityId = entity.getId().toString(); - final var type = entity.getEntityReference().getType(); - if (OntologyTermSearch.isTerm(type) && ontologyBody == null) { - // The 2-arg overload cannot safely publish a term: the release-aware writer needs the - // release-snapshot body, and embedding from the mutable working (draft) row would - // publish unpublished / not-in-active-release / deprecated terms with no publication - // check. Manual term reindexing must go through the release-aware bulk writer (reindex), - // which passes the published body into this 3-arg overload — see - // VectorEmbeddingHandler.refreshOntologyEmbedding and OntologyTermBulkWrite. - LOG.warn( - "Skipping embedding for ontology term {} without a release body; rebuild term " - + "embeddings via the release-aware reindex path", - entity.getId()); - return; - } - String existingFingerprint = getExistingFingerprint(entityIndexName, entityId); - String currentFingerprint = - ontologyBody == null - ? VectorDocBuilder.computeFingerprintForEntity(entity) - : VectorDocBuilder.computeFingerprintForEntity(entity, ontologyBody); - - if (currentFingerprint.equals(existingFingerprint)) { - LOG.debug("Skipping entity {} - fingerprint unchanged", entityId); - return; + private static String readEntityBody(HttpEntity entity) throws IOException { + String body = null; + if (entity != null) { + try (InputStream content = entity.getContent()) { + body = new String(content.readAllBytes(), StandardCharsets.UTF_8); } - - Map embeddingFields = generateEmbeddingFields(entity, ontologyBody); - if (OntologyTermSearch.isTerm(type)) { - OntologyTermSearch.writeCurrentEmbedding( - entity.getEntityReference(), - currentFingerprint, - () -> partialUpdateEntity(entityIndexName, entityId, embeddingFields)); - } else { - partialUpdateEntity(entityIndexName, entityId, embeddingFields); - } - } catch (Exception e) { - LOG.error("Failed to update embedding for entity {}: {}", entity.getId(), e.getMessage(), e); } + return body; } @Override - public String getExistingFingerprint(String indexName, String entityId) { - try { - String query = - "{\"size\":1,\"_source\":[\"fingerprint\"]," - + "\"query\":{\"term\":{\"_id\":\"" - + VectorSearchQueryBuilder.escape(entityId) - + "\"}}}"; - String response = executeGenericRequest("POST", "/" + indexName + "/_search", query); - JsonNode root = MAPPER.readTree(response); - JsonNode hits = root.path("hits").path("hits"); - if (hits.isArray() && !hits.isEmpty()) { - return hits.get(0).path("_source").path("fingerprint").asText(null); - } - } catch (Exception e) { - LOG.debug( - "Failed to get fingerprint for entityId={} in index={}: {}", - entityId, - indexName, - e.getMessage()); - } - return null; + protected ObjectNode chunkIndexSettings() { + return MAPPER.createObjectNode(); } @Override - public Map getExistingFingerprintsBatch( - String indexName, List entityIds) { - if (entityIds == null || entityIds.isEmpty()) { - return Collections.emptyMap(); - } - try { - StringBuilder idsArray = new StringBuilder("["); - for (int i = 0; i < entityIds.size(); i++) { - if (i > 0) idsArray.append(','); - idsArray - .append("\"") - .append(VectorSearchQueryBuilder.escape(entityIds.get(i))) - .append("\""); - } - idsArray.append("]"); - - String query = - "{\"size\":" - + entityIds.size() - + ",\"_source\":[\"fingerprint\"]" - + ",\"query\":{\"ids\":{\"values\":" - + idsArray - + "}}}"; - - String response = executeGenericRequest("POST", "/" + indexName + "/_search", query); - JsonNode root = MAPPER.readTree(response); - JsonNode hits = root.path("hits").path("hits"); - - Map result = new HashMap<>(); - for (JsonNode hit : hits) { - String id = hit.path("_id").asText(); - String fp = hit.path("_source").path("fingerprint").asText(null); - if (id != null && fp != null) { - result.put(id, fp); - } - } - return result; - } catch (Exception e) { - LOG.error("Failed to batch get fingerprints in index={}: {}", indexName, e.getMessage(), e); - return Collections.emptyMap(); - } + protected ObjectNode embeddingFieldMapping(int dimension) { + return MAPPER + .createObjectNode() + .put("type", "dense_vector") + .put("dims", dimension) + .put("index", true) + .put("similarity", "cosine"); } - private static final List EMBEDDING_SOURCE_FIELDS = - List.of( - "fingerprint", - "embedding", - "textToLLMContext", - "textToEmbed", - "chunkIndex", - "chunkCount", - "parentId"); - - /** - * Two-step batch fetch of the stored embeddings a reindex may reuse, keyed by entity id. Step 1 - * reads only the stored fingerprint and keeps the ids whose fingerprint equals the current one - * (see {@link StoredEmbeddingReuse}); step 2 pulls the full embedding _source for those, so large - * vectors stay off the wire for entities that will be re-embedded anyway. Mirrors - * OpenSearchVectorService (ES uses _search). - * - * @param currentFingerprintById each entity's current fingerprint, computed only when a stored - * one exists - */ @Override - public Map getExistingEmbeddingsBatch( - String indexName, Map> currentFingerprintById) { - if (currentFingerprintById == null || currentFingerprintById.isEmpty()) { - return Collections.emptyMap(); - } - try { - List entityIds = new ArrayList<>(currentFingerprintById.keySet()); - List matchingIds = new ArrayList<>(); - for (Map.Entry entry : - fetchSourceByIds(indexName, entityIds, StoredEmbeddingReuse.HEADER_FIELDS).entrySet()) { - Supplier currentFingerprint = currentFingerprintById.get(entry.getKey()); - if (currentFingerprint != null - && StoredEmbeddingReuse.fingerprintMatches( - entry.getKey(), entry.getValue(), currentFingerprint)) { - matchingIds.add(entry.getKey()); - } - } - if (matchingIds.isEmpty()) { - return Collections.emptyMap(); - } - Map result = new HashMap<>(); - for (Map.Entry entry : - fetchSourceByIds(indexName, matchingIds, EMBEDDING_SOURCE_FIELDS).entrySet()) { - if (StoredEmbeddingReuse.isSpliceable(entry.getValue())) { - result.put(entry.getKey(), entry.getValue()); - } - } - return result; - } catch (Exception e) { - LOG.error("Failed to batch get embeddings in index={}", indexName, e); - return Collections.emptyMap(); - } - } - - private Map fetchSourceByIds( - String indexName, List ids, List sourceFields) { - Map result = new HashMap<>(); - try { - String query = - "{\"size\":" - + ids.size() - + ",\"_source\":" - + toJsonArray(sourceFields, false) - + ",\"query\":{\"ids\":{\"values\":" - + toJsonArray(ids, true) - + "}}}"; - String response = executeGenericRequest("POST", "/" + indexName + "/_search", query); - JsonNode hits = MAPPER.readTree(response).path("hits").path("hits"); - for (JsonNode hit : hits) { - result.put(hit.path("_id").asText(), hit.path("_source")); - } - } catch (Exception e) { - LOG.error("Failed to fetch _source by ids in index={}: {}", indexName, e.getMessage(), e); - } - return result; - } - - private static String toJsonArray(List values, boolean escapeForQuery) { - StringBuilder array = new StringBuilder("["); - for (int i = 0; i < values.size(); i++) { - if (i > 0) { - array.append(','); - } - String value = - escapeForQuery ? VectorSearchQueryBuilder.escape(values.get(i)) : values.get(i); - array.append("\"").append(value).append("\""); - } - return array.append("]").toString(); - } - - public void partialUpdateEntity( - String indexName, String entityId, Map embeddingFields) { - try { - String docJson = MAPPER.writeValueAsString(embeddingFields); - String updateBody = "{\"doc\":" + docJson + "}"; - executeGenericRequest( - "POST", "/" + indexName + "/_update/" + entityId + "?retry_on_conflict=3", updateBody); - } catch (Exception e) { - LOG.error( - "Failed to partial update entity {} in {}: {}", entityId, indexName, e.getMessage(), e); - } + protected String buildKnnSearch( + float[] vector, VectorSearchParameters parameters, Set readableAnchorIds) { + return VectorSearchQueryBuilder.buildNativeESQuery( + vector, parameters, knnNumCandidatesMultiplier, readableAnchorIds); } @Override - public void clearEntityEmbedding(String entityIndexName, String entityId) { - // A doc merge cannot delete keys, so removal has to go through a script. - try { - String fieldsJson = MAPPER.writeValueAsString(EMBEDDING_SOURCE_FIELDS); - String updateBody = - "{\"script\":{\"source\":\"for (field in params.fields) { ctx._source.remove(field) }\"," - + "\"params\":{\"fields\":" - + fieldsJson - + "}}}"; - executeGenericRequest( - "POST", - "/" + entityIndexName + "/_update/" + entityId + "?retry_on_conflict=3", - updateBody); - } catch (Exception e) { - LOG.error( - "Failed to clear embedding for entity {} in {}: {}", - entityId, - entityIndexName, - e.getMessage(), - e); - } + protected boolean chunksOntologyTerms() { + // Ontology term vectors stay on the term documents, read through the ontologyTerms alias. + return false; } - public void close() { - // No-op by design, mirroring OpenSearchVectorService. The elasticsearch-java client stored - // here was constructed elsewhere and its Rest5Client transport is shared with - // ElasticSearchClient and every other manager. Closing the transport from here would shut - // down HTTP I/O for the whole application (the same failure mode as the OpenSearch - // "I/O reactor has been shut down" production incident). + @Override + protected boolean knnReturnsAtMostK(double threshold) { + // The native knn search never returns more than k hits; the threshold is applied afterwards. + return true; } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java index 82995f6e58bf..d552123634be 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java @@ -2,81 +2,35 @@ import static org.openmetadata.service.search.opensearch.OsUtils.loadVectorIndexMapping; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import io.github.resilience4j.core.IntervalFunction; -import io.github.resilience4j.retry.Retry; -import io.github.resilience4j.retry.RetryConfig; import java.io.IOException; -import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; -import java.util.function.Supplier; -import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.EntityInterface; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.service.Entity; -import org.openmetadata.service.events.lifecycle.EntityLifecycleEventDispatcher; -import org.openmetadata.service.search.OntologyChunkIndex; -import org.openmetadata.service.search.OntologyTermSearch; -import org.openmetadata.service.search.SearchUtils; -import org.openmetadata.service.search.indexes.ContextMemoryIndex; import org.openmetadata.service.search.vector.client.EmbeddingClient; -import org.openmetadata.service.search.vector.client.EmbeddingUnavailableException; -import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; -import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; -import org.openmetadata.service.security.policyevaluator.SubjectContext; -import os.org.opensearch.client.json.JsonData; -import os.org.opensearch.client.json.jackson.JacksonJsonpMapper; import os.org.opensearch.client.opensearch.OpenSearchClient; -import os.org.opensearch.client.opensearch._types.OpenSearchException; -import os.org.opensearch.client.opensearch.core.MgetResponse; -import os.org.opensearch.client.opensearch.core.get.GetResult; -import os.org.opensearch.client.opensearch.core.mget.MultiGetResponseItem; import os.org.opensearch.client.opensearch.generic.Body; -import os.org.opensearch.client.opensearch.generic.OpenSearchGenericClient; import os.org.opensearch.client.opensearch.generic.Request; import os.org.opensearch.client.opensearch.generic.Requests; import os.org.opensearch.client.opensearch.generic.Response; +/** + * The OpenSearch dialect of the vector index: {@code knn_vector} mapping, the {@code knn} query, + * and the hybrid RRF search pipeline, which only OpenSearch has. + */ @Slf4j -public class OpenSearchVectorService implements VectorIndexService { +public class OpenSearchVectorService extends AbstractVectorIndexService { private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final String ALREADY_CLOSED_EXCEPTION = "already_closed_exception"; - private static final Retry GENERIC_REQUEST_RETRY = - Retry.of( - "opensearch-vector-request", - RetryConfig.custom() - .maxAttempts(3) - .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2)) - .retryOnException( - error -> - error instanceof UncheckedIOException - && error.getCause() instanceof ClosedSegmentException) - .build()); - private static final int OVER_FETCH_MULTIPLIER = 2; public static final String HYBRID_PIPELINE_NAME = "hybrid-rrf"; private static volatile OpenSearchVectorService instance; private final OpenSearchClient client; - @Getter private final EmbeddingClient embeddingClient; - private final Function> readableAnchors; public OpenSearchVectorService(OpenSearchClient client, EmbeddingClient embeddingClient) { this(client, embeddingClient, VectorSearchMemoryAccess::readableAnchorIds); @@ -86,9 +40,8 @@ public OpenSearchVectorService(OpenSearchClient client, EmbeddingClient embeddin OpenSearchClient client, EmbeddingClient embeddingClient, Function> readableAnchors) { + super(embeddingClient, readableAnchors); this.client = client; - this.embeddingClient = embeddingClient; - this.readableAnchors = readableAnchors; } public static synchronized void init(OpenSearchClient client, EmbeddingClient embeddingClient) { @@ -108,18 +61,6 @@ public static OpenSearchVectorService getInstance() { return instance; } - private void registerVectorEmbeddingHandler() { - try { - VectorEmbeddingHandler handler = new VectorEmbeddingHandler(this); - // Replace, so a re-init hands over to the new service without a window in which entity - // writes see no vector handler at all. - EntityLifecycleEventDispatcher.getInstance().replaceHandler(handler); - LOG.info("Registered VectorEmbeddingHandler for entity lifecycle events"); - } catch (Exception e) { - LOG.error("Failed to register VectorEmbeddingHandler", e); - } - } - public void close() { // No-op by design. The opensearch-java client stored here was constructed elsewhere and its // transport is shared with OpenSearchClient and every other manager. Closing the transport @@ -231,927 +172,41 @@ private static String describeRejectedProbe(Response response) { } @Override - public Map generateEmbeddingFields(EntityInterface entity) { - return VectorDocBuilder.buildEmbeddingFields(entity, embeddingClient); + protected String engineName() { + return "OpenSearch"; } @Override - public void updateEntityEmbedding(EntityInterface entity, String entityIndexName) { - if (!embeddingClient.isAvailable()) { - LOG.debug("Embedding provider unavailable; skipping entity {}", entity.getId()); - return; - } - try { - String entityId = entity.getId().toString(); - String existingFingerprint = getExistingFingerprint(entityIndexName, entityId); - String currentFingerprint = VectorDocBuilder.computeFingerprintForEntity(entity); - - if (currentFingerprint.equals(existingFingerprint)) { - LOG.debug("Skipping entity {} - fingerprint unchanged", entityId); - return; - } - - Map embeddingFields = generateEmbeddingFields(entity); - partialUpdateEntity(entityIndexName, entityId, embeddingFields); - } catch (EmbeddingUnavailableException unavailable) { - LOG.debug("Skipping embedding for entity {}: {}", entity.getId(), unavailable.getMessage()); - } catch (Exception e) { - LOG.error("Failed to update embedding for entity {}: {}", entity.getId(), e.getMessage(), e); - } - } - - private static final String CHUNK_INDEX_BASE = "data_asset_embeddings_chunks"; - private volatile boolean ontologyChunkIndexEnsured; - private volatile boolean chunkIndexEnsured = false; - - /** - * Name of the dedicated chunk index (issue #4789). Lives alongside the entity indices; the - * {@code dataAssetEmbeddings} alias is attached to it so the vector read path sees chunk docs - * together with legacy entity-doc embeddings during migration. - */ - public String getChunkIndexName() { - return getChunkIndexName(CHUNK_INDEX_BASE); - } - - private String getOntologyChunkIndexName() { - return OntologyChunkIndex.name(); - } - - private String getChunkIndexName(String base) { - String clusterAlias = null; - try { - clusterAlias = Entity.getSearchRepository().getClusterAlias(); - } catch (Exception ignored) { - // No SearchRepository in standalone/test contexts; fall back to the unprefixed name. + protected RawResponse performRequest(String method, String endpoint, String body) + throws IOException { + var builder = Requests.builder().endpoint(endpoint).method(method); + if (body != null) { + builder.json(body); } - return clusterAlias == null || clusterAlias.isEmpty() - ? base - : clusterAlias.toLowerCase(Locale.ROOT) + "_" + base; - } - - @Override - public void updateEntityEmbeddingChunks(EntityInterface entity) { - updateEntityEmbeddingChunks( - entity, chunkTargetForWrite(entity.getEntityReference().getType()), null); - } - - /** - * Reindex-sink entry point for the reused-embedding backfill. During a staged recreate the write - * must go to the staged generation — chunks written to the live target die at promotion, - * silently dropping every unchanged entity from vector retrieval. The {@code recreateRun} flag - * comes from the sink's own ReindexContext, so writers of normal (non-recreate) runs never - * consult generation discovery and can never land in a crashed run's orphan. - */ - public void backfillEntityChunks(EntityInterface entity, String stagedChunkTarget) { - if (stagedChunkTarget == null) { - updateEntityEmbeddingChunks(entity); - } else { - backfillChunksToStagedGeneration(entity, stagedChunkTarget); + try (Response response = client.generic().execute(builder.build())) { + return new RawResponse( + response.getStatus(), response.getBody().map(this::readBody).orElse(null)); } } - /** - * Staged-recreate variant of the sink backfill: writes the entity's chunk docs into the staged - * generation, reusing the live generation's stored vectors when the content fingerprint is - * unchanged (the sink only takes this path for unchanged entities), so a full recreate does not - * re-embed the whole catalog. Nothing is skipped — the staged generation starts empty, so every - * entity passes through exactly once ({@code stagedHeader} short-circuits retries). - */ - private void backfillChunksToStagedGeneration(EntityInterface entity, String staged) { + private String readBody(Body body) { + String text; try { - String parentId = entity.getId().toString(); - String fingerprint = VectorDocBuilder.computeFingerprintForEntity(entity); - ChunkHeader stagedHeader = getChunkHeader(staged, parentId); - if (chunkRefresh(entity, fingerprint, stagedHeader) != ChunkRefresh.NONE) { - String live = getChunkIndexName(); - ChunkHeader liveHeader = getChunkHeader(live, parentId); - List> chunkDocs = - (liveHeader != null && fingerprint.equals(liveHeader.fingerprint())) - ? rebuildChunksReusingEmbeddings(entity, live, parentId, liveHeader) - : VectorDocBuilder.fromEntity(entity, embeddingClient); - replaceChunks(staged, parentId, chunkDocs, previousCount(stagedHeader)); - } - } catch (Exception e) { - // A failed chunk write is tolerated like any failed document index: the chunk is simply - // absent from the staged generation. Promotion is gated on the run's aggregate success - // (see markEntityTypeReindexed), so a run that failed overall never promotes; a sub-document - // failure on an otherwise-successful run leaves a gap that the next recreate heals. - LOG.error( - "Failed to backfill chunks for {} into staged {}: {}", - entity.getId(), - staged, - e.getMessage(), - e); + text = new String(body.bodyAsBytes(), StandardCharsets.UTF_8); + } catch (RuntimeException e) { + LOG.warn("Failed to read OpenSearch response body", e); + text = "{}"; } + return text; } - /** - * Single-embed dual-target write: builds the chunk documents once (one embedding call per - * chunk) and reuses chunk 0's embedding fields for the legacy entity-doc partial update, so a - * content change costs N embedding calls instead of N+1. Each target keeps its own - * fingerprint-based staleness check. - */ @Override - public void updateEntityEmbeddings(EntityInterface entity, String entityIndexName) { - updateEntityEmbeddings(entity, entityIndexName, null); + protected ObjectNode chunkIndexSettings() { + return loadVectorIndexMapping(); } @Override - public void updateEntityEmbeddings( - EntityInterface entity, String entityIndexName, String ontologyBody) { - if (!embeddingClient.isAvailable()) { - LOG.debug("Embedding provider unavailable; skipping entity {}", entity.getId()); - return; - } - try { - String parentId = entity.getId().toString(); - String currentFingerprint = fingerprint(entity, ontologyBody); - final var type = entity.getEntityReference().getType(); - if (OntologyTermSearch.isTerm(type) && ontologyBody == null) { - // The 2-arg overload cannot safely publish a term. The release-aware writer needs the - // release-snapshot body, and embedding from the mutable working (draft) row would - // publish unpublished / not-in-active-release / deprecated terms straight into the - // searchable ontology chunk index with no publication check. Manual term reindexing - // must go through the release-aware bulk writer (reindex), which passes the published - // body into the 3-arg overload — see VectorEmbeddingHandler.refreshOntologyEmbedding - // and OntologyTermBulkWrite. - LOG.warn( - "Skipping embedding for ontology term {} without a release body; rebuild term " - + "embeddings via the release-aware reindex path", - entity.getId()); - return; - } - String chunkIndexName = chunkTargetForWrite(type); - boolean entityDocStale = - !currentFingerprint.equals(getExistingFingerprint(entityIndexName, parentId)); - ChunkHeader header = getChunkHeader(chunkIndexName, parentId); - ChunkRefresh refresh = chunkRefresh(entity, currentFingerprint, header); - if (entityDocStale || refresh != ChunkRefresh.NONE) { - List> chunkDocs = - refresh == ChunkRefresh.RESTAMP - ? rebuildChunksReusingEmbeddings( - entity, chunkIndexName, parentId, header, ontologyBody) - : VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody); - if (!OntologyTermSearch.isTerm(type)) { - if (refresh != ChunkRefresh.NONE) { - replaceChunks(chunkIndexName, parentId, chunkDocs, previousCount(header)); - mirrorToStagedGeneration(parentId, chunkDocs); - } - if (entityDocStale && !chunkDocs.isEmpty()) { - partialUpdateEntity(entityIndexName, parentId, legacyEmbeddingFields(chunkDocs.get(0))); - } - } else { - writeCurrentOntologyEmbeddings( - entity, currentFingerprint, entityIndexName, chunkIndexName, chunkDocs); - } - } - } catch (EmbeddingUnavailableException unavailable) { - LOG.debug("Skipping embeddings for entity {}: {}", entity.getId(), unavailable.getMessage()); - } catch (Exception e) { - LOG.error("Failed to update embeddings for entity {}: {}", entity.getId(), e.getMessage(), e); - } - } - - private void writeCurrentOntologyEmbeddings( - EntityInterface entity, - String fingerprint, - String entityIndexName, - String chunkIndexName, - List> chunkDocs) - throws IOException { - OntologyTermSearch.writeCurrentEmbedding( - entity.getEntityReference(), - fingerprint, - () -> { - String id = entity.getId().toString(); - ChunkHeader header = getChunkHeader(chunkIndexName, id); - if (chunkRefresh(entity, fingerprint, header) != ChunkRefresh.NONE) { - replaceChunks(chunkIndexName, id, chunkDocs, previousCount(header)); - } - if (!chunkDocs.isEmpty()) { - partialUpdateEntity(entityIndexName, id, legacyEmbeddingFields(chunkDocs.getFirst())); - } - }); - } - - /** - * Write the given prebuilt chunk documents for an entity. Used by the reindex sink, which builds - * the chunk docs itself so chunk 0 can also be spliced into the staged entity doc without a - * second embedding pass. - */ - public void writeEntityChunks(String parentId, List> chunkDocs) { - writeEntityChunks(parentId, chunkDocs, null); - } - - /** - * Reindex-sink chunk write. {@code stagedChunkTarget} is the staged generation created by the - * run's own reCreateIndexes call and carried in its ReindexContext — the same propagation the - * staged ENTITY indexes rely on — so writes are scoped to the current run by construction: - * partial recreates and normal runs carry no target and write to the live index, and a crashed - * run's orphan can never capture anything. - */ - public void writeEntityChunks( - String parentId, List> chunkDocs, String stagedChunkTarget) { - try { - if (chunkDocs.isEmpty()) { - return; - } - final var type = (String) chunkDocs.getFirst().get("entityType"); - final var target = - stagedChunkTarget == null || OntologyTermSearch.isTerm(type) - ? chunkTargetForWrite(type) - : stagedChunkTarget; - ChunkHeader header = getChunkHeader(target, parentId); - replaceChunks(target, parentId, chunkDocs, previousCount(header)); - } catch (Exception e) { - // Tolerated like a failed document index — the chunk is absent, and the run's aggregate - // success (see markEntityTypeReindexed) gates whether the staged generation ever promotes. - LOG.error("Failed to write chunk docs for {}: {}", parentId, e.getMessage(), e); - } - } - - /** - * The legacy entity-doc embedding payload extracted from a chunk document: only the embedding - * fields, never the chunk doc's trimmed filter fields (tags/domains/tier), which would clobber - * the entity doc's rich versions of those fields on partial update. - */ - public static Map legacyEmbeddingFields(Map chunkDoc) { - Map fields = new HashMap<>(); - for (String key : EMBEDDING_SOURCE_FIELDS) { - Object value = chunkDoc.get(key); - if (value != null) { - fields.put(key, value); - } - } - return fields; - } - - @Override - public void deleteEntityChunks(String parentId) { - // Always delete from the live index: a staged run can be abandoned, and a delete applied only - // to the staged generation would then be lost — the deleted entity's chunks would keep - // surfacing until the next full recreate, the exact staleness this feature exists to prevent. - deleteChunksFrom(getChunkIndexName(), parentId); - // Also delete from an in-flight staged generation so a promoted run does not resurrect them. - String staged = resolveChunkSinkTarget(); - if (staged != null) { - deleteChunksFrom(staged, parentId); - } - } - - private void deleteChunksFrom(String indexName, String parentId) { - try { - ChunkHeader header = getChunkHeader(indexName, parentId); - replaceChunks(indexName, parentId, List.of(), previousCount(header)); - } catch (Exception e) { - LOG.debug("Failed to delete chunks for {} from {}: {}", parentId, indexName, e.getMessage()); - } - } - - /** - * Progressive disclosure for a single knowledge entity (the issue #4789 payoff): KNN over just - * this parent's chunks in the dedicated chunk index, returning the {@code textToLLMContext} of the - * top {@code k} chunks most relevant to {@code query}. Unlike {@link #search}, results are not - * collapsed by parent, so this yields several passages of one long article rather than a single - * representative — the mechanism that lets a get_asset_context bundle carry only excerpts. - */ - public List searchChunksByParent(String parentId, String query, int k) { - return searchChunksByParent(parentId, query, k, null); - } - - /** - * As above, resolving context memory visibility for {@code subjectContext}. Needed even though the - * parent is known: a parent may be a restricted memory, which yields no passages without it. - */ - public List searchChunksByParent( - String parentId, String query, int k, SubjectContext subjectContext) { - List passages = new ArrayList<>(); - try { - ensureChunkIndex(); - float[] vector = embeddingClient.embedQuery(query); - Map> filters = Map.of("parentId", List.of(parentId)); - String queryJson = - VectorSearchQueryBuilder.build(vector, k, 0, k, filters, 0.0, subjectContext); - String response = - executeGenericRequest("POST", "/" + getChunkIndexName() + "/_search", queryJson); - JsonNode hits = MAPPER.readTree(response).path("hits").path("hits"); - for (JsonNode hit : hits) { - String text = hit.path("_source").path("textToLLMContext").asText(null); - if (text != null && !text.isBlank()) { - passages.add(text); - } - } - } catch (Exception e) { - LOG.warn("Chunk retrieval failed for parent {}: {}", parentId, e.getMessage()); - } - return passages; - } - - // --- Staged chunk-index recreate: generation indexes promoted behind the read alias --- - // - // Full-recreate runs must sweep orphaned chunks (entities deleted without events — DB restore, - // wipe-and-remigrate), but dropping the live index up front turns any mid-run failure into a - // retrieval outage. Instead the run writes into a bare next-generation index - // ({chunk_base}_g), invisible to reads, and only when every vector-indexable entity type - // finalizes successfully is the generation promoted: one atomic _aliases call points the read - // and search aliases at it and removes the previous target. Any failure before promotion leaves - // the old chunks fully live; abandoned generations are swept at the next staged recreate. - - private final Object stagedChunkLock = new Object(); - private volatile String stagedChunkIndex; - private volatile Set stagedExpectedTypes = Set.of(); - private final Set stagedCompletedTypes = ConcurrentHashMap.newKeySet(); - private volatile boolean stagedChunkRunFailed; - // Run-scoped staged chunk index latched by a non-coordinator participant from its ReindexContext - // (see latchParticipantStagedTarget). Null on the coordinator, which uses stagedChunkIndex; null - // on a participant whose reindex thread has not yet latched (startup race). Volatile: set by the - // participant's reindex thread, read by request threads via resolveChunkSinkTarget. - private volatile String participantStagedTarget; - - /** - * Begins a staged recreate for a full-recreate run: pre-flights the embedding client (a broken - * client would make the whole run pointless), sweeps generations orphaned by crashed runs, and - * creates the next generation bare — no aliases, so reads keep hitting the old chunks. - * - *

Returns {@code null} when the embedding client cannot serve a request, meaning "not staged": - * the caller carries on with a normal in-place reindex and the existing chunks stay live, exactly - * as they do for a partial recreate. An unreachable embedding provider is a reason not to stage a - * generation we could never finish — it is not a reason to fail the entity reindex, which does - * not need embeddings at all. Note the provider is only exercised here: client construction makes - * no call to it, and live indexing logs and continues on embedding errors, so a deployment with - * semantic search enabled but no working provider looks healthy right up until a reindex. - * - *

Also returns {@code null} when the live-target probe is indeterminate. Skipping the stage - * deletes nothing — the sweep below never runs — so an unanswerable probe is a reason to leave - * the chunk index alone, not to fail an entity reindex that does not depend on it. Throwing here - * took down the whole run before its first record. The promote path stays strict: that swap does - * remove the previous target, so it must know what the target is. - * - *

Still throws on index create — a half-made generation is a state the next run must not - * inherit silently. - */ - public String beginStagedChunkRecreate() { - if (!isEmbeddingAvailable()) { - LOG.warn( - "Embedding pre-flight failed — skipping the staged chunk recreate. The entity reindex " - + "continues and existing chunks stay live; orphaned chunks, if any, are swept by the " - + "next recreate that runs with a working embedding provider."); - return null; - } - synchronized (stagedChunkLock) { - String base = getChunkIndexName(); - String liveTarget; - try { - liveTarget = requireResolvedLiveChunkTarget(base); - } catch (RuntimeException e) { - LOG.warn( - "Could not determine the live chunk target for {} — skipping the staged chunk " - + "recreate. The entity reindex continues and existing chunks stay live.", - base, - e); - return null; - } - deleteOrphanChunkGenerations(base, liveTarget); - String generation = nextChunkGenerationName(base); - try { - executeGenericRequest("PUT", "/" + generation, buildChunkIndexMapping(false)); - } catch (Exception e) { - throw new RuntimeException("Failed to create staged chunk index " + generation, e); - } - stagedChunkIndex = generation; - stagedExpectedTypes = AvailableEntityTypes.DATA_ASSET_CHUNK_TYPES; - stagedCompletedTypes.clear(); - stagedChunkRunFailed = false; - LOG.info( - "Staged chunk index {} created; chunks stay live at {} until promotion", - generation, - liveTarget); - return generation; - } - } - - /** - * Clears this JVM's staged-recreate state when the owning run dies before any type finalizes — - * without this, a later unrelated run's callbacks could complete and promote the dead - * generation. The bare generation index is left for the next staged recreate's sweep. - */ - public void clearStagedChunkState(String generation) { - synchronized (stagedChunkLock) { - if (generation.equals(stagedChunkIndex)) { - stagedChunkIndex = null; - stagedCompletedTypes.clear(); - LOG.warn( - "Cleared staged chunk state for {} — its run died before finalization; the " - + "generation will be swept by the next staged recreate", - generation); - } - } - } - - /** - * Whether the embedding client can actually serve a request. Logged rather than thrown: the only - * caller treats an unavailable provider as "do not stage", and the stack trace belongs in the log - * next to the provider's own error, not wrapped in a reindex failure. - */ - private boolean isEmbeddingAvailable() { - try { - embeddingClient.embedQuery("chunk index recreate pre-flight"); - return true; - } catch (Exception e) { - LOG.warn("Embedding client pre-flight failed: {}", e.getMessage(), e); - return false; - } - } - - /** - * Records one entity type's reindex outcome for an active staged chunk recreate, using the same - * aggregate success signal every other index promotes on. A type finalizing with {@code - * success=false} marks the run failed, so the staged generation is never promoted and the old - * chunks stay live (swept by the next recreate). Once every vector-indexable type finalizes - * successfully the staged generation is promoted atomically. This runs on the coordinator — the - * only JVM that finalizes entity types (participant-completed partitions are reconciled to the - * coordinator's completion callbacks). No-op when no staged recreate is active or for non-vector - * types. - */ - public void markEntityTypeReindexed(String entityType, boolean success, String runGeneration) { - String normalized = entityType == null ? null : entityType.toLowerCase(Locale.ROOT); - String generation = stagedChunkIndex; - if (generation != null && runGeneration != null && !generation.equals(runGeneration)) { - // Mark from a different run than the one that staged this generation — never count it. - LOG.warn( - "Ignoring chunk-type mark for {} bound to run generation {} while {} is staged", - entityType, - runGeneration, - generation); - return; - } - if (generation != null && runGeneration == null && normalized != null) { - // A run WITHOUT chunk staging is finalizing types while staged state lingers on this JVM — - // stale leftovers of a dead run. Never count these marks toward promotion. - LOG.warn( - "Ignoring unbound chunk-type mark for {} — staged generation {} belongs to a dead run " - + "and will be swept by the next staged recreate", - entityType, - generation); - return; - } - if (stagedChunkIndex != null - && normalized != null - && stagedExpectedTypes.contains(normalized)) { - if (success) { - stagedCompletedTypes.add(normalized); - if (!stagedChunkRunFailed && stagedCompletedTypes.containsAll(stagedExpectedTypes)) { - promoteStagedChunkIndex(); - } - } else { - stagedChunkRunFailed = true; - // Never delete mid-run: writers on other nodes may still be flushing into the generation, - // and a write against a deleted index auto-creates a junk index. The un-promoted - // generation is swept by the next staged recreate. - LOG.warn( - "Staged chunk recreate: entity type {} failed to reindex — promotion blocked, old " - + "chunks stay live; staged index {} will be swept by the next recreate", - entityType, - stagedChunkIndex); - } - } - } - - /** - * Points the read and search aliases at the staged generation and removes the previous target in - * one atomic {@code _aliases} call — no window where reads see neither or both generations. - */ - private void promoteStagedChunkIndex() { - synchronized (stagedChunkLock) { - String generation = stagedChunkIndex; - if (generation != null && stagedChunkRunFailed) { - // Re-check under the lock: a type may have finalized as failed between the caller's - // containsAll check and this swap. - LOG.warn( - "Staged chunk index {} — run marked failed, promotion blocked; old chunks stay live", - generation); - stagedChunkIndex = null; - generation = null; - } - if (generation != null) { - String base = getChunkIndexName(); - String oldTarget = requireResolvedLiveChunkTarget(base); - try { - executeGenericRequest( - "POST", - "/_aliases", - buildChunkPromoteActions(generation, base, getIndexAlias(), oldTarget)); - } catch (Exception e) { - throw new RuntimeException("Failed to promote staged chunk index " + generation, e); - } - stagedChunkIndex = null; - chunkIndexEnsured = true; - LOG.info("Promoted staged chunk index {} (previous target: {})", generation, oldTarget); - } - } - } - - private static final long SINK_TARGET_CACHE_MS = 15_000; - private volatile String cachedSinkTarget; - private volatile long cachedSinkTargetAt; - - /** - * Resolves the staged chunk target for the live-edit mirror ({@link #mirrorToStagedGeneration}) - * and delete ({@link #deleteEntityChunks}) paths. Resolution order: - * - *

    - *
  1. {@link #stagedChunkIndex} — the coordinator's own run-scoped generation, set by {@link - * #beginStagedChunkRecreate}. Coordinator-only; also gates promotion in {@link - * #markEntityTypeReindexed}, so it must never be set on a participant. - *
  2. {@link #participantStagedTarget} — a non-coordinator participant's run-scoped - * generation, latched from its {@code ReindexContext} by {@link - * #latchParticipantStagedTarget}. Authoritative for the run, so mirroring and deletes - * never depend on best-effort discovery — the gap that lost live edits when discovery - * cached a stale {@code null} on a participant JVM (see fd054753fa). - *
  3. Best-effort cluster-state probe ({@link #findActiveStagedGeneration}) with a short - * JVM-local cache that may hold {@code null} (no un-promoted {@code *_g*} index exists - * yet, or a transient probe failure). Reached only before a participant latches (startup - * race) or on a JVM with no run context; a {@code null} here is harmless for deletes but - * causes {@link #mirrorToStagedGeneration} to skip the mirror. - *
- * - *

Sink writes ({@code writeEntityChunks} / {@code backfillEntityChunks}) do not use this - * helper: they receive the run-scoped target explicitly via {@code ReindexContext}. - */ - private String resolveChunkSinkTarget() { - String target = stagedChunkIndex; // coordinator-only fast path (also gates promotion) - if (target == null) { - target = participantStagedTarget; // participant latch from ReindexContext - } - if (target == null) { - long now = System.currentTimeMillis(); - if (now - cachedSinkTargetAt > SINK_TARGET_CACHE_MS) { - cachedSinkTarget = findActiveStagedGeneration(); - cachedSinkTargetAt = now; - } - target = cachedSinkTarget; - } - return target; - } - - /** - * Latches the run-scoped staged chunk index a participant received via its {@code - * ReindexContext}, so live-edit mirroring ({@link #mirrorToStagedGeneration}) and deletes ({@link - * #deleteEntityChunks}) read the authoritative run-scoped target instead of falling through to - * the best-effort probe in {@link #findActiveStagedGeneration}. That probe can hold a stale - * {@code null} for up to {@value SINK_TARGET_CACHE_MS}ms on a non-coordinator JVM (cached before - * the coordinator created the generation, or after a transient cluster-state failure), in which - * case the mirror silently no-ops and the live edit is stranded in the soon-to-be-removed old - * generation. Called once per run by {@code DistributedJobParticipant} before it streams, and - * cleared by {@link #clearParticipantStagedTarget} when the run ends. - * - *

Must NOT set {@link #stagedChunkIndex}: that field gates promotion in {@link - * #markEntityTypeReindexed} (checking {@code stagedCompletedTypes} against {@code - * stagedExpectedTypes}) and is coordinator-only. {@code participantStagedTarget} is safe because - * the promotion path never reads it. - */ - public void latchParticipantStagedTarget(String staged) { - participantStagedTarget = staged; - } - - /** - * Clears the participant latch set by {@link #latchParticipantStagedTarget} when its run ends, so - * a later run cannot mirror or delete into a generation that belongs to a finished (promoted or - * abandoned) run. - */ - public void clearParticipantStagedTarget() { - participantStagedTarget = null; - } - - /** Newest generation index not yet holding the read alias, or null when none exists. */ - private String findActiveStagedGeneration() { - String base = getChunkIndexName(); - String result = null; - long best = 0; - try { - JsonNode response = MAPPER.readTree(executeGenericRequest("GET", "/" + base + "_g*", null)); - Iterator names = response.fieldNames(); - while (names.hasNext()) { - String name = names.next(); - boolean promoted = response.path(name).path("aliases").has(base); - long generation = chunkGenerationNumber(name, base); - if (!promoted && generation > best) { - best = generation; - result = name; - } - } - } catch (Exception e) { - LOG.debug("Staged chunk generation lookup failed: {}", e.getMessage()); - } - return result; - } - - /** - * {@code _aliases} actions promoting a generation: attach the read alias and the search alias, - * and atomically remove the previous target (the legacy physical index on first promotion, an - * older generation afterwards). Null {@code oldTarget} (fresh install) emits no removal. - */ - static String buildChunkPromoteActions( - String generation, String readAlias, String searchAlias, String oldTarget) { - var actions = MAPPER.createArrayNode(); - actions.add( - MAPPER - .createObjectNode() - .set( - "add", MAPPER.createObjectNode().put("index", generation).put("alias", readAlias))); - actions.add( - MAPPER - .createObjectNode() - .set( - "add", - MAPPER.createObjectNode().put("index", generation).put("alias", searchAlias))); - if (oldTarget != null && !oldTarget.equals(generation)) { - actions.add( - MAPPER - .createObjectNode() - .set("remove_index", MAPPER.createObjectNode().put("index", oldTarget))); - } - ObjectNode body = MAPPER.createObjectNode(); - body.set("actions", actions); - return body.toString(); - } - - /** - * The physical index currently serving chunk reads: the alias target when the read name is an - * alias (post-promotion layout), the legacy physical index when it exists under the read name, - * or null on a fresh install. Throws when the cluster cannot answer, so callers can distinguish - * "nothing is live" from "could not tell". - * - *

Index-scoped by construction: {@code GET /{base}/_alias} names the index in the path, so a - * deployment whose search role only grants its own {@code *} prefix — every - * shared-tenancy cloud cluster — is authorized for it. The alias-scoped forms - * ({@code HEAD|GET /_alias/{base}}) name no index, so the cluster resolves them against _all and - * denies them with a 403 that opensearch-java raises before any boolean-endpoint status mapping, - * i.e. one that can never degrade to "no alias". - * - *

One call covers both layouts because the response is keyed by physical index: the staged - * generation when {@code base} is the read alias, {@code base} itself when it is still the - * legacy physical index. A 404 means neither exists yet. - */ - private String resolveLiveChunkTargetStrict(String base) throws IOException { - try { - Iterator names = - client.indices().getAlias(a -> a.index(base)).result().keySet().iterator(); - return names.hasNext() ? names.next() : null; - } catch (OpenSearchException e) { - if (e.status() == 404) { - LOG.debug("No chunk index or alias named {} — fresh install", base); - return null; - } - throw e; - } - } - - /** - * Lenient resolution for the ensure/create path: a wrongly-null target there can only make an - * index create attempt fail and be retried — it can never delete anything. - */ - private String resolveLiveChunkTarget(String base) { - String target = null; - try { - target = resolveLiveChunkTargetStrict(base); - } catch (Exception e) { - LOG.warn("Could not resolve live chunk target for {}: {}", base, e.getMessage()); - } - return target; - } - - /** - * Strict resolution for destructive paths (orphan sweep, alias swap): an indeterminate probe - * aborts the operation, because a null target would read as "nothing is live" and let the sweep - * delete the live generation. - */ - private String requireResolvedLiveChunkTarget(String base) { - try { - return resolveLiveChunkTargetStrict(base); - } catch (Exception e) { - throw new RuntimeException("Cannot determine the live chunk target for " + base, e); - } - } - - /** - * Sweeps generation indexes that are not the live target — leftovers of crashed or never-promoted - * staged runs. Runs before creating the next generation, so an orphan can never swallow writes. - */ - private void deleteOrphanChunkGenerations(String base, String liveTarget) { - try { - String response = executeGenericRequest("GET", "/" + base + "_g*", null); - Iterator names = MAPPER.readTree(response).fieldNames(); - while (names.hasNext()) { - String name = names.next(); - if (!name.equals(liveTarget)) { - deleteOrphanGeneration(name); - } - } - } catch (Exception e) { - LOG.warn("Orphaned chunk generation sweep failed: {}", e.getMessage()); - } - } - - private void deleteOrphanGeneration(String name) { - try { - executeGenericRequest("DELETE", "/" + name, null); - LOG.info("Deleted orphaned staged chunk index {}", name); - } catch (Exception e) { - LOG.warn("Failed to delete orphaned staged chunk index {}: {}", name, e.getMessage()); - } - } - - /** Generation stamp of a chunk index name, or 0 for the legacy physical / non-generation name. */ - static long chunkGenerationNumber(String indexName, String chunkBase) { - long number = 0; - String prefix = chunkBase + "_g"; - if (indexName != null && indexName.startsWith(prefix)) { - try { - number = Long.parseLong(indexName.substring(prefix.length())); - } catch (NumberFormatException e) { - number = 0; - } - } - return number; - } - - /** - * Run-unique generation name (epoch-millis stamp) so a pending promote from a superseded run - * fails loudly on a missing index rather than silently aliasing another run's half-built one. - */ - static String nextChunkGenerationName(String chunkBase) { - return chunkBase + "_g" + System.currentTimeMillis(); - } - - private String chunkTargetForWrite(String entityType) { - if (!OntologyTermSearch.isTerm(entityType)) { - requireChunkIndexForWrite(); - return getChunkIndexName(); - } - final var index = getOntologyChunkIndexName(); - if (!ontologyChunkIndexEnsured) { - synchronized (this) { - if (!ontologyChunkIndexEnsured) { - final var target = resolveLiveChunkTarget(index); - if (target == null) { - executeGenericRequest("PUT", "/" + index, buildChunkIndexMapping(false)); - ontologyChunkIndexEnsured = true; - } else { - ontologyChunkIndexEnsured = applyChunkMappingUpgradeIfStale(target); - } - } - } - } - if (!ontologyChunkIndexEnsured) { - throw new IllegalStateException("Ontology vector chunk index unavailable"); - } - return index; - } - - /** - * Write-path gate: throws when the chunk index could not be ensured. A raw write against a - * missing index would auto-create it with dynamic mappings ({@code embedding} as float, not - * knn_vector), permanently wedging vector search until manual index surgery — worse than the - * skipped write. Read paths stay lenient: reads cannot auto-create an index. - */ - private void requireChunkIndexForWrite() { - ensureChunkIndex(); - if (!chunkIndexEnsured) { - throw new IllegalStateException( - "Vector chunk index unavailable (create/upgrade failed); refusing chunk write that " - + "would auto-create it with a non-knn mapping"); - } - } - - private void ensureChunkIndex() { - if (!chunkIndexEnsured) { - synchronized (this) { - if (!chunkIndexEnsured) { - // Only latch on success so a transient failure (e.g. OpenSearch outage during startup) - // is retried on the next write instead of disabling chunk indexing until restart. - chunkIndexEnsured = createChunkIndexIfAbsent(); - } - } - } - } - - private boolean createChunkIndexIfAbsent() { - String base = getChunkIndexName(); - boolean ensured = false; - try { - // Post-promotion the read name is an alias over the live generation; operate on the - // resolved physical target. On a fresh install, create the legacy physical layout — - // generations appear at the first staged recreate. - String target = resolveLiveChunkTarget(base); - if (target == null) { - executeGenericRequest("PUT", "/" + base, buildChunkIndexMapping(true)); - LOG.info("Created dedicated vector chunk index {}", base); - ensured = true; - } else { - // The search alias is normally attached at creation, but an index left over from a partial - // or manual setup may miss it — and reads via the alias would then silently skip all chunk - // docs. The alias PUT is idempotent. Only report "ensured" once the mapping is at the - // current version so a failed upgrade does not latch (and so docs are not stamped with the - // new docVersion into a still-stale mapping). - executeGenericRequest("PUT", "/" + target + "/_alias/" + getIndexAlias(), "{}"); - ensured = applyChunkMappingUpgradeIfStale(target); - } - } catch (Exception e) { - LOG.error("Failed to ensure chunk index {}: {}", base, e.getMessage()); - } - return ensured; - } - - /** - * When the chunk index already exists, compare its {@code _meta.chunkDocVersion} against the code - * {@link VectorDocBuilder#CHUNK_DOC_VERSION}; if the index is older, apply the additive - * {@code PUT _mapping} so the new denormalized fields become mappable. This is legal on a - * {@code dynamic:false} index and safe pre-backfill: old docs simply lack the new fields until a - * Search Reindex re-materializes them (the reindex reuses embeddings, so there is no re-embed - * cost — see {@link #updateEntityEmbeddingChunks(EntityInterface, String)}). - * - * @return {@code true} when the index is (already or now) at the current version; {@code false} - * when the upgrade could not be applied, so the caller leaves the index un-ensured and the - * PUT is retried on the next write rather than silently proceeding with a stale mapping. - */ - private boolean applyChunkMappingUpgradeIfStale(String indexName) { - try { - String mappingJson = executeGenericRequest("GET", "/" + indexName + "/_mapping", null); - JsonNode mappings = MAPPER.readTree(mappingJson).path(indexName).path("mappings"); - int existingVersion = mappings.path("_meta").path("chunkDocVersion").asInt(0); - if (existingVersion >= VectorDocBuilder.CHUNK_DOC_VERSION) { - return true; - } - executeGenericRequest("PUT", "/" + indexName + "/_mapping", buildChunkMappingUpgradeBody()); - LOG.info( - "Upgraded chunk index {} mapping chunkDocVersion {} -> {} (denormalized fields backfill " - + "on next Search Reindex)", - indexName, - existingVersion, - VectorDocBuilder.CHUNK_DOC_VERSION); - return true; - } catch (Exception e) { - LOG.error( - "Failed to upgrade chunk index {} mapping; leaving it un-ensured to retry on the next " - + "write rather than stamping docs with the new docVersion into a stale mapping: {}", - indexName, - e.getMessage()); - return false; - } - } - - private String buildChunkIndexMapping(boolean withSearchAlias) { - var mappings = MAPPER.createObjectNode().put("dynamic", false); - mappings.set("properties", buildChunkProperties()); - mappings.set("_meta", chunkMeta()); - var root = loadVectorIndexMapping(); - root.set("mappings", mappings); - // Staged generations are created bare: attaching the search alias before promotion would make - // the half-built generation searchable alongside the live one. - if (withSearchAlias) { - root.set( - "aliases", MAPPER.createObjectNode().set(getIndexAlias(), MAPPER.createObjectNode())); - } - return root.toString(); - } - - /** - * Additive {@code PUT _mapping} body applied by {@link #applyChunkMappingUpgradeIfStale}. Sends the - * property set minus the {@code embedding} knn_vector plus the bumped - * {@code _meta.chunkDocVersion}. Re-declaring the existing {@code knn_vector} is rejected by some - * OpenSearch versions/plugins even with identical parameters; because {@code PUT _mapping} is - * atomic, that would fail the whole request and silently leave the genuinely new denormalized - * fields unmapped (on a {@code dynamic:false} index) while docs are still stamped with the new - * {@code docVersion} — defeating the rollout. Omitting the unchanged vector avoids that - * all-or-nothing failure; the remaining fields are additive (new fields) or legal no-ops - * (unchanged keyword/text/integer). - * - *

Absent-on-old-docs fields are inert for anything that merely scores or widens on them, so - * those upgrades carry no regression before the backfill runs. That is not true of a field a - * filter restricts on: {@code visibility}, {@code entityStatus} and {@code anchorId} are required - * by the context memory clause in {@link VectorSearchQueryBuilder}, where absence means exclusion - * rather than indifference. Memory chunks written before they were stamped therefore stay out of - * every KNN result, for admins too, until a Search Reindex restamps them — deliberately, since an - * unstamped document may be a Private, retired or anchored memory. {@code memoryScope}, - * {@code memoryType} and {@code pinned} (v8) restrict only a query that asks for them, so before - * the backfill such a query loses those memories' vector hits and never gains a wrong one. Weigh - * that before making any future field a filter depends on. - */ - private String buildChunkMappingUpgradeBody() { - ObjectNode properties = buildChunkProperties(); - properties.remove("embedding"); - var body = MAPPER.createObjectNode(); - body.set("properties", properties); - body.set("_meta", chunkMeta()); - return body.toString(); - } - - private ObjectNode chunkMeta() { - return MAPPER.createObjectNode().put("chunkDocVersion", VectorDocBuilder.CHUNK_DOC_VERSION); - } - - private ObjectNode buildChunkProperties() { + protected ObjectNode embeddingFieldMapping(int dimension) { var method = MAPPER .createObjectNode() @@ -1159,964 +214,27 @@ private ObjectNode buildChunkProperties() { .put("engine", "lucene") .put("space_type", "cosinesimil") .set("parameters", MAPPER.createObjectNode().put("m", 48).put("ef_construction", 256)); - var embedding = - MAPPER - .createObjectNode() - .put("type", "knn_vector") - .put("dimension", embeddingClient.getDimension()) - .set("method", method); - var properties = MAPPER.createObjectNode(); - properties.set("embedding", embedding); - // The three metric enums are mapped as real keywords, not source-only: they are cheap to index - // and are the natural facets to filter a metric search on (granularity DAY vs MONTH). - // Memory privacy and lifecycle fields must be filterable on every chunk. - for (String keyword : - List.of( - "parentId", - "fingerprint", - "entityType", - "fullyQualifiedName", - "serviceType", - "metricType", - "granularity", - "unitOfMeasurement", - "customUnitOfMeasurement", - "visibility", - "sharedWithIds", - ContextMemoryIndex.FIELD_ANCHOR_ID, - ContextMemoryIndex.FIELD_STATUS, - ContextMemoryIndex.FIELD_MEMORY_SCOPE, - ContextMemoryIndex.FIELD_MEMORY_TYPE)) { - properties.set(keyword, MAPPER.createObjectNode().put("type", "keyword")); - } - // name/displayName keep a keyword root but gain a `.keyword` subfield so the shard-fair exact - // (case_insensitive term) clauses, which target `.keyword`, resolve on chunk docs. - for (String keywordWithSub : List.of("name", "displayName")) { - properties.set(keywordWithSub, keywordWithKeywordSubfield()); - } - for (String integer : List.of("chunkIndex", "chunkCount", "docVersion")) { - properties.set(integer, MAPPER.createObjectNode().put("type", "integer")); - } - // Analyzed lexical parity fields. The dedicated chunk index defines no custom analyzers, so - // these use the default standard analyzer; full om_analyzer/compound parity is a Phase 4 - // index recreate. - for (String text : - List.of("textToEmbed", "textToLLMContext", "description", "fqnParts", "synonyms")) { - properties.set(text, MAPPER.createObjectNode().put("type", "text")); - } - properties.set("deleted", MAPPER.createObjectNode().put("type", "boolean")); - properties.set( - ContextMemoryIndex.FIELD_PINNED, MAPPER.createObjectNode().put("type", "boolean")); - properties.set("tags", objectKeyword("tagFQN")); - properties.set("domains", objectKeyword("name")); - properties.set("tier", objectKeyword("tagFQN")); - properties.set("certification", certificationMapping()); - // owners is a `nested` type: NLQ owner filters run a nested query over owners.name, and the - // context memory visibility filter runs one over owners.id. - properties.set("owners", nestedOwnersMapping()); - properties.set("service", nameDisplayNameObject()); - properties.set("database", nameDisplayNameObject()); - // Map name+displayName like service/database: buildDenormalizedFields copies both onto the - // chunk doc, so mapping only `name` would leave the denormalized displayName in _source but - // unindexed (dynamic:false), silently unfilterable and inconsistent with the entity index. - properties.set("databaseSchema", nameDisplayNameObject()); - properties.set("columns", columnsMapping()); - properties.set( - "relatedTerms", MAPPER.createObjectNode().put("type", "object").put("enabled", false)); - // Display-only: semantic_search returns a metric's expression, nothing filters or scores on it, - // and the code is already searchable through textToEmbed. `enabled: false` keeps it in _source - // without paying to index it on a dynamic:false index. - properties.set( - "metricExpression", MAPPER.createObjectNode().put("type", "object").put("enabled", false)); - return properties; - } - - private ObjectNode keywordWithKeywordSubfield() { - return (ObjectNode) - MAPPER - .createObjectNode() - .put("type", "keyword") - .set( - "fields", - MAPPER - .createObjectNode() - .set("keyword", MAPPER.createObjectNode().put("type", "keyword"))); - } - - private ObjectNode objectKeyword(String field) { - return (ObjectNode) - MAPPER - .createObjectNode() - .set( - "properties", - MAPPER - .createObjectNode() - .set(field, MAPPER.createObjectNode().put("type", "keyword"))); - } - - private ObjectNode nestedOwnersMapping() { - var properties = MAPPER.createObjectNode(); - properties.set("name", MAPPER.createObjectNode().put("type", "keyword")); - properties.set("id", MAPPER.createObjectNode().put("type", "keyword")); - return (ObjectNode) - MAPPER.createObjectNode().put("type", "nested").set("properties", properties); - } - - private ObjectNode nameDisplayNameObject() { - var props = MAPPER.createObjectNode(); - props.set("name", MAPPER.createObjectNode().put("type", "keyword")); - props.set("displayName", MAPPER.createObjectNode().put("type", "keyword")); - return (ObjectNode) MAPPER.createObjectNode().set("properties", props); - } - - private ObjectNode certificationMapping() { - var tagLabel = objectKeyword("tagFQN"); - return (ObjectNode) - MAPPER - .createObjectNode() - .put("type", "object") - .set("properties", MAPPER.createObjectNode().set("tagLabel", tagLabel)); - } - - private ObjectNode columnsMapping() { - var name = keywordWithKeywordSubfield(); - return (ObjectNode) - MAPPER.createObjectNode().set("properties", MAPPER.createObjectNode().set("name", name)); - } - - /** - * Multi-chunk write path (issue #4789): index one standalone document per body chunk into the - * dedicated chunk index, keyed {@code _}. Skips work when the whole-body - * fingerprint is unchanged. Chunk ids are deterministic, so a shrinking body is handled by - * bulk-deleting the trailing stale ids in the same request — no delete-by-query and no forced - * refresh on this hot path; visibility follows the index refresh interval. - */ - private static String fingerprint(EntityInterface entity, String ontologyBody) { - return ontologyBody == null - ? VectorDocBuilder.computeFingerprintForEntity(entity) - : VectorDocBuilder.computeFingerprintForEntity(entity, ontologyBody); - } - - public void updateEntityEmbeddingChunks(EntityInterface entity, String chunkIndexName) { - updateEntityEmbeddingChunks(entity, chunkIndexName, null); - } - - private void updateEntityEmbeddingChunks( - EntityInterface entity, String chunkIndexName, String ontologyBody) { - try { - String parentId = entity.getId().toString(); - ChunkHeader header = getChunkHeader(chunkIndexName, parentId); - String currentFingerprint = fingerprint(entity, ontologyBody); - ChunkRefresh refresh = chunkRefresh(entity, currentFingerprint, header); - if (refresh == ChunkRefresh.NONE) { - LOG.debug("Skipping chunk embedding for {} - content and filters current", parentId); - } else { - List> chunkDocs = - refresh == ChunkRefresh.RESTAMP - ? rebuildChunksReusingEmbeddings( - entity, chunkIndexName, parentId, header, ontologyBody) - : VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody); - replaceChunks(chunkIndexName, parentId, chunkDocs, previousCount(header)); - } - } catch (EmbeddingUnavailableException unavailable) { - LOG.debug("Skipping chunk embeddings for {}: {}", entity.getId(), unavailable.getMessage()); - } catch (Exception e) { - LOG.error("Failed to update chunk embeddings for {}: {}", entity.getId(), e.getMessage(), e); - } - } - - /** - * Rebuild an entity's chunk docs for a docVersion migration by reusing the embeddings already - * stored on those chunk docs (fingerprint unchanged ⇒ same body ⇒ same chunking ⇒ 1:1 reusable - * vectors), so only the denormalized fields and {@code docVersion} change and no embedding call is - * made. Falls back to a full re-embed if the cached vectors can't all be recovered (partial/corrupt - * chunk set) or the re-chunk disagrees with the cached count. - */ - private List> rebuildChunksReusingEmbeddings( - EntityInterface entity, String chunkIndexName, String parentId, ChunkHeader header) { - return rebuildChunksReusingEmbeddings(entity, chunkIndexName, parentId, header, null); - } - - private List> rebuildChunksReusingEmbeddings( - EntityInterface entity, - String chunkIndexName, - String parentId, - ChunkHeader header, - String ontologyBody) { - Map vectors = - fetchExistingChunkVectors(chunkIndexName, parentId, header.chunkCount()); - if (vectors.size() != header.chunkCount()) { - LOG.info( - "Chunk docVersion rebuild for {} recovered {}/{} cached vectors; re-embedding", - parentId, - vectors.size(), - header.chunkCount()); - return VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody); - } - try { - return VectorDocBuilder.fromEntityReusingEmbeddings(entity, vectors, ontologyBody); - } catch (RuntimeException e) { - LOG.info( - "Chunk docVersion rebuild for {} fell back to re-embedding: {}", - parentId, - e.getMessage()); - return VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody); - } - } - - /** - * Batch-fetch the stored embedding vectors for an entity's chunk docs ({@code _0..N-1}), - * keyed by {@code chunkIndex}. Pulls only {@code embedding}+{@code chunkIndex} so the large vector - * payload is the only thing on the wire. - */ - private Map fetchExistingChunkVectors( - String chunkIndexName, String parentId, int chunkCount) { - Map vectors = new HashMap<>(); - if (chunkCount <= 0) { - return vectors; - } - try { - List ids = new ArrayList<>(chunkCount); - for (int i = 0; i < chunkCount; i++) { - ids.add(parentId + "_" + i); - } - MgetResponse response = - client.mget( - m -> - m.index(chunkIndexName) - .ids(ids) - .sourceIncludes(List.of("embedding", "chunkIndex")), - JsonData.class); - for (MultiGetResponseItem item : response.docs()) { - if (!item.isResult()) { - continue; - } - GetResult doc = item.result(); - if (!doc.found() || doc.source() == null) { - continue; - } - JsonNode source = doc.source().to(JsonNode.class, JACKSON_JSONP_MAPPER); - float[] vector = toFloatArray(source.path("embedding")); - if (vector != null) { - vectors.put(source.path("chunkIndex").asInt(0), vector); - } - } - } catch (Exception e) { - LOG.warn( - "Failed to fetch existing chunk vectors for {}; will re-embed: {}", - parentId, - e.getMessage(), - e); - } - return vectors; - } - - private static float[] toFloatArray(JsonNode node) { - if (node == null || !node.isArray() || node.isEmpty()) { - return null; - } - float[] out = new float[node.size()]; - for (int i = 0; i < node.size(); i++) { - out[i] = (float) node.get(i).asDouble(); - } - return out; - } - - /** Header of an entity's chunk set, read from chunk 0. */ - record ChunkHeader( - String fingerprint, - int chunkCount, - int docVersion, - String status, - String anchorId, - MemoryKind memoryKind) {} - - /** The memory kind a chunk was stamped with; filters read it, the fingerprint does not see it. */ - record MemoryKind(String scope, String type, boolean pinned) { - static MemoryKind of(ContextMemory memory) { - return new MemoryKind( - ContextMemoryIndex.memoryScopeValue(memory), - ContextMemoryIndex.memoryTypeValue(memory), - Boolean.TRUE.equals(memory.getPinned())); - } - - static MemoryKind read(JsonNode source) { - return new MemoryKind( - source.path(ContextMemoryIndex.FIELD_MEMORY_SCOPE).asText(null), - source.path(ContextMemoryIndex.FIELD_MEMORY_TYPE).asText(null), - source.path(ContextMemoryIndex.FIELD_PINNED).asBoolean(false)); - } - } - - /** How an entity's stored chunks must be brought up to date. */ - enum ChunkRefresh { - NONE, - /** Same embedded text: rewrite the metadata around the stored vectors, at no embedding cost. */ - RESTAMP, - REEMBED - } - - static ChunkRefresh chunkRefresh( - EntityInterface entity, String fingerprint, ChunkHeader header) { - ChunkRefresh refresh = ChunkRefresh.NONE; - if (header == null || !fingerprint.equals(header.fingerprint())) { - refresh = ChunkRefresh.REEMBED; - } else if (docVersionStale(header) || memoryFilterChanged(entity, header)) { - refresh = ChunkRefresh.RESTAMP; - } - return refresh; - } - - // Status and anchor gate memory visibility, and the kind narrows a filtered recall; none of them - // is embedded text, so the fingerprint cannot see them change. - private static boolean memoryFilterChanged(EntityInterface entity, ChunkHeader header) { - return entity instanceof ContextMemory memory - && (!Objects.equals(ContextMemoryIndex.statusValue(memory), header.status()) - || !ContextMemoryIndex.anchorId(memory).equals(header.anchorId()) - || !MemoryKind.of(memory).equals(header.memoryKind())); - } - - /** - * A recreate in flight would otherwise promote the chunks it copied before this update, the same - * staleness {@link #deleteEntityChunks} guards against for deletes. - */ - private void mirrorToStagedGeneration(String parentId, List> chunkDocs) { - String staged = resolveChunkSinkTarget(); - if (staged == null) { - LOG.debug("No staged chunk generation to mirror the live update for {}", parentId); - return; - } - try { - replaceChunks(staged, parentId, chunkDocs, previousCount(getChunkHeader(staged, parentId))); - } catch (IOException | RuntimeException e) { - LOG.warn( - "Failed to mirror chunks for {} into staged {}: {}", parentId, staged, e.getMessage()); - } - } - - private static boolean docVersionStale(ChunkHeader header) { - return header != null && header.docVersion() < VectorDocBuilder.CHUNK_DOC_VERSION; - } - - private static int previousCount(ChunkHeader header) { - return header == null ? 0 : header.chunkCount(); - } - - /** - * Real-time by-id GET of chunk 0's content and filter metadata. It sees unrefreshed writes and - * avoids a search request on each entity update. - */ - private ChunkHeader getChunkHeader(String indexName, String parentId) { - ChunkHeader header = null; - try { - OpenSearchGenericClient genericClient = client.generic(); - var request = - Requests.builder() - .endpoint( - "/" - + indexName - + "/_doc/" - + parentId - + "_0?_source_includes=fingerprint,chunkCount,docVersion," - + String.join( - ",", - ContextMemoryIndex.FIELD_STATUS, - ContextMemoryIndex.FIELD_ANCHOR_ID, - ContextMemoryIndex.FIELD_MEMORY_SCOPE, - ContextMemoryIndex.FIELD_MEMORY_TYPE, - ContextMemoryIndex.FIELD_PINNED)) - .method("GET") - .build(); - try (var response = genericClient.execute(request)) { - if (response.getStatus() < 400) { - String body = - response - .getBody() - .map( - b -> { - try { - return new String(b.bodyAsBytes(), StandardCharsets.UTF_8); - } catch (Exception ignored) { - return "{}"; - } - }) - .orElse("{}"); - JsonNode root = MAPPER.readTree(body); - if (root.path("found").asBoolean(false)) { - JsonNode source = root.path("_source"); - header = - new ChunkHeader( - source.path("fingerprint").asText(null), - source.path("chunkCount").asInt(0), - source.path("docVersion").asInt(0), - source.path(ContextMemoryIndex.FIELD_STATUS).asText(null), - source.path(ContextMemoryIndex.FIELD_ANCHOR_ID).asText(null), - MemoryKind.read(source)); - } - } - } - } catch (Exception e) { - LOG.debug("No chunk header for {} in {}: {}", parentId, indexName, e.getMessage()); - } - return header; - } - - /** - * One bulk request that overwrites chunk ids {@code 0..N-1} and deletes the trailing stale ids - * {@code N..previousCount-1} left behind by a shrinking body. Deletes are by id, so they do not - * depend on search visibility of prior writes. - */ - private void replaceChunks( - String indexName, String parentId, List> chunkDocs, int previousCount) - throws IOException { - if (previousCount == 0) { - cleanOrphanChunks(indexName, parentId); - } - if (chunkDocs.isEmpty() && previousCount == 0) { - return; - } - StringBuilder bulk = new StringBuilder(); - for (int i = 0; i < chunkDocs.size(); i++) { - bulk.append("{\"index\":{\"_index\":\"") - .append(indexName) - .append("\",\"_id\":\"") - .append(parentId) - .append('_') - .append(i) - .append("\"}}\n") - .append(MAPPER.writeValueAsString(chunkDocs.get(i))) - .append('\n'); - } - appendChunkDeletes(bulk, indexName, parentId, chunkDocs.size(), previousCount); - String response = executeGenericRequest("POST", "/_bulk", bulk.toString()); - failOnBulkItemErrors(indexName, parentId, response); - } - - /** - * The bulk API reports per-item failures (rejected executions under load, mapping conflicts) as - * HTTP 200 with {@code errors:true} — exactly the failure class a heavy reindex produces. - * Silently accepting them would leave holes with no log trail; throwing surfaces the failure to - * the callers' catch-and-log so a partially-written entity is at least visible in the logs. - */ - private void failOnBulkItemErrors(String indexName, String parentId, String response) { - try { - JsonNode root = MAPPER.readTree(response); - if (!root.path("errors").asBoolean(false)) { - return; - } - StringBuilder reasons = new StringBuilder(); - int reported = 0; - for (JsonNode item : root.path("items")) { - // replaceChunks emits index AND delete actions (trailing-chunk cleanup); create for - // completeness — each item is keyed by whichever action it was. - for (String action : BULK_ACTIONS) { - JsonNode error = item.path(action).path("error"); - if (!error.isMissingNode() && reported < 3) { - reasons.append(action).append(' '); - reasons.append(error.path("type").asText("?")).append(": "); - reasons.append(error.path("reason").asText("?")).append("; "); - reported++; - } - } - } - throw new IllegalStateException( - "Bulk chunk write for " - + parentId - + " into " - + indexName - + " had item failures: " - + reasons); - } catch (IllegalStateException e) { - throw e; - } catch (Exception parseFailure) { - // Conservative: an unparseable 200 could be hiding item failures, and in a staged - // generation silently accepting it becomes a chunk drop at promotion. - throw new IllegalStateException( - "Bulk chunk write for " - + parentId - + " into " - + indexName - + " returned an unparseable response", - parseFailure); - } - } - - private static final List BULK_ACTIONS = List.of("index", "delete", "create"); - - /** - * Belt-and-braces for a missing or corrupt chunk-0 header (e.g. a partial bulk failure). - * {@code previousCount == 0} is overwhelmingly the brand-new-entity case on the write and - * reindex-backfill hot paths, so the guard is the cheapest primitive available — a real-time - * by-id existence probe of chunk 1 that never touches the search layer. Only when a trailing - * chunk survived without its header do we pay a delete-by-query heal. (A failure that drops - * both chunk 0 and chunk 1 while later chunks survive would evade the probe; the next - * successful full write overwrites those ids anyway.) - */ - private void cleanOrphanChunks(String indexName, String parentId) { - try { - if (chunkDocExists(indexName, parentId + "_1")) { - LOG.warn("Healing orphan chunk docs for parent {} with missing chunk-0 header", parentId); - String body = - "{\"query\":{\"term\":{\"parentId\":\"" - + VectorSearchQueryBuilder.escape(parentId) - + "\"}}}"; - executeGenericRequest( - "POST", "/" + indexName + "/_delete_by_query?conflicts=proceed", body); - } - } catch (Exception e) { - LOG.debug("Orphan chunk cleanup skipped for {}: {}", parentId, e.getMessage()); - } - } - - private boolean chunkDocExists(String indexName, String docId) { - boolean exists = false; - try { - OpenSearchGenericClient genericClient = client.generic(); - var request = - Requests.builder() - .endpoint("/" + indexName + "/_doc/" + docId + "?_source=false") - .method("HEAD") - .build(); - try (var response = genericClient.execute(request)) { - exists = response.getStatus() < 300; - } - } catch (Exception e) { - LOG.debug("Chunk existence probe failed for {}: {}", docId, e.getMessage()); - } - return exists; - } - - private static void appendChunkDeletes( - StringBuilder bulk, String indexName, String parentId, int fromIndex, int toExclusive) { - for (int i = fromIndex; i < toExclusive; i++) { - bulk.append("{\"delete\":{\"_index\":\"") - .append(indexName) - .append("\",\"_id\":\"") - .append(parentId) - .append('_') - .append(i) - .append("\"}}\n"); - } - } - - @Override - @SuppressWarnings("unchecked") - public VectorSearchResponse search( - String query, - Map> filters, - int size, - int from, - int k, - double threshold, - String preference, - SubjectContext subjectContext) { - return search( - new VectorSearchParameters( - query, filters, size, from, k, threshold, preference, subjectContext, null)); - } - - @Override - @SuppressWarnings("unchecked") - public VectorSearchResponse search(VectorSearchParameters parameters) { - String query = parameters.query(); - int size = parameters.size(); - int from = parameters.from(); - int k = parameters.k(); - double threshold = parameters.threshold(); - long start = System.currentTimeMillis(); - try { - float[] queryVector = embeddingClient.embedQuery(query); - LinkedHashMap>> byParent = new LinkedHashMap<>(); - int rawOffset = 0; - long totalHits = -1L; - boolean exhausted = false; - int requestedParents = from + size + 1; // Fetch one extra parent so hasMore is accurate. - int overFetchSize = Math.max(requestedParents * OVER_FETCH_MULTIPLIER, OVER_FETCH_MULTIPLIER); - if (threshold <= 0.0) { - overFetchSize = Math.min(overFetchSize, k); - } - - String aliasName = vectorSearchTarget(parameters.filters()); - Set readableAnchorIds = readableAnchors.apply(parameters); - while (!exhausted && byParent.size() < requestedParents) { - String queryJson = - VectorSearchQueryBuilder.build( - queryVector, - parameters.withPagination(overFetchSize, rawOffset), - readableAnchorIds); - String endpoint = - SearchUtils.appendPreferenceParam( - "/" + aliasName + "/_search", parameters.preference()); - if (aliasName.contains(getOntologyChunkIndexName())) { - endpoint += (endpoint.contains("?") ? "&" : "?") + "ignore_unavailable=true"; - } - String responseBody = executeGenericRequest("POST", endpoint, queryJson); - - JsonNode root = MAPPER.readTree(responseBody); - JsonNode hitsNode = root.path("hits").path("hits"); - totalHits = extractTotalHits(root); - - int pageHitCount = collectSearchHits(hitsNode, threshold, byParent); - if (pageHitCount == 0) { - exhausted = true; - break; - } - - rawOffset += pageHitCount; - exhausted = totalHits >= 0 ? rawOffset >= totalHits : pageHitCount < overFetchSize; - } - - List> results = new ArrayList<>(); - int parentCount = 0; - int skipped = 0; - for (List> chunks : byParent.values()) { - if (skipped < from) { - skipped++; - continue; - } - if (parentCount >= size) { - break; - } - results.addAll(chunks); - parentCount++; - } - - boolean hasMore = byParent.size() > (from + parentCount); - long tookMillis = System.currentTimeMillis() - start; - return new VectorSearchResponse( - tookMillis, results, totalHits >= 0 ? totalHits : null, hasMore); - } catch (Exception e) { - LOG.error("Vector search failed: {}", e.getMessage(), e); - throw new RuntimeException("Vector search failed", e); - } - } - - String vectorSearchTarget(Map> filters) { - final var types = - filters == null ? List.of() : filters.getOrDefault("entityType", List.of()); - if (types.stream().noneMatch(OntologyTermSearch::isTerm)) { - return getIndexAlias(); - } - final var ontologyChunks = getOntologyChunkIndexName(); - return types.stream().allMatch(OntologyTermSearch::isTerm) - ? ontologyChunks - : getIndexAlias() + "," + ontologyChunks; - } - - private static int collectSearchHits( - JsonNode hitsNode, - double threshold, - LinkedHashMap>> byParent) { - int pageHitCount = 0; - for (JsonNode hit : hitsNode) { - pageHitCount++; - double score = hit.path("_score").asDouble(0.0); - // When threshold > 0, OpenSearch already applies min_score at the KNN query level. - // This post-filter acts as a safety net for the no-threshold case (k-based retrieval), - // where low-scoring neighbors may still be returned to fill the k count. - if (score < threshold) { - continue; - } - - Map hitMap = MAPPER.convertValue(hit.path("_source"), Map.class); - hitMap.put("_score", score); - - String parentId = (String) hitMap.getOrDefault("parentId", hit.path("_id").asText()); - // Persist the fallback into the result map so consumers (e.g. SemanticSearchTool collapsing - // chunks by entity) see the same parentId this grouping used, matching the ES service. - hitMap.put("parentId", parentId); - List> group = - byParent.computeIfAbsent(parentId, ignored -> new ArrayList<>()); - // During chunk-index migration the same chunk can surface twice — once from the legacy - // entity-doc embedding and once from the dedicated chunk index. Keep the first (higher - // scoring) occurrence per chunkIndex. - if (!isDuplicateChunk(group, hitMap.get("chunkIndex"))) { - group.add(hitMap); - } - } - return pageHitCount; - } - - private static boolean isDuplicateChunk(List> group, Object chunkIndex) { - boolean duplicate = false; - Object key = normalizeChunkIndex(chunkIndex); - for (Map member : group) { - if (key.equals(normalizeChunkIndex(member.get("chunkIndex")))) { - duplicate = true; - break; - } - } - return duplicate; - } - - /** - * Every embedding writer (legacy entity-doc and chunk-index) sets {@code chunkIndex} — 0 for the - * legacy single-doc format — so a missing value can only come from exotic/manual docs. Treat it - * as chunk 0 so such a doc still dedupes against the real chunk 0 during dual-write migration. - */ - private static Object normalizeChunkIndex(Object chunkIndex) { - return chunkIndex == null ? 0 : chunkIndex; - } - - private static long extractTotalHits(JsonNode root) { - JsonNode totalNode = root.path("hits").path("total"); - if (totalNode.isIntegralNumber()) { - return totalNode.asLong(-1L); - } - if (totalNode.isObject()) { - return totalNode.path("value").asLong(-1L); - } - return -1L; - } - - @Override - public String getExistingFingerprint(String indexName, String entityId) { - try { - String query = - "{\"size\":1,\"_source\":[\"fingerprint\"]," - + "\"query\":{\"term\":{\"_id\":\"" - + VectorSearchQueryBuilder.escape(entityId) - + "\"}}}"; - String response = executeGenericRequest("POST", "/" + indexName + "/_search", query); - JsonNode root = MAPPER.readTree(response); - JsonNode hits = root.path("hits").path("hits"); - if (hits.isArray() && !hits.isEmpty()) { - return hits.get(0).path("_source").path("fingerprint").asText(null); - } - } catch (Exception e) { - LOG.debug( - "Failed to get fingerprint for entityId={} in index={}: {}", - entityId, - indexName, - e.getMessage()); - } - return null; + return MAPPER + .createObjectNode() + .put("type", "knn_vector") + .put("dimension", dimension) + .set("method", method); } @Override - public Map getExistingFingerprintsBatch( - String indexName, List entityIds) { - if (entityIds == null || entityIds.isEmpty()) { - return Collections.emptyMap(); - } - try { - StringBuilder idsArray = new StringBuilder("["); - for (int i = 0; i < entityIds.size(); i++) { - if (i > 0) idsArray.append(','); - idsArray - .append("\"") - .append(VectorSearchQueryBuilder.escape(entityIds.get(i))) - .append("\""); - } - idsArray.append("]"); - - String query = - "{\"size\":" - + entityIds.size() - + ",\"_source\":[\"fingerprint\"]" - + ",\"query\":{\"ids\":{\"values\":" - + idsArray - + "}}}"; - - String response = executeGenericRequest("POST", "/" + indexName + "/_search", query); - JsonNode root = MAPPER.readTree(response); - JsonNode hits = root.path("hits").path("hits"); - - Map result = new HashMap<>(); - for (JsonNode hit : hits) { - String id = hit.path("_id").asText(); - String fp = hit.path("_source").path("fingerprint").asText(null); - if (id != null && fp != null) { - result.put(id, fp); - } - } - return result; - } catch (Exception e) { - LOG.error("Failed to batch get fingerprints in index={}: {}", indexName, e.getMessage(), e); - return Collections.emptyMap(); - } + protected String buildKnnSearch( + float[] vector, VectorSearchParameters parameters, Set readableAnchorIds) { + return VectorSearchQueryBuilder.build(vector, parameters, readableAnchorIds); } - private static final List EMBEDDING_SOURCE_FIELDS = - List.of( - "fingerprint", - "embedding", - "textToLLMContext", - "textToEmbed", - "chunkIndex", - "chunkCount", - "parentId"); - - // Jackson-backed mapper so JsonData.to(JsonNode.class, ...) deserializes via Jackson - // and produces a tree of Jackson types (TextNode, ArrayNode, etc.) rather than - // jakarta.json.JsonValue wrappers like org.glassfish.json.JsonStringImpl. - private static final JacksonJsonpMapper JACKSON_JSONP_MAPPER = new JacksonJsonpMapper(MAPPER); - - /** - * Two-step batch fetch of the stored embeddings a reindex may reuse, keyed by entity id. Designed - * to keep large vector payloads off the wire for entities that will be re-embedded anyway. - * - *

Step 1 — {@code mget} only the stored {@code fingerprint} for every requested ID and keep - * the IDs whose fingerprint equals the current one (see {@link StoredEmbeddingReuse}). - * - *

Step 2 — issue a second {@code mget} that pulls the full embedding {@code _source} only for - * matching IDs. Entries that don't match are dropped, and the caller can rely on every returned - * value being safe to splice into a staged index document. - * - * @param currentFingerprintById each entity's current fingerprint, computed only when a stored - * one exists - */ @Override - public Map getExistingEmbeddingsBatch( - String indexName, Map> currentFingerprintById) { - if (currentFingerprintById == null || currentFingerprintById.isEmpty()) { - return Collections.emptyMap(); - } - try { - List entityIds = new ArrayList<>(currentFingerprintById.keySet()); - MgetResponse headerResponse = - client.mget( - m -> - m.index(indexName) - .ids(entityIds) - .sourceIncludes(StoredEmbeddingReuse.HEADER_FIELDS), - JsonData.class); - - List matchingIds = new ArrayList<>(); - for (MultiGetResponseItem item : headerResponse.docs()) { - if (!item.isResult()) { - continue; - } - GetResult doc = item.result(); - if (!doc.found() || doc.source() == null) { - continue; - } - JsonNode header = doc.source().to(JsonNode.class, JACKSON_JSONP_MAPPER); - if (header == null || !header.isObject()) { - continue; - } - Supplier currentFingerprint = currentFingerprintById.get(doc.id()); - if (currentFingerprint != null - && StoredEmbeddingReuse.fingerprintMatches(doc.id(), header, currentFingerprint)) { - matchingIds.add(doc.id()); - } - } - if (matchingIds.isEmpty()) { - return Collections.emptyMap(); - } - - MgetResponse response = - client.mget( - m -> m.index(indexName).ids(matchingIds).sourceIncludes(EMBEDDING_SOURCE_FIELDS), - JsonData.class); - - Map result = new HashMap<>(); - for (MultiGetResponseItem item : response.docs()) { - if (!item.isResult()) { - continue; - } - GetResult doc = item.result(); - if (!doc.found() || doc.source() == null) { - continue; - } - JsonNode cached = doc.source().to(JsonNode.class, JACKSON_JSONP_MAPPER); - if (StoredEmbeddingReuse.isSpliceable(cached)) { - result.put(doc.id(), cached); - } - } - return result; - } catch (Exception e) { - LOG.error("Failed to batch get embeddings in index={}", indexName, e); - return Collections.emptyMap(); - } - } - - public void partialUpdateEntity( - String indexName, String entityId, Map embeddingFields) { - try { - String docJson = MAPPER.writeValueAsString(embeddingFields); - String updateBody = "{\"doc\":" + docJson + "}"; - executeGenericRequest( - "POST", "/" + indexName + "/_update/" + entityId + "?retry_on_conflict=3", updateBody); - } catch (Exception e) { - LOG.error( - "Failed to partial update entity {} in {}: {}", entityId, indexName, e.getMessage(), e); - } - } - - @Override - public void clearEntityEmbedding(String entityIndexName, String entityId) { - // A doc merge cannot delete keys, so removal has to go through a script. - try { - String fieldsJson = MAPPER.writeValueAsString(EMBEDDING_SOURCE_FIELDS); - String updateBody = - "{\"script\":{\"source\":\"for (field in params.fields) { ctx._source.remove(field) }\"," - + "\"params\":{\"fields\":" - + fieldsJson - + "}}}"; - executeGenericRequest( - "POST", - "/" + entityIndexName + "/_update/" + entityId + "?retry_on_conflict=3", - updateBody); - } catch (Exception e) { - LOG.error( - "Failed to clear embedding for entity {} in {}: {}", - entityId, - entityIndexName, - e.getMessage(), - e); - } + protected boolean chunksOntologyTerms() { + return true; } @Override - public String executeGenericRequest(String method, String endpoint, String body) { - try { - return GENERIC_REQUEST_RETRY.executeSupplier( - () -> executeGenericRequestAttempt(method, endpoint, body)); - } catch (RuntimeException e) { - Throwable cause = e instanceof UncheckedIOException ? e.getCause() : e; - LOG.error("Generic request failed: {} {}", method, endpoint, cause); - throw new RuntimeException("OpenSearch generic request failed", cause); - } - } - - private String executeGenericRequestAttempt(String method, String endpoint, String body) { - var builder = Requests.builder().endpoint(endpoint).method(method); - if (body != null) { - builder.json(body); - } - try (var response = client.generic().execute(builder.build())) { - validateGenericResponse(response); - return response.getBody().map(this::readGenericResponseBody).orElse("{}"); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - private void validateGenericResponse(Response response) throws IOException { - if (response.getStatus() >= 400) { - String errorBody = response.getBody().map(Body::bodyAsString).orElse("no body"); - String message = - "OpenSearch request failed with status " + response.getStatus() + ": " + errorBody; - if (response.getStatus() >= 500 && errorBody.contains(ALREADY_CLOSED_EXCEPTION)) { - throw new ClosedSegmentException(message); - } - throw new IOException(message); - } - } - - private String readGenericResponseBody(Body body) { - try { - return new String(body.bodyAsBytes(), StandardCharsets.UTF_8); - } catch (RuntimeException e) { - LOG.warn("Failed to read OpenSearch response body", e); - return "{}"; - } - } - - private static final class ClosedSegmentException extends IOException { - private ClosedSegmentException(String message) { - super(message); - } + protected boolean knnReturnsAtMostK(double threshold) { + // With min_score set, the knn query returns every neighbour above it, however many. + return threshold <= 0.0; } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/StoredEmbeddingReuse.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/StoredEmbeddingReuse.java index c9dd1db79b24..a20830f294b2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/StoredEmbeddingReuse.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/StoredEmbeddingReuse.java @@ -7,14 +7,15 @@ /** * When a reindex may copy the embedding stored on an entity search doc into the rebuilt doc instead - * of calling the embedding provider. Shared by the OpenSearch and Elasticsearch vector services. + * of calling the embedding provider. The vector index service selects stored embeddings by these + * rules and the reindex bulk sinks check them again where they splice. * *

The stored fingerprint is the only reuse key. An unchanged {@code updatedAt} is not enough: a * release that changes the embedding text leaves every entity's {@code updatedAt} as it was. * ADR:2026-11-11-reindex-reuses-an-embedding-only-when-its-fingerprint-matches */ @Slf4j -final class StoredEmbeddingReuse { +public final class StoredEmbeddingReuse { static final String FINGERPRINT_FIELD = "fingerprint"; static final List HEADER_FIELDS = List.of(FINGERPRINT_FIELD); @@ -33,12 +34,14 @@ static boolean fingerprintMatches( // own reuse, not every other entity's in the batch. private static String currentFingerprintOrNull( String entityId, Supplier currentFingerprint) { + String fingerprint; try { - return currentFingerprint.get(); + fingerprint = currentFingerprint.get(); } catch (RuntimeException e) { LOG.warn("Cannot fingerprint entity {}; re-embedding it: {}", entityId, e.getMessage()); - return null; + fingerprint = null; } + return fingerprint; } /** @@ -54,6 +57,16 @@ && hasEmbedding(cached) && !cached.path(FINGERPRINT_FIELD).asText().isBlank(); } + /** + * As {@link #isSpliceable(JsonNode)}, for an index built with {@code dimension}-dimensional + * vectors. The fingerprint covers the entity's text and not the embedding model, so after a model + * change a stored vector still matches by fingerprint while the new index would reject its + * length. A non-positive {@code dimension} means no embedding client and skips the comparison. + */ + public static boolean isSpliceable(JsonNode cached, int dimension) { + return isSpliceable(cached) && (dimension <= 0 || cached.path("embedding").size() == dimension); + } + private static boolean hasEmbedding(JsonNode cached) { JsonNode embedding = cached.path("embedding"); return embedding.isArray() && !embedding.isEmpty(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/UnrecordedStagedChunkDeleteException.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/UnrecordedStagedChunkDeleteException.java new file mode 100644 index 000000000000..183906d546e8 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/UnrecordedStagedChunkDeleteException.java @@ -0,0 +1,17 @@ +package org.openmetadata.service.search.vector; + +/** + * This node missed a delete from the run's staged chunk generation and could not record it on the + * cluster. A partition that ends with it fails for good, without a retry: no node can repair the + * missed delete, and the failed partition's error, which starts with {@link + * VectorIndexService#UNRECORDED_STAGED_DELETE}, is what keeps the generation from going live. + */ +public class UnrecordedStagedChunkDeleteException extends IllegalStateException { + public UnrecordedStagedChunkDeleteException(String generation) { + super( + VectorIndexService.UNRECORDED_STAGED_DELETE + + ": a delete from staged chunk index " + + generation + + " failed and the flag that blocks its promotion could not be saved"); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorDocBuilder.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorDocBuilder.java index 1a87a490b894..f641f71432ea 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorDocBuilder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorDocBuilder.java @@ -54,7 +54,7 @@ public class VectorDocBuilder { * Schema version of the denormalized chunk document (issue #862/#858). Stamped on every chunk doc * as {@code docVersion} and mirrored on the chunk index mapping as {@code _meta.chunkDocVersion}. * Bump this whenever {@link #buildDenormalizedFields} materializes a new field or changes an existing one - * so {@code OpenSearchVectorService} triggers an additive {@code PUT _mapping} and an + * so {@code AbstractVectorIndexService} triggers an additive {@code PUT _mapping} and an * embedding-reuse backfill on the next Search Reindex — without forcing a re-embed (the * fingerprint is deliberately left untouched, see {@link #computeFingerprintForEntity}). */ @@ -633,6 +633,33 @@ public static Map buildEmbeddingFields( return fields; } + /** The embedding fields an entity document carries; the {@code _source} a reindex reuses. */ + static final List EMBEDDING_SOURCE_FIELDS = + List.of( + "fingerprint", + "embedding", + "textToLLMContext", + "textToEmbed", + "chunkIndex", + "chunkCount", + "parentId"); + + /** + * The legacy entity-doc embedding payload extracted from a chunk document: only the embedding + * fields, never the chunk doc's trimmed filter fields (tags/domains/tier), which would clobber + * the entity doc's rich versions of those fields on partial update. + */ + public static Map legacyEmbeddingFields(Map chunkDoc) { + Map fields = new HashMap<>(); + for (String key : EMBEDDING_SOURCE_FIELDS) { + Object value = chunkDoc.get(key); + if (value != null) { + fields.put(key, value); + } + } + return fields; + } + public static String computeFingerprintForEntity(EntityInterface entity) { String entityType = entity.getEntityReference().getType(); return computeFingerprintForEntity(entity, buildBodyText(entity, entityType)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorIndexService.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorIndexService.java index f495170fec11..e269144f84ba 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorIndexService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorIndexService.java @@ -10,43 +10,33 @@ import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; import org.openmetadata.service.security.policyevaluator.SubjectContext; +/** + * The vector index of the configured search engine. Callers reach it through {@code + * SearchRepository.getVectorIndexService()}, never through an engine class, so every capability + * here exists on both Elasticsearch and OpenSearch. + */ public interface VectorIndexService { String VECTOR_EMBEDDING_ALIAS = "dataAssetEmbeddings"; - Map generateEmbeddingFields(EntityInterface entity); - - default EmbeddingClient getEmbeddingClient() { - return null; - } + /** + * Starts the error of a partition failed for good by {@link + * #requireStagedChunkFailuresRecorded}, so the coordinator can keep the run's chunk generation + * from going live. + */ + String UNRECORDED_STAGED_DELETE = "Unrecorded staged chunk delete"; - default Map getExistingEmbeddingsBatch( - String indexName, Map> fingerprints) { - return Map.of(); - } + EmbeddingClient getEmbeddingClient(); - /** A matching content fingerprint can still come from an embedding model of another dimension. */ - static boolean canReuseCachedEmbedding(JsonNode cached, int dimension) { - if (cached == null || !cached.isObject()) { - return false; - } - final var vector = cached.path("embedding"); - final var fingerprint = cached.path("fingerprint"); - return vector.isArray() - && !vector.isEmpty() - && (dimension <= 0 || vector.size() == dimension) - && fingerprint.isTextual() - && !fingerprint.asText().isBlank(); - } + Map generateEmbeddingFields(EntityInterface entity); void updateEntityEmbedding(EntityInterface entity, String entityIndexName); /** * Multi-chunk write path (issue #4789): index one document per body chunk into the dedicated - * chunk index so long articles are fully retrievable. Default is a no-op for backends without - * chunk support. + * chunk index so long articles are fully retrievable. */ - default void updateEntityEmbeddingChunks(EntityInterface entity) {} + void updateEntityEmbeddingChunks(EntityInterface entity); default void updateEntityEmbeddings( EntityInterface entity, String indexName, String ontologyBody) { @@ -54,25 +44,90 @@ default void updateEntityEmbeddings( } /** Remove all chunk documents for the given parent entity (hard/soft delete cleanup). */ - default void deleteEntityChunks(String parentId) {} + void deleteEntityChunks(String parentId); /** * Strip the embedding fields from an entity document. Entity-doc embedding writes are partial * merges, so an entity whose repository stops considering it embeddable would otherwise keep a - * stale {@code embedding} and stay matchable by kNN. Default is a no-op for backends without the - * legacy entity-doc embedding. + * stale {@code embedding} and stay matchable by kNN. */ - default void clearEntityEmbedding(String entityIndexName, String entityId) {} + void clearEntityEmbedding(String entityIndexName, String entityId); /** * Combined write: refresh both the legacy entity-doc embedding (read by hybrid search) and the - * chunk documents (read by the semantic vector path). Implementations should embed each chunk - * once and reuse chunk 0 for the entity doc; this default simply chains the two writes. + * chunk documents (read by the semantic vector path), embedding each chunk once and reusing + * chunk 0 for the entity doc. */ - default void updateEntityEmbeddings(EntityInterface entity, String entityIndexName) { - updateEntityEmbedding(entity, entityIndexName); - updateEntityEmbeddingChunks(entity); - } + void updateEntityEmbeddings(EntityInterface entity, String entityIndexName); + + /** + * Reindex-sink write of prebuilt chunk documents. {@code stagedChunkTarget} is the generation + * the run staged with {@link #beginStagedChunkRecreate}, or null to write to the live index. + * Returns false when the chunks could not be written, a miss the caller counts and retries. + */ + boolean writeEntityChunks( + String parentId, List> chunkDocs, String stagedChunkTarget); + + /** + * Reindex-sink backfill of chunk documents for an entity whose stored embedding is reused, into + * {@code stagedChunkTarget} or, when null, the live index. Returns false when the chunks could + * not be written, or needed the embedding provider while it was unavailable. + */ + boolean backfillEntityChunks(EntityInterface entity, String stagedChunkTarget); + + /** + * Reindex-sink write of an entity's embedding fields into its already indexed document in + * {@code entityIndexName}, for an entity the run could not embed on its first attempt. Returns + * false when the document could not be updated, a miss the caller counts. + */ + boolean writeEntityEmbedding( + String entityIndexName, String entityId, Map embeddingFields); + + /** + * The stored entity-doc embeddings a reindex may reuse, keyed by entity id: those whose stored + * fingerprint equals the current one. + * + * @param currentFingerprintById each entity's current fingerprint, computed only when a stored + * one exists + */ + Map getExistingEmbeddingsBatch( + String indexName, Map> currentFingerprintById); + + /** + * The {@code textToLLMContext} of the {@code k} chunks of one parent entity most relevant to + * {@code query}, resolving context memory visibility for {@code subjectContext}. + */ + List searchChunksByParent( + String parentId, String query, int k, SubjectContext subjectContext); + + /** + * Begins a staged recreate of the chunk index for a full-recreate run and returns the staged + * generation, or null when nothing was staged and the run reindexes in place. + */ + String beginStagedChunkRecreate(); + + /** Forgets {@code generation} as this node's staged recreate, without touching the index. */ + void clearStagedChunkState(String generation); + + /** + * Records whether one entity type's staged entity index replaced its live index, for the run + * that staged {@code runGeneration}. Once every expected type has finalized, the staged chunk + * generation is promoted when all their entity indexes were. + */ + void markEntityTypeReindexed( + String entityType, boolean entityIndexPromoted, String runGeneration); + + /** Routes this participant node's live chunk writes to the run's staged generation as well. */ + void latchParticipantStagedTarget(String staged); + + void clearParticipantStagedTarget(); + + /** + * Throws {@link UnrecordedStagedChunkDeleteException} when this node missed a delete from the + * run's staged generation and could not record it, so the caller's partition fails for good and + * the generation is not promoted. + */ + void requireStagedChunkFailuresRecorded(); default VectorSearchResponse search( String query, @@ -100,7 +155,7 @@ default VectorSearchResponse search( * fail-closed: only org-wide memories match, so a caller that cannot identify its user never sees * a restricted one. Callers whose filters already exclude memories can leave it null. */ - VectorSearchResponse search( + default VectorSearchResponse search( String query, Map> filters, int size, @@ -108,24 +163,15 @@ VectorSearchResponse search( int k, double threshold, String preference, - SubjectContext subjectContext); - - /** Search with a compiled query filter in addition to the structured vector filters. */ - default VectorSearchResponse search(VectorSearchParameters parameters) { - if (parameters.queryFilter() != null && !parameters.queryFilter().isBlank()) { - throw new UnsupportedOperationException("Compiled vector query filters are not supported"); - } + SubjectContext subjectContext) { return search( - parameters.query(), - parameters.filters(), - parameters.size(), - parameters.from(), - parameters.k(), - parameters.threshold(), - parameters.preference(), - parameters.subjectContext()); + new VectorSearchParameters( + query, filters, size, from, k, threshold, preference, subjectContext, null)); } + /** Search with a compiled query filter in addition to the structured vector filters. */ + VectorSearchResponse search(VectorSearchParameters parameters); + String getExistingFingerprint(String indexName, String entityId); Map getExistingFingerprintsBatch(String indexName, List entityIds); @@ -133,14 +179,15 @@ default VectorSearchResponse search(VectorSearchParameters parameters) { String executeGenericRequest(String method, String endpoint, String body); default String getIndexAlias() { + String alias = VECTOR_EMBEDDING_ALIAS; try { String clusterAlias = Entity.getSearchRepository().getClusterAlias(); - if (clusterAlias == null || clusterAlias.isEmpty()) { - return VECTOR_EMBEDDING_ALIAS; + if (clusterAlias != null && !clusterAlias.isEmpty()) { + alias = clusterAlias + "_" + VECTOR_EMBEDDING_ALIAS; } - return clusterAlias + "_" + VECTOR_EMBEDDING_ALIAS; } catch (Exception ex) { - return VECTOR_EMBEDDING_ALIAS; + alias = VECTOR_EMBEDDING_ALIAS; } + return alias; } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java index f7b15782771f..0ce7a49b16fa 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java @@ -165,8 +165,7 @@ public static String buildNativeESQuery( /** * As {@link #buildNativeESQuery}, constraining context memories to those {@code subjectContext} - * may see. Elasticsearch has no chunk index, so this filters memory entity documents, which carry - * the same visibility fields. + * may see. Memory entity documents and their chunk documents carry the same visibility fields. */ public static String buildNativeESQuery( float[] vector, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchUtils.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchUtils.java deleted file mode 100644 index 05eebfea9cc6..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.openmetadata.service.search.vector; - -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.EntityInterface; -import org.openmetadata.search.IndexMapping; -import org.openmetadata.service.Entity; -import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; - -@Slf4j -public final class VectorSearchUtils { - private VectorSearchUtils() {} - - public static void updateVectorEmbeddingsForOpenSearch(EntityInterface entity) { - String entityType = entity.getEntityReference().getType(); - updateVectorEmbeddingsForOpenSearch(entity, entityType); - } - - public static void updateVectorEmbeddingsForOpenSearch( - EntityInterface entity, String entityType) { - if (!Entity.getSearchRepository().isVectorEmbeddingEnabled()) { - return; - } - if (!AvailableEntityTypes.isVectorIndexable(entityType)) { - return; - } - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); - if (vectorService == null) { - return; - } - try { - IndexMapping mapping = Entity.getSearchRepository().getIndexMapping(entityType); - if (mapping == null) { - LOG.warn("No index mapping found for entity type: {}", entityType); - return; - } - String entityIndexName = mapping.getIndexName(Entity.getSearchRepository().getClusterAlias()); - vectorService.updateEntityEmbedding(entity, entityIndexName); - } catch (Exception e) { - LOG.error( - "Failed to update vector embeddings for entity {}: {}", - entity.getId(), - e.getMessage(), - e); - } - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/utils/DTOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/utils/DTOs.java index 050e7056eacf..000dc35832f1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/utils/DTOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/utils/DTOs.java @@ -33,7 +33,7 @@ public static class VectorSearchResponse { public long tookMillis; public List> hits; - // Total raw hits returned by OpenSearch before parent-level grouping. + // Total raw hits the search engine returned before parent-level grouping. public Long totalHits; // Indicates whether additional parent groups may be available after this page. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/util/OpenMetadataOperations.java b/openmetadata-service/src/main/java/org/openmetadata/service/util/OpenMetadataOperations.java index 7fd0455e801d..22088f0bb582 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/util/OpenMetadataOperations.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/util/OpenMetadataOperations.java @@ -99,6 +99,7 @@ import org.openmetadata.service.apps.bundles.searchIndex.SlackWebApiClient; import org.openmetadata.service.apps.scheduler.AppScheduler; import org.openmetadata.service.cache.CacheConfig; +import org.openmetadata.service.clients.llm.LlmConfigHolder; import org.openmetadata.service.clients.pipeline.PipelineServiceClientFactory; import org.openmetadata.service.config.source.ConfigSources; import org.openmetadata.service.config.source.ConfigTemplateKind; @@ -147,6 +148,7 @@ import org.openmetadata.service.search.fitness.SearchClusterFitnessAnalyzer; import org.openmetadata.service.search.fitness.SearchClusterFitnessReport; import org.openmetadata.service.search.opensearch.OpenSearchClient; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.secrets.SecretsManager; import org.openmetadata.service.secrets.SecretsManagerFactory; import org.openmetadata.service.secrets.SecretsManagerUpdateService; @@ -1780,167 +1782,181 @@ public Integer reembed( defaultValue = "300", description = "Queue size for buffering embedding tasks.") int queueSize) { - int finalProducerThreads = - producerThreads <= 0 - ? Math.max(1, Runtime.getRuntime().availableProcessors()) - : producerThreads; - int finalConsumerThreads = - consumerThreads <= 0 - ? Math.max(1, Runtime.getRuntime().availableProcessors()) - : consumerThreads; + int finalProducerThreads = threadsOrProcessorCount(producerThreads); + int finalConsumerThreads = threadsOrProcessorCount(consumerThreads); int finalQueueSize = Math.max(1, queueSize); - java.util.concurrent.BlockingQueue taskQueue = - new java.util.concurrent.LinkedBlockingQueue<>(finalQueueSize); - java.util.concurrent.atomic.AtomicBoolean producersDone = - new java.util.concurrent.atomic.AtomicBoolean(false); - java.util.concurrent.ConcurrentHashMap - processedCounts = new java.util.concurrent.ConcurrentHashMap<>(); - java.util.concurrent.ConcurrentHashMap - failedCounts = new java.util.concurrent.ConcurrentHashMap<>(); - java.util.concurrent.ExecutorService producerExecutor = - java.util.concurrent.Executors.newFixedThreadPool( - finalProducerThreads, Thread.ofPlatform().name("reembed-producer-", 0).factory()); - java.util.concurrent.ExecutorService consumerExecutor = - java.util.concurrent.Executors.newFixedThreadPool( - finalConsumerThreads, Thread.ofPlatform().name("reembed-consumer-", 0).factory()); + ReembedRun run = + new ReembedRun( + new java.util.concurrent.LinkedBlockingQueue<>(finalQueueSize), + new java.util.concurrent.atomic.AtomicBoolean(false), + new java.util.concurrent.ConcurrentHashMap<>(), + new java.util.concurrent.ConcurrentHashMap<>(), + java.util.concurrent.Executors.newFixedThreadPool( + finalProducerThreads, Thread.ofPlatform().name("reembed-producer-", 0).factory()), + java.util.concurrent.Executors.newFixedThreadPool( + finalConsumerThreads, Thread.ofPlatform().name("reembed-consumer-", 0).factory())); + int exitCode = 1; try { - if (!OpenMetadataApplicationConfigHolder.isInitialized()) { - parseConfig(); + initializeReembedRuntime(); + VectorIndexService vecService = prepareReembedVectorService(); + if (vecService != null) { + LOG.info( + "Re-embedding with producers: {}, consumers: {}, queue size: {}, batch size: {}", + finalProducerThreads, + finalConsumerThreads, + finalQueueSize, + batchSize); + reembedAllTypes(vecService, run, batchSize, finalConsumerThreads); + LOG.info("Re-embedding completed successfully"); + exitCode = 0; } - CollectionRegistry.initialize(); - var omConfig = OpenMetadataApplicationConfigHolder.getInstance(); - ApplicationHandler.initialize(omConfig); - SeedDataGate.getInstance().forceSeedData(); - CollectionRegistry.getInstance() - .loadSeedData(Entity.getJdbi(), omConfig, null, null, null, true); - TypeRepository typeRepository = (TypeRepository) Entity.getEntityRepository(Entity.TYPE); - TypeRegistry.instance().initialize(typeRepository); + } catch (Exception e) { + LOG.error("Failed to run full re-embedding", e); + } finally { + shutdownReembedExecutor(run.producerExecutor(), "reembed-producer"); + shutdownReembedExecutor(run.consumerExecutor(), "reembed-consumer"); + } + return exitCode; + } - SearchRepository repo = Entity.getSearchRepository(); - if (repo == null) { - LOG.error("Search repository is not initialized; cannot run re-embedding"); - return 1; - } + private static int threadsOrProcessorCount(int threads) { + return threads <= 0 ? Math.max(1, Runtime.getRuntime().availableProcessors()) : threads; + } + private void initializeReembedRuntime() throws Exception { + if (!OpenMetadataApplicationConfigHolder.isInitialized()) { + parseConfig(); + } + CollectionRegistry.initialize(); + var omConfig = OpenMetadataApplicationConfigHolder.getInstance(); + ApplicationHandler.initialize(omConfig); + SeedDataGate.getInstance().forceSeedData(); + CollectionRegistry.getInstance() + .loadSeedData(Entity.getJdbi(), omConfig, null, null, null, true); + TypeRepository typeRepository = (TypeRepository) Entity.getEntityRepository(Entity.TYPE); + TypeRegistry.instance().initialize(typeRepository); + } + + /** The engine's vector service ready to re-embed, or null when re-embedding cannot run. */ + private static VectorIndexService prepareReembedVectorService() { + SearchRepository repo = Entity.getSearchRepository(); + VectorIndexService vecService = null; + if (repo == null) { + LOG.error("Search repository is not initialized; cannot run re-embedding"); + } else { repo.prepareForReindex(); - org.openmetadata.service.search.vector.OpenSearchVectorService vecService = - org.openmetadata.service.search.vector.OpenSearchVectorService.getInstance(); + vecService = repo.getVectorIndexService(); if (vecService == null || vecService.getEmbeddingClient() == null) { LOG.warn("Vector embeddings are disabled or not initialized. Skipping re-embedding."); - return 1; + vecService = null; } + } + return vecService; + } - java.util.concurrent.ConcurrentHashMap entityTotals = - new java.util.concurrent.ConcurrentHashMap<>(); - int totalBatches = calculateReembedTotalBatches(batchSize, entityTotals); - java.util.concurrent.CountDownLatch producerLatch = - new java.util.concurrent.CountDownLatch(totalBatches); + private void reembedAllTypes( + VectorIndexService vecService, ReembedRun run, int batchSize, int consumerThreads) + throws InterruptedException { + Map entityTotals = new java.util.concurrent.ConcurrentHashMap<>(); + int totalBatches = calculateReembedTotalBatches(batchSize, entityTotals); + java.util.concurrent.CountDownLatch producerLatch = + new java.util.concurrent.CountDownLatch(totalBatches); + java.util.concurrent.CountDownLatch consumerLatch = + startReembedConsumers( + consumerThreads, + run.consumerExecutor(), + run.taskQueue(), + run.producersDone(), + vecService, + run.processedCounts(), + run.failedCounts()); + for (String entityType : + org.openmetadata.service.search.vector.utils.AvailableEntityTypes.LIST) { + if (isReembedableEntityType(entityType)) { + // Ontology term embeddings are rebuilt only via the release-aware reindex path, which + // publishes terms through the gated writer that keeps drafts out of search. See + // calculateReembedTotalBatches, which also excludes term types, and the ADR 2026-11-23. + scheduleReembedBatches( + entityType, entityTotals.getOrDefault(entityType, 0), batchSize, run, producerLatch); + } + } + awaitReembedProducers(producerLatch, run.producerExecutor()); + run.producersDone().set(true); + signalReembedConsumersToStop(consumerThreads, run.taskQueue()); + consumerLatch.await(); + logReembedSummary(run); + } + private void scheduleReembedBatches( + String entityType, + int totalRecords, + int batchSize, + ReembedRun run, + java.util.concurrent.CountDownLatch producerLatch) { + int batches = calculateReembedNumberOfBatches(totalRecords, batchSize); + if (batches == 0) { + LOG.info("No entities found for type {}, skipping", entityType); + } else { + org.openmetadata.service.workflows.searchIndex.PaginatedEntitiesSource source = + new org.openmetadata.service.workflows.searchIndex.PaginatedEntitiesSource( + entityType, batchSize, List.of("*")); LOG.info( - "Re-embedding with producers: {}, consumers: {}, queue size: {}, batch size: {}", - finalProducerThreads, - finalConsumerThreads, - finalQueueSize, - batchSize); - - java.util.concurrent.CountDownLatch consumerLatch = - startReembedConsumers( - finalConsumerThreads, - consumerExecutor, - taskQueue, - producersDone, - vecService, - processedCounts, - failedCounts); - - for (String entityType : - org.openmetadata.service.search.vector.utils.AvailableEntityTypes.LIST) { - if (!isReembedableEntityType(entityType)) { - // Ontology term embeddings are rebuilt only via the release-aware reindex path, which - // publishes terms through the gated writer that keeps drafts out of search. See - // calculateReembedTotalBatches, which also excludes term types, and the ADR - // 2026-11-23. - continue; - } - int totalRecords = entityTotals.getOrDefault(entityType, 0); - int batches = calculateReembedNumberOfBatches(totalRecords, batchSize); - if (batches == 0) { - LOG.info("No entities found for type {}, skipping", entityType); - continue; - } - - org.openmetadata.service.workflows.searchIndex.PaginatedEntitiesSource source = - new org.openmetadata.service.workflows.searchIndex.PaginatedEntitiesSource( - entityType, batchSize, List.of("*")); - - LOG.info( - "Scheduling re-embedding for entity type {} with {} records ({} batches)", - entityType, - totalRecords, - batches); - - for (int i = 0; i < batches; i++) { - int offset = i * batchSize; - producerExecutor.submit( - () -> { - try { - org.openmetadata.schema.utils.ResultList> batch = - source.readWithCursor(RestUtil.encodeCursor(String.valueOf(offset))); - if (batch != null && batch.getData() != null && !batch.getData().isEmpty()) { - taskQueue.put(new ReembedTask(entityType, batch)); - } - if (batch != null && batch.getErrors() != null && !batch.getErrors().isEmpty()) { - failedCounts - .computeIfAbsent( - entityType, key -> new java.util.concurrent.atomic.AtomicInteger(0)) - .addAndGet(batch.getErrors().size()); - } - } catch (Exception e) { - LOG.warn( - "Failed to read batch for entity type {} at offset {}", - entityType, - offset, - e); - } finally { - producerLatch.countDown(); - } - }); - } + "Scheduling re-embedding for entity type {} with {} records ({} batches)", + entityType, + totalRecords, + batches); + for (int i = 0; i < batches; i++) { + int offset = i * batchSize; + run.producerExecutor() + .submit(() -> produceReembedBatch(source, entityType, offset, run, producerLatch)); } + } + } - awaitReembedProducers(producerLatch, producerExecutor); - producersDone.set(true); - signalReembedConsumersToStop(finalConsumerThreads, taskQueue); - consumerLatch.await(); - - for (String entityType : - org.openmetadata.service.search.vector.utils.AvailableEntityTypes.LIST) { - int processed = - processedCounts - .getOrDefault(entityType, new java.util.concurrent.atomic.AtomicInteger(0)) - .get(); - int failed = - failedCounts - .getOrDefault(entityType, new java.util.concurrent.atomic.AtomicInteger(0)) - .get(); - LOG.info( - "Finished re-embedding {} entities for type {} (failed reads: {})", - processed, - entityType, - failed); + private static void produceReembedBatch( + org.openmetadata.service.workflows.searchIndex.PaginatedEntitiesSource source, + String entityType, + int offset, + ReembedRun run, + java.util.concurrent.CountDownLatch producerLatch) { + try { + org.openmetadata.schema.utils.ResultList> batch = + source.readWithCursor(RestUtil.encodeCursor(String.valueOf(offset))); + if (batch != null && batch.getData() != null && !batch.getData().isEmpty()) { + run.taskQueue().put(new ReembedTask(entityType, batch)); + } + if (batch != null && batch.getErrors() != null && !batch.getErrors().isEmpty()) { + run.failedCounts() + .computeIfAbsent(entityType, key -> new AtomicInteger(0)) + .addAndGet(batch.getErrors().size()); } - - LOG.info("Re-embedding completed successfully"); - return 0; } catch (Exception e) { - LOG.error("Failed to run full re-embedding", e); - return 1; + LOG.warn("Failed to read batch for entity type {} at offset {}", entityType, offset, e); } finally { - shutdownReembedExecutor(producerExecutor, "reembed-producer"); - shutdownReembedExecutor(consumerExecutor, "reembed-consumer"); + producerLatch.countDown(); + } + } + + private static void logReembedSummary(ReembedRun run) { + for (String entityType : + org.openmetadata.service.search.vector.utils.AvailableEntityTypes.LIST) { + LOG.info( + "Finished re-embedding {} entities for type {} (failed reads: {})", + run.processedCounts().getOrDefault(entityType, new AtomicInteger(0)).get(), + entityType, + run.failedCounts().getOrDefault(entityType, new AtomicInteger(0)).get()); } } + /** The state a re-embedding run shares between its producers and consumers. */ + private record ReembedRun( + java.util.concurrent.BlockingQueue taskQueue, + java.util.concurrent.atomic.AtomicBoolean producersDone, + Map processedCounts, + Map failedCounts, + java.util.concurrent.ExecutorService producerExecutor, + java.util.concurrent.ExecutorService consumerExecutor) {} + private record ReembedTask( String entityType, org.openmetadata.schema.utils.ResultList> batch) {} @@ -1950,7 +1966,7 @@ private java.util.concurrent.CountDownLatch startReembedConsumers( java.util.concurrent.ExecutorService consumerExecutor, java.util.concurrent.BlockingQueue taskQueue, java.util.concurrent.atomic.AtomicBoolean producersDone, - org.openmetadata.service.search.vector.OpenSearchVectorService vecService, + VectorIndexService vecService, Map processedCounts, Map failedCounts) { java.util.concurrent.CountDownLatch consumerLatch = @@ -1974,7 +1990,7 @@ private void runReembedConsumer( int consumerId, java.util.concurrent.BlockingQueue taskQueue, java.util.concurrent.atomic.AtomicBoolean producersDone, - org.openmetadata.service.search.vector.OpenSearchVectorService vecService, + VectorIndexService vecService, Map processedCounts, Map failedCounts) { LOG.debug("Consumer {} started", consumerId); @@ -3593,6 +3609,7 @@ public void parseConfig() throws Exception { configFilePath); IndexMappingLoader.init(config.getElasticSearchConfiguration()); Fernet.getInstance().setFernetKey(config); + LlmConfigHolder.initialize(config.getLlmConfiguration()); DataSourceFactory dataSourceFactory = config.getDataSourceFactory(); if (dataSourceFactory == null) { throw new IllegalArgumentException("No database in config file"); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextBuilderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextBuilderTest.java index 35121c1f978a..88789d64de46 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextBuilderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextBuilderTest.java @@ -21,7 +21,9 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.when; import jakarta.ws.rs.core.SecurityContext; import java.util.ArrayList; @@ -32,6 +34,7 @@ import java.util.Set; import java.util.UUID; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import org.openmetadata.schema.api.data.MetricExpression; import org.openmetadata.schema.api.services.CreateDatabaseService; import org.openmetadata.schema.entity.context.ContextMemory; @@ -52,6 +55,7 @@ import org.openmetadata.schema.type.Edge; import org.openmetadata.schema.type.EntityLineage; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.JoinedWith; import org.openmetadata.schema.type.LineageDetails; import org.openmetadata.schema.type.MetadataOperation; @@ -74,6 +78,8 @@ import org.openmetadata.schema.type.aicontext.TableContext; import org.openmetadata.schema.type.aicontext.TableDataModel; import org.openmetadata.service.Entity; +import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.OperationContext; @@ -265,6 +271,32 @@ void applyKnowledgeBudget_keepsShortItemsFullAndExcerptsOversized() { "excerpted article bounded to the excerpt length"); } + @Test + void applyKnowledgeBudget_excerptsAnOversizedItemWithThePassageMostRelevantToTheQuery() { + KnowledgeItem article = knowledgeItem("article", "z".repeat(4000)); + UUID articleId = UUID.randomUUID(); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(vectorService.searchChunksByParent(articleId.toString(), "refund window", 1, null)) + .thenReturn(List.of("Refunds are accepted within 30 days.")); + SearchRepository searchRepository = mock(SearchRepository.class); + when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); + + try (MockedStatic entity = mockStatic(Entity.class)) { + entity.when(Entity::getSearchRepository).thenReturn(searchRepository); + entity + .when(() -> Entity.getEntityReferenceByName("page", "kb.article", Include.NON_DELETED)) + .thenReturn(new EntityReference().withId(articleId)); + + new AIContextBuilder("table", "svc.db.sch.orders") + .withQuery("refund window") + .applyKnowledgeBudget(new AIContext().withArticles(List.of(article))); + } + + assertEquals("Refunds are accepted within 30 days.", article.getContent()); + assertTrue(article.getContentTruncated()); + } + @Test void resolveColumnGlossary_loadsEachTermOnceButBudgetsEveryColumnIndependently() { Map loads = new HashMap<>(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java index 29c068dbc754..3ce14414fc6c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java @@ -53,8 +53,7 @@ import org.openmetadata.service.search.elasticsearch.EsUtils; import org.openmetadata.service.search.indexes.DocBuildContext; import org.openmetadata.service.search.indexes.SearchIndex; -import org.openmetadata.service.search.vector.ElasticSearchVectorService; -import org.openmetadata.service.search.vector.client.EmbeddingClient; +import org.openmetadata.service.search.vector.VectorIndexService; class ElasticSearchBulkSinkBehaviorTest { @@ -169,6 +168,75 @@ void addEntityRecordsSuccessAndProcessStats() throws Exception { } } + @Test + void anEntityWithACurrentStoredEmbeddingIsIndexedWithItAndItsChunksAreBackfilled() + throws Exception { + EntityInterface entity = mock(EntityInterface.class); + UUID entityId = UUID.randomUUID(); + when(entity.getId()).thenReturn(entityId); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); + when(vectorService.backfillEntityChunks(any(), any())).thenReturn(true); + JsonNode storedEmbedding = + new ObjectMapper().readTree("{\"fingerprint\":\"fp\",\"embedding\":[0.1,0.2,0.3]}"); + ReindexContext recreate = new ReindexContext(); + recreate.setStagedChunkIndex("data_asset_embeddings_chunks_g1"); + + try (MockedConstruction processorConstruction = + mockConstruction(ElasticSearchBulkSink.CustomBulkProcessor.class); + MockedStatic entityMock = mockStatic(Entity.class)) { + ElasticSearchBulkSink sink = new ElasticSearchBulkSink(searchRepository, 10, 2, 1000L); + ElasticSearchBulkSink.CustomBulkProcessor processor = + processorConstruction.constructed().getFirst(); + entityMock.when(Entity::getSearchRepository).thenReturn(searchRepository); + entityMock.when(() -> Entity.getEntityTypeFromObject(entity)).thenReturn(ENTITY_TYPE); + entityMock.when(() -> Entity.isVectorEmbeddable(entity)).thenReturn(true); + entityMock + .when(() -> Entity.buildSearchIndex(ENTITY_TYPE, entity)) + .thenReturn(new StubSearchIndex(Map.of("name", "orders"))); + + invokePrivate( + sink, + "addEntity", + new Class[] { + EntityInterface.class, + String.class, + ReindexContext.class, + StageStatsTracker.class, + boolean.class, + Map.class, + Map.class, + boolean.class, + Map.class + }, + entity, + "table_index", + recreate, + null, + true, + Map.of(entityId.toString(), storedEmbedding), + Map.of(), + false, + Map.of()); + + ArgumentCaptor operationCaptor = ArgumentCaptor.forClass(BulkOperation.class); + verify(processor) + .add( + operationCaptor.capture(), + eq(entityId.toString()), + eq(ENTITY_TYPE), + isNull(), + anyLong()); + Map indexed = + EsUtils.jsonDataToMap((JsonData) operationCaptor.getValue().index().document()); + assertEquals("orders", indexed.get("name")); + assertEquals("fp", indexed.get("fingerprint")); + assertEquals(List.of(0.1, 0.2, 0.3), indexed.get("embedding")); + verify(vectorService).backfillEntityChunks(entity, "data_asset_embeddings_chunks_g1"); + assertEquals(1, sink.getVectorStats().getSuccessRecords()); + } + } + @Test void relationshipPartialUpdateUsesFullDocumentUpsertWithoutRewritingOtherFields() throws Exception { @@ -567,31 +635,6 @@ void flushAndCloseDelegateToProcessorAndPreserveInterrupts() throws Exception { } } - @Test - void isVectorEmbeddingEnabledForEntityReturnsFalseWhenIndexMappingMissing() { - try (MockedConstruction ignored = - mockConstruction(ElasticSearchBulkSink.CustomBulkProcessor.class); - MockedStatic - vectorServiceMock = - mockStatic( - org.openmetadata.service.search.vector.ElasticSearchVectorService.class)) { - vectorServiceMock - .when(org.openmetadata.service.search.vector.ElasticSearchVectorService::getInstance) - .thenReturn( - mock(org.openmetadata.service.search.vector.ElasticSearchVectorService.class)); - when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); - - ElasticSearchBulkSink sink = new ElasticSearchBulkSink(searchRepository, 10, 2, 1000L); - - // table is vector-indexable AND has mapping → enabled - assertTrue(sink.isVectorEmbeddingEnabledForEntity("table")); - - // mapping unloaded → disabled, even when everything else says yes - when(searchRepository.getIndexMapping("table")).thenReturn(null); - assertFalse(sink.isVectorEmbeddingEnabledForEntity("table")); - } - } - @Test void settersUpdateConfigurationAndForwardFailureCallbacks() { try (MockedConstruction processorConstruction = @@ -704,132 +747,6 @@ void addEntityFallsBackToEmptyContextWhenEntityNotInMap() throws Exception { } } - @Test - void enrichWithEmbeddingReusesCachedFieldsWhenServiceReportsMatch() throws Exception { - // P1 guard: on an incremental reindex the doc is re-indexed via a full index op, so a - // state-matched entity must carry its cached embedding spliced back in — never embedding-less - // (which would wipe the stored vector). Mirrors the OpenSearch sink test. - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - ElasticSearchVectorService vectorService = mock(ElasticSearchVectorService.class); - ObjectMapper mapper = new ObjectMapper(); - JsonNode cached = - mapper.readTree( - "{\"fingerprint\":\"fp\",\"embedding\":[0.1,0.2,0.3],\"textToEmbed\":\"cached\"}"); - Map existingEmbeddingsById = Map.of(entityId.toString(), cached); - - try (MockedConstruction ignored = - mockConstruction(ElasticSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(ElasticSearchVectorService.class)) { - vectorServiceMock.when(ElasticSearchVectorService::getInstance).thenReturn(vectorService); - ElasticSearchBulkSink sink = new ElasticSearchBulkSink(searchRepository, 10, 2, 1000L); - - String result = - (String) - invokePrivate( - sink, - "enrichWithEmbedding", - new Class[] { - EntityInterface.class, String.class, Map.class, StageStatsTracker.class - }, - entity, - "{\"name\":\"my-table\"}", - existingEmbeddingsById, - tracker); - - verify(vectorService, never()).generateEmbeddingFields(any()); - verify(tracker).recordVector(StatsResult.SUCCESS); - JsonNode doc = mapper.readTree(result); - assertEquals("my-table", doc.get("name").asText()); - assertEquals("fp", doc.get("fingerprint").asText()); - assertTrue(doc.get("embedding").isArray()); - } - } - - @Test - void enrichWithEmbeddingRecomputesWhenNoCachedEntryAvailable() throws Exception { - EntityInterface entity = mock(EntityInterface.class); - when(entity.getId()).thenReturn(UUID.randomUUID()); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - ElasticSearchVectorService vectorService = mock(ElasticSearchVectorService.class); - when(vectorService.generateEmbeddingFields(entity)) - .thenReturn(Map.of("fingerprint", "fp-new", "embedding", List.of(0.9, 0.8))); - - try (MockedConstruction ignored = - mockConstruction(ElasticSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(ElasticSearchVectorService.class)) { - vectorServiceMock.when(ElasticSearchVectorService::getInstance).thenReturn(vectorService); - ElasticSearchBulkSink sink = new ElasticSearchBulkSink(searchRepository, 10, 2, 1000L); - - String result = - (String) - invokePrivate( - sink, - "enrichWithEmbedding", - new Class[] { - EntityInterface.class, String.class, Map.class, StageStatsTracker.class - }, - entity, - "{\"name\":\"t\"}", - Collections.emptyMap(), - tracker); - - verify(vectorService).generateEmbeddingFields(entity); - assertEquals("fp-new", new ObjectMapper().readTree(result).get("fingerprint").asText()); - } - } - - @Test - void enrichWithEmbeddingRecomputesWhenCachedDimensionMismatchesClient() throws Exception { - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - EmbeddingClient embeddingClient = mock(EmbeddingClient.class); - when(embeddingClient.getDimension()).thenReturn(384); - ElasticSearchVectorService vectorService = mock(ElasticSearchVectorService.class); - when(vectorService.getEmbeddingClient()).thenReturn(embeddingClient); - when(vectorService.generateEmbeddingFields(entity)) - .thenReturn(Map.of("fingerprint", "fp-new", "embedding", List.of(0.1, 0.2, 0.3))); - JsonNode cached = - new ObjectMapper().readTree("{\"fingerprint\":\"fp\",\"embedding\":[0.1,0.2,0.3]}"); - - try (MockedConstruction ignored = - mockConstruction(ElasticSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(ElasticSearchVectorService.class)) { - vectorServiceMock.when(ElasticSearchVectorService::getInstance).thenReturn(vectorService); - ElasticSearchBulkSink sink = new ElasticSearchBulkSink(searchRepository, 10, 2, 1000L); - - invokePrivate( - sink, - "enrichWithEmbedding", - new Class[] {EntityInterface.class, String.class, Map.class, StageStatsTracker.class}, - entity, - "{\"name\":\"z\"}", - Map.of(entityId.toString(), cached), - tracker); - - verify(vectorService).generateEmbeddingFields(entity); - } - } - private Object invokePrivate( Object target, String methodName, Class[] parameterTypes, Object... args) throws Exception { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkSimpleTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkSimpleTest.java index d2bd94569d1b..eeb86f8c76b4 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkSimpleTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkSimpleTest.java @@ -117,13 +117,6 @@ void testContextDataHandling() { assertEquals(false, recreateIndex); } - @Test - void testIsVectorEmbeddingEnabledForEntity() { - assertEquals(false, elasticSearchBulkSink.isVectorEmbeddingEnabledForEntity("table")); - assertEquals(false, elasticSearchBulkSink.isVectorEmbeddingEnabledForEntity("user")); - assertEquals(false, elasticSearchBulkSink.isVectorEmbeddingEnabledForEntity("dashboard")); - } - /** * Mirror of {@code OpenSearchBulkSinkSimpleTest#semaphoreTimeoutRecordsPermanentFailure...}. * The Elasticsearch sink shares the leaked-future failure mode — without the bounded diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingEnricherTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingEnricherTest.java new file mode 100644 index 000000000000..1c6814e66481 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/EmbeddingEnricherTest.java @@ -0,0 +1,539 @@ +package org.openmetadata.service.apps.bundles.searchIndex; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.system.StepStats; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.search.IndexMapping; +import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.bundles.searchIndex.stats.StageStatsTracker; +import org.openmetadata.service.apps.bundles.searchIndex.stats.StatsResult; +import org.openmetadata.service.search.ReindexContext; +import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.vector.VectorDocBuilder; +import org.openmetadata.service.search.vector.VectorIndexService; +import org.openmetadata.service.search.vector.client.EmbeddingClient; +import org.slf4j.LoggerFactory; + +class EmbeddingEnricherTest { + private static final String INDEX = "table_search_index"; + private static final String ORIGINAL_INDEX = "table_search_index_rebuild_1"; + private static final String STAGED_INDEX = INDEX + "_staged"; + private static final String STAGED_CHUNKS = "data_asset_embeddings_chunks_g1700000000000"; + private static final String ENTITY_JSON = "{\"name\":\"orders\"}"; + + private final SearchRepository searchRepository = mock(SearchRepository.class); + private final VectorIndexService vectorService = mock(VectorIndexService.class); + private final StageStatsTracker tracker = mock(StageStatsTracker.class); + private final ThreeDimensionalEmbeddings embeddings = new ThreeDimensionalEmbeddings(); + private final EmbeddingEnricher enricher = new EmbeddingEnricher(searchRepository); + private final Table table = + new Table() + .withId(UUID.randomUUID()) + .withName("orders") + .withFullyQualifiedName("svc.db.schema.orders") + .withDescription("Orders placed online") + .withUpdatedAt(1_700_000_000_000L); + private final String tableId = table.getId().toString(); + private MockedStatic entities; + + @BeforeAll + static void tablesHaveAnEntityType() { + EntityInterface.CANONICAL_ENTITY_NAME_MAP.put("table", Entity.TABLE); + } + + // Whether one entity may be embedded is its repository's decision. No repository is registered + // here, and one left registered by another test class must not decide it either. + @BeforeEach + void theTableMayBeEmbedded() { + entities = mockStatic(Entity.class); + entities.when(() -> Entity.isVectorEmbeddable(table)).thenReturn(true); + } + + @AfterEach + void releaseTheEntityRegistry() { + entities.close(); + } + + @BeforeEach + void semanticSearchIsOn() { + when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); + when(searchRepository.getIndexMapping(Entity.TABLE)) + .thenReturn(IndexMapping.builder().indexName(INDEX).build()); + when(vectorService.getEmbeddingClient()).thenReturn(embeddings); + when(vectorService.backfillEntityChunks(any(), any())).thenReturn(true); + when(vectorService.writeEntityChunks(any(), any(), any())).thenReturn(true); + when(vectorService.writeEntityEmbedding(any(), any(), any())).thenReturn(true); + } + + @Test + void embeddingAppliesToAnIndexableTypeWithAMappingOnceTheVectorServiceExists() { + assertTrue(enricher.isEnabledFor(Entity.TABLE)); + assertFalse(enricher.isEnabledFor(Entity.USER), "users are not vector-indexable"); + + when(searchRepository.getIndexMapping(Entity.TABLE)).thenReturn(null); + assertFalse(enricher.isEnabledFor(Entity.TABLE), "no index mapping"); + + when(searchRepository.getIndexMapping(Entity.TABLE)) + .thenReturn(IndexMapping.builder().indexName(INDEX).build()); + when(searchRepository.getVectorIndexService()).thenReturn(null); + assertFalse(enricher.isEnabledFor(Entity.TABLE), "no vector service on either engine"); + } + + @Test + void aRecreateReadsStoredEmbeddingsFromTheIndexItReplaces() { + JsonNode stored = storedEmbedding("[0.5,0.6,0.7]"); + when(vectorService.getExistingEmbeddingsBatch(eq(ORIGINAL_INDEX), any())) + .thenReturn(Map.of(tableId, stored)); + + Map reusable = + enricher.reusableEmbeddings(List.of(table), INDEX, recreateOf(Entity.TABLE)); + + assertEquals(Map.of(tableId, stored), reusable); + assertEquals( + VectorDocBuilder.computeFingerprintForEntity(table), + currentFingerprintsSentFor(ORIGINAL_INDEX).get(tableId).get()); + } + + @Test + void aRunThatRecreatesNothingReadsStoredEmbeddingsFromTheIndexItWrites() { + JsonNode stored = storedEmbedding("[0.5,0.6,0.7]"); + when(vectorService.getExistingEmbeddingsBatch(eq(INDEX), any())) + .thenReturn(Map.of(tableId, stored)); + + assertEquals(Map.of(tableId, stored), enricher.reusableEmbeddings(List.of(table), INDEX, null)); + } + + @Test + void aCurrentStoredEmbeddingIsSplicedAndItsChunksBackfilledIntoTheStagedGeneration() + throws Exception { + JsonNode stored = storedEmbedding("[0.5,0.6,0.7]"); + + String enriched = + enricher.enrich(table, ENTITY_JSON, Map.of(tableId, stored), tracker, recreateRun()); + + assertEquals( + JsonUtils.readTree( + "{\"name\":\"orders\",\"fingerprint\":\"fp-stored\",\"embedding\":[0.5,0.6,0.7]," + + "\"textToEmbed\":\"stored text\",\"chunkIndex\":0,\"chunkCount\":1," + + "\"parentId\":\"" + + tableId + + "\"}"), + JsonUtils.readTree(enriched)); + verify(vectorService).backfillEntityChunks(table, STAGED_CHUNKS); + verify(vectorService, never()).writeEntityChunks(any(), any(), any()); + assertEquals(0, embeddings.calls.get(), "a reused embedding costs no provider call"); + assertVectorStats(1, 0); + verify(tracker).recordVector(StatsResult.SUCCESS); + } + + @Test + void anEntityWithoutAStoredEmbeddingIsEmbeddedAndItsChunksWrittenToTheLiveIndex() + throws Exception { + String enriched = enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, liveRun()); + + JsonNode doc = JsonUtils.readTree(enriched); + assertEquals("orders", doc.path("name").asText()); + assertEquals("[0.1,0.2,0.3]", doc.path("embedding").toString()); + assertEquals( + VectorDocBuilder.computeFingerprintForEntity(table), doc.path("fingerprint").asText()); + assertEquals(tableId, doc.path("parentId").asText()); + Map chunk = chunksWrittenTo(null).getFirst(); + assertEquals(0, chunk.get("chunkIndex")); + assertEquals(tableId, chunk.get("parentId")); + verify(vectorService, never()).backfillEntityChunks(any(), any()); + assertVectorStats(1, 0); + } + + @Test + void aStoredEmbeddingOfAnotherDimensionIsRecomputed() throws Exception { + JsonNode twoDimensional = storedEmbedding("[0.5,0.6]"); + + String enriched = + enricher.enrich( + table, ENTITY_JSON, Map.of(tableId, twoDimensional), tracker, recreateRun()); + + assertEquals("[0.1,0.2,0.3]", JsonUtils.readTree(enriched).path("embedding").toString()); + assertEquals(1, chunksWrittenTo(STAGED_CHUNKS).size()); + verify(vectorService, never()).backfillEntityChunks(any(), any()); + } + + @Test + void aFreshEmbedTheProviderFailsIsRetriedAndWritesTheEntityEmbeddingAndChunks() { + embeddings.failuresLeft = 1; + theRetryReadsTheTable(); + + String enriched = enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, recreateRun()); + + assertEquals(JsonUtils.readTree(ENTITY_JSON), JsonUtils.readTree(enriched)); + verify(vectorService, never()).writeEntityChunks(any(), any(), any()); + assertVectorStats(0, 0); + enricher.retryMissedChunks(tracker); + + Map written = entityEmbeddingWrittenTo(STAGED_INDEX); + assertEquals(VectorDocBuilder.computeFingerprintForEntity(table), written.get("fingerprint")); + assertTrue(written.containsKey("embedding"), "the entity document gets its embedding"); + Map chunk = chunksWrittenTo(STAGED_CHUNKS).getFirst(); + assertEquals(VectorDocBuilder.legacyEmbeddingFields(chunk), written); + verify(vectorService, never()).backfillEntityChunks(any(), any()); + assertVectorStats(1, 0); + verify(tracker).recordVector(StatsResult.SUCCESS); + verify(tracker, never()).recordVector(StatsResult.FAILED); + } + + @Test + void aFreshEmbedRetriedOnALiveRunWritesToTheLiveIndexes() { + embeddings.failuresLeft = 1; + theRetryReadsTheTable(); + + enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, liveRun()); + enricher.retryMissedChunks(tracker); + + entityEmbeddingWrittenTo(INDEX); + assertEquals(1, chunksWrittenTo(null).size()); + assertVectorStats(1, 0); + } + + @Test + void aFreshEmbedThatFailsAgainCountsOneFailureAndWritesNothing() { + embeddings.failuresLeft = Integer.MAX_VALUE; + theRetryReadsTheTable(); + + enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, recreateRun()); + enricher.retryMissedChunks(tracker); + enricher.retryMissedChunks(tracker); + + assertEquals(2, embeddings.calls.get(), "one first attempt and one retry"); + verify(vectorService, never()).writeEntityEmbedding(any(), any(), any()); + verify(vectorService, never()).writeEntityChunks(any(), any(), any()); + assertVectorStats(0, 1); + verify(tracker).recordVector(StatsResult.FAILED); + } + + @Test + void aRetryThatCannotWriteTheChunksStillWritesTheEntityEmbeddingAndCountsAFailure() { + embeddings.failuresLeft = 1; + when(vectorService.writeEntityChunks(any(), any(), any())).thenReturn(false); + theRetryReadsTheTable(); + + enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, recreateRun()); + enricher.retryMissedChunks(tracker); + + entityEmbeddingWrittenTo(STAGED_INDEX); + assertVectorStats(0, 1); + } + + @Test + void anOpenCircuitOnTheFreshPathMakesNoCallAndCountsTheMissOnceAfterTheSkippedRetry() { + embeddings.available = false; + theRetryReadsTheTable(); + + String enriched = enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, recreateRun()); + assertVectorStats(0, 0); + enricher.retryMissedChunks(tracker); + + assertEquals(ENTITY_JSON, enriched); + assertEquals(0, embeddings.calls.get(), "no provider call while the circuit is open"); + verify(vectorService, never()).writeEntityEmbedding(any(), any(), any()); + verify(vectorService, never()).writeEntityChunks(any(), any(), any()); + assertVectorStats(0, 1); + verify(tracker).recordVector(StatsResult.FAILED); + } + + @Test + void freshEmbedMissesLogOneSummaryWarningAndNoStackTracePerEntity() { + ListAppender log = captureLogsOf(EmbeddingEnricher.class, MissedChunks.class); + Table other = + new Table() + .withId(UUID.randomUUID()) + .withName("refunds") + .withFullyQualifiedName("svc.db.schema.refunds") + .withDescription("Refunds"); + entities.when(() -> Entity.isVectorEmbeddable(other)).thenReturn(true); + embeddings.failuresLeft = 2; + theRetryReadsTheTable(); + + enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, recreateRun()); + enricher.enrich(other, ENTITY_JSON, Map.of(), tracker, recreateRun()); + assertTrue(atLeast(log, Level.WARN).isEmpty(), "no warning per entity"); + enricher.retryMissedChunks(tracker); + enricher.logMissedChunksSummary(); + + List warnings = atLeast(log, Level.WARN); + assertEquals(1, warnings.size()); + assertTrue( + warnings + .getFirst() + .getFormattedMessage() + .startsWith( + "Search Indexing missed the chunk " + + "documents of 2 entities on this node, 2 of them with their entity embedding too; " + + "the retry recovered 2.")); + assertTrue(log.list.stream().allMatch(event -> event.getThrowableProxy() == null)); + } + + @Test + void aMissedChunkWriteIsRetriedOnceAndCountsOneSuccessWhenItRecovers() { + when(vectorService.backfillEntityChunks(table, STAGED_CHUNKS)).thenReturn(false, true); + theRetryReadsTheTable(); + + enricher.enrich( + table, + ENTITY_JSON, + Map.of(tableId, storedEmbedding("[0.5,0.6,0.7]")), + tracker, + recreateRun()); + assertVectorStats(0, 0); + enricher.retryMissedChunks(tracker); + enricher.retryMissedChunks(tracker); + + verify(vectorService, times(2)).backfillEntityChunks(table, STAGED_CHUNKS); + assertVectorStats(1, 0); + verify(tracker).recordVector(StatsResult.SUCCESS); + verify(tracker).flush(); + } + + @Test + void aChunkWriteThatStillMissesAfterTheRetryCountsOneFailure() { + when(vectorService.writeEntityChunks(any(), any(), any())).thenReturn(false); + when(vectorService.backfillEntityChunks(table, STAGED_CHUNKS)).thenReturn(false); + theRetryReadsTheTable(); + + enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, recreateRun()); + enricher.retryMissedChunks(tracker); + + verify(vectorService).backfillEntityChunks(table, STAGED_CHUNKS); + assertVectorStats(0, 1); + verify(tracker).recordVector(StatsResult.FAILED); + } + + @Test + void anOpenCircuitSkipsTheRetryAndCountsAFailure() { + when(vectorService.backfillEntityChunks(table, STAGED_CHUNKS)).thenReturn(false); + theRetryReadsTheTable(); + + enricher.enrich( + table, + ENTITY_JSON, + Map.of(tableId, storedEmbedding("[0.5,0.6,0.7]")), + tracker, + recreateRun()); + embeddings.available = false; + enricher.retryMissedChunks(tracker); + + verify(vectorService, times(1)).backfillEntityChunks(table, STAGED_CHUNKS); + assertEquals(0, embeddings.calls.get(), "no provider call while the circuit is open"); + assertVectorStats(0, 1); + } + + @Test + void aRetryLeavesTheMissesOfAnotherPartitionOfTheSameTypePending() { + StageStatsTracker otherPartition = mock(StageStatsTracker.class); + embeddings.failuresLeft = 1; + theRetryReadsTheTable(); + + enricher.enrich(table, ENTITY_JSON, Map.of(), tracker, recreateRun()); + enricher.retryMissedChunks(otherPartition); + + assertEquals( + 1, embeddings.calls.get(), "the other partition's document may not be written yet"); + verify(vectorService, never()).writeEntityEmbedding(any(), any(), any()); + verifyNoInteractions(otherPartition); + assertVectorStats(0, 0); + + enricher.retryMissedChunks(tracker); + + entityEmbeddingWrittenTo(STAGED_INDEX); + assertVectorStats(1, 0); + } + + private void theRetryReadsTheTable() { + entities + .when(() -> Entity.getEntity(any(EntityReference.class), eq("*"), eq(Include.NON_DELETED))) + .thenReturn(table); + } + + @Test + void anEntityThatOptsOutOfEmbeddingIsLeftUntouched() { + entities.when(() -> Entity.isVectorEmbeddable(table)).thenReturn(false); + + String enriched = + enricher.enrich( + table, + ENTITY_JSON, + Map.of(tableId, storedEmbedding("[0.5,0.6,0.7]")), + tracker, + liveRun()); + + assertSame(ENTITY_JSON, enriched); + verify(vectorService, never()).backfillEntityChunks(any(), any()); + verify(vectorService, never()).writeEntityChunks(any(), any(), any()); + assertVectorStats(0, 0); + verifyNoInteractions(tracker); + } + + @Test + void aReusedEmbeddingOfANonRecreateRunIsSplicedAndBackfilledToTheLiveIndex() { + String enriched = + enricher.enrich( + table, + ENTITY_JSON, + Map.of(tableId, storedEmbedding("[0.5,0.6,0.7]")), + tracker, + liveRun()); + + JsonNode doc = JsonUtils.readTree(enriched); + assertEquals("fp-stored", doc.path("fingerprint").asText()); + assertEquals("[0.5,0.6,0.7]", doc.path("embedding").toString()); + verify(vectorService).backfillEntityChunks(table, null); + assertVectorStats(1, 0); + } + + private void assertVectorStats(int succeeded, int failed) { + StepStats stats = enricher.stats(); + assertEquals(succeeded, stats.getSuccessRecords()); + assertEquals(failed, stats.getFailedRecords()); + assertEquals(succeeded + failed, stats.getTotalRecords()); + } + + /** A stored entity-doc embedding as the vector service returns it for reuse. */ + private JsonNode storedEmbedding(String vector) { + return JsonUtils.readTree( + "{\"fingerprint\":\"fp-stored\",\"embedding\":" + + vector + + ",\"textToEmbed\":\"stored text\",\"chunkIndex\":0,\"chunkCount\":1," + + "\"parentId\":\"" + + tableId + + "\"}"); + } + + private static EmbeddingTargets liveRun() { + return EmbeddingTargets.of(INDEX, null); + } + + private static EmbeddingTargets recreateRun() { + return EmbeddingTargets.of(STAGED_INDEX, recreateOf(Entity.TABLE)); + } + + @SuppressWarnings("unchecked") + private Map entityEmbeddingWrittenTo(String entityIndex) { + ArgumentCaptor> written = ArgumentCaptor.forClass(Map.class); + verify(vectorService).writeEntityEmbedding(eq(entityIndex), eq(tableId), written.capture()); + return written.getValue(); + } + + private final List capturedLoggers = new ArrayList<>(); + private final ListAppender capturedLog = new ListAppender<>(); + + private ListAppender captureLogsOf(Class... owners) { + capturedLog.start(); + for (Class owner : owners) { + Logger logger = (Logger) LoggerFactory.getLogger(owner); + logger.addAppender(capturedLog); + capturedLoggers.add(logger); + } + return capturedLog; + } + + @AfterEach + void releaseCapturedLogs() { + capturedLoggers.forEach(logger -> logger.detachAppender(capturedLog)); + } + + private static List atLeast(ListAppender log, Level level) { + return log.list.stream().filter(event -> event.getLevel().isGreaterOrEqual(level)).toList(); + } + + /** A full recreate: it replaces {@code entityType}'s index and stages a chunk generation. */ + private static ReindexContext recreateOf(String entityType) { + ReindexContext context = new ReindexContext(); + context.add(entityType, INDEX, ORIGINAL_INDEX, INDEX + "_staged", Set.of(), INDEX, List.of()); + context.setStagedChunkIndex(STAGED_CHUNKS); + return context; + } + + @SuppressWarnings("unchecked") + private Map> currentFingerprintsSentFor(String indexName) { + ArgumentCaptor>> sent = ArgumentCaptor.forClass(Map.class); + verify(vectorService).getExistingEmbeddingsBatch(eq(indexName), sent.capture()); + return sent.getValue(); + } + + @SuppressWarnings("unchecked") + private List> chunksWrittenTo(String stagedChunkTarget) { + ArgumentCaptor>> written = ArgumentCaptor.forClass(List.class); + verify(vectorService) + .writeEntityChunks( + eq(tableId), + written.capture(), + stagedChunkTarget == null ? isNull() : eq(stagedChunkTarget)); + return written.getValue(); + } + + private static final class ThreeDimensionalEmbeddings extends EmbeddingClient { + private final AtomicInteger calls = new AtomicInteger(); + private boolean available = true; + private int failuresLeft; + + @Override + protected float[] doEmbed(String text) { + calls.incrementAndGet(); + if (failuresLeft > 0) { + failuresLeft--; + throw new IllegalStateException("OpenAI API returned status 429: injected"); + } + return new float[] {0.1f, 0.2f, 0.3f}; + } + + @Override + public boolean isAvailable() { + return available; + } + + @Override + public int getDimension() { + return 3; + } + + @Override + public String getModelId() { + return "three-dimensional"; + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java index a764d893353d..ad729a4711b1 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java @@ -51,8 +51,7 @@ import org.openmetadata.service.search.indexes.SearchIndex; import org.openmetadata.service.search.opensearch.OpenSearchClient; import org.openmetadata.service.search.opensearch.OsUtils; -import org.openmetadata.service.search.vector.OpenSearchVectorService; -import org.openmetadata.service.search.vector.VectorDocBuilder; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.search.vector.client.EmbeddingClient; import os.org.opensearch.client.json.JsonData; import os.org.opensearch.client.opensearch._types.Script; @@ -191,17 +190,15 @@ void relationshipPartialUpdateUsesVectorEnrichedFullUpsertWithoutRewritingOtherF + "\"chunkIndex\":0,\"chunkCount\":1,\"parentId\":\"" + entityId + "\"}"); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); + VectorIndexService vectorService = mock(VectorIndexService.class); EmbeddingClient embeddingClient = mock(EmbeddingClient.class); when(vectorService.getEmbeddingClient()).thenReturn(embeddingClient); when(embeddingClient.getDimension()).thenReturn(2); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); try (MockedConstruction processorConstruction = mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); - MockedStatic entityMock = mockStatic(Entity.class); - MockedStatic vectorServiceMock = - mockStatic(OpenSearchVectorService.class)) { - vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); + MockedStatic entityMock = mockStatic(Entity.class)) { OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 2000L); OpenSearchBulkSink.CustomBulkProcessor processor = processorConstruction.constructed().getFirst(); @@ -646,66 +643,6 @@ void addEntityLooksUpEntityContextFromMap() throws Exception { } } - @Test - void enrichWithEmbeddingReusesCachedFieldsWhenServiceReportsMatch() throws Exception { - // The service-layer two-step fetch already pre-filters to fingerprint matches; if an entry is - // present in the map, the splice path is taken without any further fingerprint check. - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode cached = - mapper.readTree( - "{\"fingerprint\":\"fp-unchanged\",\"embedding\":[0.1,0.2,0.3]," - + "\"textToEmbed\":\"cached-text\",\"textToLLMContext\":\"cached-ctx\"," - + "\"chunkIndex\":0,\"chunkCount\":1,\"parentId\":\"" - + entityId - + "\"}"); - Map existingEmbeddingsById = Map.of(entityId.toString(), cached); - - String entityJson = "{\"name\":\"my-table\",\"description\":\"desc\"}"; - - try (MockedConstruction processorConstruction = - mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(OpenSearchVectorService.class)) { - vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); - - OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 1000L); - - Method enrich = - OpenSearchBulkSink.class.getDeclaredMethod( - "enrichWithEmbedding", - EntityInterface.class, - String.class, - Map.class, - StageStatsTracker.class, - String.class); - enrich.setAccessible(true); - String result = - (String) enrich.invoke(sink, entity, entityJson, existingEmbeddingsById, tracker, null); - - verify(vectorService, never()).generateEmbeddingFields(any()); - verify(tracker).recordVector(StatsResult.SUCCESS); - - JsonNode resultNode = mapper.readTree(result); - assertEquals("my-table", resultNode.get("name").asText()); - assertEquals("fp-unchanged", resultNode.get("fingerprint").asText()); - JsonNode embedding = resultNode.get("embedding"); - assertNotNull(embedding); - assertTrue(embedding.isArray()); - assertEquals(3, embedding.size()); - assertEquals("cached-text", resultNode.get("textToEmbed").asText()); - } - } - @Test void addEntityFallsBackToEmptyContextWhenEntityNotInMap() throws Exception { EntityInterface entity = mock(EntityInterface.class); @@ -748,328 +685,6 @@ void addEntityFallsBackToEmptyContextWhenEntityNotInMap() throws Exception { } } - /** - * Stubs the recompute (non-cached) embedding path introduced with multi-chunk indexing: the sink - * builds chunk docs once via {@link VectorDocBuilder#fromEntity}, splices chunk 0's legacy - * embedding fields into the staged doc, and writes the chunks. Returns the chunk-doc list so the - * caller can verify {@code writeEntityChunks} received it. - */ - private static List> stubRecompute( - MockedStatic docBuilderMock, - MockedStatic vectorServiceMock, - EntityInterface entity, - String fingerprint, - List embedding, - String textToEmbed) { - Map chunk0 = new HashMap<>(); - chunk0.put("fingerprint", fingerprint); - chunk0.put("embedding", embedding); - chunk0.put("textToEmbed", textToEmbed); - chunk0.put("chunkIndex", 0); - chunk0.put("chunkCount", 1); - List> chunkDocs = List.of(chunk0); - Map legacyFields = new HashMap<>(); - legacyFields.put("fingerprint", fingerprint); - legacyFields.put("embedding", embedding); - legacyFields.put("textToEmbed", textToEmbed); - docBuilderMock.when(() -> VectorDocBuilder.fromEntity(eq(entity), any())).thenReturn(chunkDocs); - vectorServiceMock - .when(() -> OpenSearchVectorService.legacyEmbeddingFields(chunk0)) - .thenReturn(legacyFields); - return chunkDocs; - } - - private static EmbeddingClient availableClient() { - EmbeddingClient client = mock(EmbeddingClient.class); - when(client.isAvailable()).thenReturn(true); - return client; - } - - @Test - void enrichWithEmbeddingRecomputesWhenNoCachedEntryAvailable() throws Exception { - // When the service-layer fetch returns nothing for this entity (cache miss or fingerprint - // mismatch filtered upstream), the call site must regenerate embeddings. - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); - EmbeddingClient embeddingClient = availableClient(); - when(vectorService.getEmbeddingClient()).thenReturn(embeddingClient); - - Map existingEmbeddingsById = Collections.emptyMap(); - String entityJson = "{\"name\":\"my-table\"}"; - - try (MockedConstruction processorConstruction = - mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic docBuilderMock = mockStatic(VectorDocBuilder.class)) { - vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); - List> chunkDocs = - stubRecompute( - docBuilderMock, - vectorServiceMock, - entity, - "fp-new", - List.of(0.9, 0.8, 0.7), - "fresh-text"); - - OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 1000L); - - Method enrich = - OpenSearchBulkSink.class.getDeclaredMethod( - "enrichWithEmbedding", - EntityInterface.class, - String.class, - Map.class, - StageStatsTracker.class, - String.class); - enrich.setAccessible(true); - String result = - (String) enrich.invoke(sink, entity, entityJson, existingEmbeddingsById, tracker, null); - - verify(vectorService).writeEntityChunks(entityId.toString(), chunkDocs, null); - verify(tracker).recordVector(StatsResult.SUCCESS); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode resultNode = mapper.readTree(result); - assertEquals("fp-new", resultNode.get("fingerprint").asText()); - assertEquals("fresh-text", resultNode.get("textToEmbed").asText()); - } - } - - @Test - void enrichWithEmbeddingRecomputesWhenCachedEntryHasNoEmbedding() throws Exception { - // Defensive: even if the service layer ever admits an entry without an embedding (e.g. a doc - // indexed before embeddings were enabled), the splice site must not blindly trust it. - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); - EmbeddingClient embeddingClient = availableClient(); - when(vectorService.getEmbeddingClient()).thenReturn(embeddingClient); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode cachedWithoutEmbedding = mapper.readTree("{\"fingerprint\":\"fp-old\"}"); - Map existingEmbeddingsById = - Map.of(entityId.toString(), cachedWithoutEmbedding); - - try (MockedConstruction processorConstruction = - mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic docBuilderMock = mockStatic(VectorDocBuilder.class)) { - vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); - List> chunkDocs = - stubRecompute( - docBuilderMock, vectorServiceMock, entity, "fp-new", List.of(0.1, 0.2, 0.3), "text"); - - OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 1000L); - Method enrich = - OpenSearchBulkSink.class.getDeclaredMethod( - "enrichWithEmbedding", - EntityInterface.class, - String.class, - Map.class, - StageStatsTracker.class, - String.class); - enrich.setAccessible(true); - - String result = - (String) - enrich.invoke( - sink, entity, "{\"name\":\"x\"}", existingEmbeddingsById, tracker, null); - - verify(vectorService).writeEntityChunks(entityId.toString(), chunkDocs, null); - verify(tracker).recordVector(StatsResult.SUCCESS); - assertEquals("fp-new", mapper.readTree(result).get("fingerprint").asText()); - } - } - - @Test - void enrichWithEmbeddingRecomputesWhenCachedNodeIsNotAnObject() throws Exception { - // Defensive: a malformed _source (array or scalar instead of object) must not crash the splice - // path; we fall through to regeneration. - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); - EmbeddingClient embeddingClient = availableClient(); - when(vectorService.getEmbeddingClient()).thenReturn(embeddingClient); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode arrayInsteadOfObject = mapper.readTree("[1,2,3]"); - Map existingEmbeddingsById = - Map.of(entityId.toString(), arrayInsteadOfObject); - - try (MockedConstruction processorConstruction = - mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic docBuilderMock = mockStatic(VectorDocBuilder.class)) { - vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); - List> chunkDocs = - stubRecompute( - docBuilderMock, vectorServiceMock, entity, "fp-new", List.of(0.4, 0.5, 0.6), "text"); - - OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 1000L); - Method enrich = - OpenSearchBulkSink.class.getDeclaredMethod( - "enrichWithEmbedding", - EntityInterface.class, - String.class, - Map.class, - StageStatsTracker.class, - String.class); - enrich.setAccessible(true); - - String result = - (String) - enrich.invoke( - sink, entity, "{\"name\":\"y\"}", existingEmbeddingsById, tracker, null); - - verify(vectorService).writeEntityChunks(entityId.toString(), chunkDocs, null); - verify(tracker).recordVector(StatsResult.SUCCESS); - assertEquals("fp-new", mapper.readTree(result).get("fingerprint").asText()); - } - } - - @Test - void enrichWithEmbeddingRecomputesWhenCachedDimensionMismatchesClient() throws Exception { - // Reuse is keyed only on entity content (the fingerprint), which does NOT change when - // the embedding model/dimension changes. A cached vector whose length no longer matches the - // active client's dimension must be regenerated — otherwise an old-dimension vector would be - // spliced into a staged index built for the new dimension and silently rejected by the knn - // field. This is the recreate-after-model-change dimension mismatch. - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); - EmbeddingClient embeddingClient = availableClient(); - when(embeddingClient.getDimension()).thenReturn(4); - when(vectorService.getEmbeddingClient()).thenReturn(embeddingClient); - - ObjectMapper mapper = new ObjectMapper(); - // Cached embedding has 3 dims; the active client now reports 4 -> must NOT be reused. - JsonNode staleDimensionCached = - mapper.readTree( - "{\"fingerprint\":\"fp-unchanged\",\"embedding\":[0.1,0.2,0.3],\"parentId\":\"" - + entityId - + "\"}"); - Map existingEmbeddingsById = - Map.of(entityId.toString(), staleDimensionCached); - - try (MockedConstruction processorConstruction = - mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic docBuilderMock = mockStatic(VectorDocBuilder.class)) { - vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); - List> chunkDocs = - stubRecompute( - docBuilderMock, - vectorServiceMock, - entity, - "fp-new", - List.of(0.1, 0.2, 0.3, 0.4), - "text"); - - OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 1000L); - Method enrich = - OpenSearchBulkSink.class.getDeclaredMethod( - "enrichWithEmbedding", - EntityInterface.class, - String.class, - Map.class, - StageStatsTracker.class, - String.class); - enrich.setAccessible(true); - - String result = - (String) - enrich.invoke( - sink, entity, "{\"name\":\"z\"}", existingEmbeddingsById, tracker, null); - - verify(vectorService).writeEntityChunks(entityId.toString(), chunkDocs, null); - verify(tracker).recordVector(StatsResult.SUCCESS); - JsonNode resultNode = mapper.readTree(result); - assertEquals("fp-new", resultNode.get("fingerprint").asText()); - assertEquals(4, resultNode.get("embedding").size()); - } - } - - @Test - void enrichWithEmbeddingSkipsGenerationWhenProviderUnavailable() throws Exception { - // Circuit open (provider unavailable): index the entity without embeddings and count it a - // success, never calling the provider or writing chunks — a transient outage must not fail - // every entity in the reindex. The embedding self-heals on the next run. - EntityInterface entity = mock(EntityInterface.class); - UUID entityId = UUID.randomUUID(); - when(entity.getId()).thenReturn(entityId); - // A real entity always resolves a reference; the bulk sink consults it via - // Entity.isVectorEmbeddable to keep restricted ContextMemory out of the vector index. - when(entity.getEntityReference()).thenReturn(new EntityReference().withType("table")); - - StageStatsTracker tracker = mock(StageStatsTracker.class); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); - EmbeddingClient unavailableClient = mock(EmbeddingClient.class); - when(unavailableClient.isAvailable()).thenReturn(false); - when(vectorService.getEmbeddingClient()).thenReturn(unavailableClient); - - Map existingEmbeddingsById = Collections.emptyMap(); - - try (MockedConstruction processorConstruction = - mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); - MockedStatic vectorServiceMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic docBuilderMock = mockStatic(VectorDocBuilder.class)) { - vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); - - OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 1000L); - Method enrich = - OpenSearchBulkSink.class.getDeclaredMethod( - "enrichWithEmbedding", - EntityInterface.class, - String.class, - Map.class, - StageStatsTracker.class, - String.class); - enrich.setAccessible(true); - - String result = - (String) - enrich.invoke( - sink, entity, "{\"name\":\"my-table\"}", existingEmbeddingsById, tracker, null); - - docBuilderMock.verify(() -> VectorDocBuilder.fromEntity(any(), any()), never()); - verify(vectorService, never()).writeEntityChunks(any(), any(), any()); - verify(tracker).recordVector(StatsResult.SUCCESS); - JsonNode resultNode = new ObjectMapper().readTree(result); - assertEquals("my-table", resultNode.get("name").asText()); - assertFalse(resultNode.has("embedding")); - } - } - private Object invokePrivate( Object target, String methodName, Class[] parameterTypes, Object... args) throws Exception { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipantTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipantTest.java index 9a1f953cb5c6..7118144ad091 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipantTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedJobParticipantTest.java @@ -70,7 +70,7 @@ import org.openmetadata.service.search.ReindexContext; import org.openmetadata.service.search.SearchClusterMetrics; import org.openmetadata.service.search.SearchRepository; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) @@ -1120,7 +1120,8 @@ void testProcessJobPartitionsUsesDefaultBulkSinkSettingsAndHandlesInterruptedWai * mapping under {@link ReindexContext#STAGED_CHUNK_KEY}) into the vector service before it * streams, and clears it in the finally when the run ends — so live edits handled on this * (non-coordinator) JVM mirror into this run's generation instead of relying on lossy - * cluster-state discovery. This wires the OpenSearchVectorService fix end-to-end. + * cluster-state discovery. The vector service is the one the search repository holds, whichever + * engine it runs on. */ @Test void testProcessJobPartitionsLatchesAndClearsTheParticipantStagedChunkTarget() throws Exception { @@ -1151,23 +1152,20 @@ void testProcessJobPartitionsLatchesAndClearsTheParticipantStagedChunkTarget() t .thenReturn(bulkSink); when(bulkSink.flushAndAwait(60)).thenReturn(true); - OpenSearchVectorService vectorServiceMock = mock(OpenSearchVectorService.class); + VectorIndexService vectorServiceMock = mock(VectorIndexService.class); + when(searchRepository.getVectorIndexService()).thenReturn(vectorServiceMock); try (MockedConstruction coordinatorMocked = - mockConstruction( - DistributedSearchIndexCoordinator.class, - (mock, context) -> { - when(mock.getJob(eq(jobId))).thenReturn(Optional.of(runningJob)); - when(mock.claimNextPartition(eq(jobId))).thenReturn(Optional.empty()); - when(mock.getPartitions(eq(jobId), eq(PartitionStatus.PENDING))) - .thenReturn(List.of()); - when(mock.getPartitions(eq(jobId), eq(PartitionStatus.PROCESSING))) - .thenReturn(List.of()); - }); - MockedStatic vectorStatic = - mockStatic(OpenSearchVectorService.class)) { - vectorStatic.when(OpenSearchVectorService::getInstance).thenReturn(vectorServiceMock); - + mockConstruction( + DistributedSearchIndexCoordinator.class, + (mock, context) -> { + when(mock.getJob(eq(jobId))).thenReturn(Optional.of(runningJob)); + when(mock.claimNextPartition(eq(jobId))).thenReturn(Optional.empty()); + when(mock.getPartitions(eq(jobId), eq(PartitionStatus.PENDING))) + .thenReturn(List.of()); + when(mock.getPartitions(eq(jobId), eq(PartitionStatus.PROCESSING))) + .thenReturn(List.of()); + })) { participant = new DistributedJobParticipant( collectionDAO, searchRepository, "test-server-1", testNotifier); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinatorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinatorTest.java index 948a339ec2a8..3619ccd7f927 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinatorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinatorTest.java @@ -42,6 +42,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -66,6 +67,7 @@ import org.openmetadata.service.jdbi3.SearchReindexDAOs.SearchIndexPartitionDAO.EntityStatsRecord; import org.openmetadata.service.jdbi3.SearchReindexDAOs.SearchIndexPartitionDAO.SearchIndexPartitionRecord; import org.openmetadata.service.jdbi3.SearchReindexDAOs.SearchReindexLockDAO; +import org.openmetadata.service.search.vector.VectorIndexService; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) @@ -871,6 +873,124 @@ void testFailPartition_RetryAvailable() { assertEquals(1, retryCaptor.getValue()); // retryCount incremented } + @Test + void aPartitionThatLostAStagedChunkDeleteFailsForGoodAndNoLaterCallRewritesIt() { + AtomicReference row = partitionRowInTheDatabase(); + UUID partitionId = UUID.fromString(row.get().id()); + String lost = VectorIndexService.UNRECORDED_STAGED_DELETE + ": chunks_g1"; + + coordinator.failPartitionWithoutRetry(partitionId, lost); + // No node can claim it for a retry: claims take PENDING rows only. A stray worker that still + // holds it can neither fail it with another error nor complete it. + coordinator.failPartition(partitionId, "read timeout"); + coordinator.completePartition(partitionId, 2, 0, 0); + + assertEquals(PartitionStatus.FAILED.name(), row.get().status()); + assertEquals(lost, row.get().lastError()); + assertEquals(0, row.get().retryCount(), "it never went back to PENDING for a retry"); + } + + @Test + void aRetriedPartitionThatThenLosesAStagedChunkDeleteEndsFailedWithThatError() { + AtomicReference row = partitionRowInTheDatabase(); + UUID partitionId = UUID.fromString(row.get().id()); + String lost = VectorIndexService.UNRECORDED_STAGED_DELETE + ": chunks_g1"; + + coordinator.failPartition(partitionId, "read timeout"); + assertEquals(PartitionStatus.PENDING.name(), row.get().status(), "an ordinary failure retries"); + row.set(withState(row.get(), PartitionStatus.PROCESSING.name(), row.get().lastError(), 1)); + coordinator.failPartitionWithoutRetry(partitionId, lost); + coordinator.completePartition(partitionId, 2, 0, 0); + + assertEquals(PartitionStatus.FAILED.name(), row.get().status()); + assertEquals(lost, row.get().lastError()); + } + + /** One PROCESSING partition row whose guarded updates behave as the database's do. */ + private AtomicReference partitionRowInTheDatabase() { + AtomicReference row = + new AtomicReference<>( + new SearchIndexPartitionRecord( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + "table", + 0, + 0, + 5000, + 5000, + 7500, + 50, + PartitionStatus.PROCESSING.name(), + 2500, + 2500, + 2400, + 100, + TEST_SERVER_ID, + System.currentTimeMillis() - 10000, + System.currentTimeMillis() - 10000, + null, + System.currentTimeMillis() - 1000, + null, + 0, + 0L)); + when(partitionDAO.findById(row.get().id())).thenAnswer(invocation -> row.get()); + when(partitionDAO.updateIfProcessing( + anyString(), + anyString(), + anyLong(), + anyLong(), + anyLong(), + anyLong(), + any(), + any(), + any(), + any(), + anyLong(), + any(), + anyInt())) + .thenAnswer( + invocation -> { + boolean processing = PartitionStatus.PROCESSING.name().equals(row.get().status()); + if (processing) { + row.set( + withState( + row.get(), + invocation.getArgument(1), + invocation.getArgument(11), + invocation.getArgument(12))); + } + return processing ? 1 : 0; + }); + return row; + } + + private static SearchIndexPartitionRecord withState( + SearchIndexPartitionRecord row, String status, String lastError, int retryCount) { + return new SearchIndexPartitionRecord( + row.id(), + row.jobId(), + row.entityType(), + row.partitionIndex(), + row.rangeStart(), + row.rangeEnd(), + row.estimatedCount(), + row.workUnits(), + row.priority(), + status, + row.cursor(), + row.processedCount(), + row.successCount(), + row.failedCount(), + row.assignedServer(), + row.claimedAt(), + row.startedAt(), + row.completedAt(), + row.lastUpdateAt(), + lastError, + retryCount, + row.claimableAt()); + } + @Test void testFailPartition_NoOpWhenAlreadyCancelled() { UUID jobId = UUID.randomUUID(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutorTest.java index 3b4fb3becb8a..487e5ba3d208 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexExecutorTest.java @@ -65,6 +65,7 @@ import org.openmetadata.service.search.RecreateIndexHandler; import org.openmetadata.service.search.ReindexContext; import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.vector.VectorIndexService; class DistributedSearchIndexExecutorTest { @@ -661,6 +662,43 @@ void promoteEntityIndexUsesDefaultAndGenericHandlers() throws Exception { verifyNoMoreInteractions(genericHandler); } + @Test + void aTypeWithAPartitionThatCouldNotRecordAStagedChunkDeleteKeepsTheLiveChunks() + throws Exception { + UUID jobId = UUID.randomUUID(); + ReindexContext stagedIndexContext = mock(ReindexContext.class); + DefaultRecreateHandler defaultHandler = mock(DefaultRecreateHandler.class); + when(stagedIndexContext.getStagedIndex("table")).thenReturn(Optional.of("staged_table")); + when(coordinator.getPartitions(jobId, PartitionStatus.FAILED)) + .thenReturn( + List.of( + SearchIndexPartition.builder() + .entityType("table") + .lastError(VectorIndexService.UNRECORDED_STAGED_DELETE + ": staged g1") + .build(), + SearchIndexPartition.builder() + .entityType("topic") + .lastError("read timeout") + .build())); + setField("currentJob", SearchIndexJob.builder().id(jobId).build()); + setField("stagedIndexContext", stagedIndexContext); + setField("indexPromotionHandler", defaultHandler); + + invokePrivate( + "promoteEntityIndex", new Class[] {String.class, boolean.class}, "table", false); + // The lost delete is read even when the type's run counts as a success, which it does when a + // retry of another partition succeeded after an earlier failure. + invokePrivate( + "promoteEntityIndex", new Class[] {String.class, boolean.class}, "table", true); + + ArgumentCaptor contextCaptor = + ArgumentCaptor.forClass(EntityReindexContext.class); + verify(defaultHandler).promoteEntityIndex(contextCaptor.capture(), eq(false)); + assertTrue(contextCaptor.getValue().isStagedChunkDeleteUnrecorded()); + verify(defaultHandler).promoteEntityIndex(contextCaptor.capture(), eq(true)); + assertTrue(contextCaptor.getValue().isStagedChunkDeleteUnrecorded()); + } + @Test void promoteEntityIndexReturnsWithoutContextAndSwallowsHandlerFailures() throws Exception { invokePrivate( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorkerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorkerTest.java index e9ee8aaa4c74..bce8eafc81d1 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorkerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/PartitionWorkerTest.java @@ -26,9 +26,11 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; @@ -49,6 +51,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; @@ -72,6 +75,9 @@ import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.search.ReindexContext; +import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.vector.UnrecordedStagedChunkDeleteException; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.util.RestUtil; import org.openmetadata.service.workflows.searchIndex.PaginatedEntitiesSource; import org.openmetadata.service.workflows.searchIndex.PaginatedEntityTimeSeriesSource; @@ -789,7 +795,14 @@ void processPartitionKeepsProgressStatusProcessingAndCompletesSuccessfully() { assertEquals( PartitionStatus.PROCESSING, progressCaptor.getAllValues().get(progressCaptor.getAllValues().size() - 1).getStatus()); - verify(coordinator).completePartition(partition.getId(), 2L, 0L, 0L); + ArgumentCaptor retried = ArgumentCaptor.forClass(StageStatsTracker.class); + InOrder flushedThenRetriedThenCompleted = inOrder(bulkSink, coordinator); + flushedThenRetriedThenCompleted.verify(bulkSink, atLeastOnce()).flushAndAwait(30); + flushedThenRetriedThenCompleted.verify(bulkSink).retryMissedChunks(retried.capture()); + flushedThenRetriedThenCompleted + .verify(coordinator) + .completePartition(partition.getId(), 2L, 0L, 0L); + assertEquals("table", retried.getValue().getEntityType(), "the partition's own tracker"); } @Test @@ -927,6 +940,46 @@ void processPartitionRecordsSinkFailuresAndStopsWhenCursorCannotBeRebuilt() thro verify(coordinator).completePartition(partition.getId(), 0L, 1L, 0L); } + @Test + void aPartitionThatCannotRecordAMissedStagedChunkDeleteFailsWithoutARetry() { + PartitionWorker partitionWorker = + new PartitionWorker(coordinator, bulkSink, BATCH_SIZE, stagedIndexContext); + SearchIndexPartition partition = buildPartition("table", 0, 2); + ResultList> resultList = new ResultList<>(); + resultList.setData(List.of(mock(EntityInterface.class), mock(EntityInterface.class))); + SearchRepository searchRepository = mock(SearchRepository.class); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); + doThrow(new UnrecordedStagedChunkDeleteException("data_asset_embeddings_chunks_g1")) + .when(vectorService) + .requireStagedChunkFailuresRecorded(); + when(coordinator.getCollectionDAO()).thenReturn(collectionDAO); + when(collectionDAO.searchIndexServerStatsDAO()).thenReturn(searchIndexServerStatsDAO); + when(bulkSink.flushAndAwait(30)).thenReturn(true); + when(bulkSink.getPendingVectorTaskCount()).thenReturn(0); + ServerIdentityResolver resolver = mock(ServerIdentityResolver.class); + when(resolver.getServerId()).thenReturn("server-a"); + + try (MockedStatic resolverMock = + mockStatic(ServerIdentityResolver.class); + MockedStatic entityMock = mockStatic(Entity.class); + MockedConstruction ignored = + mockConstruction( + PaginatedEntitiesSource.class, + (mock, context) -> doReturn(resultList).when(mock).readNextKeyset(null))) { + resolverMock.when(ServerIdentityResolver::getInstance).thenReturn(resolver); + entityMock.when(Entity::getSearchRepository).thenReturn(searchRepository); + + partitionWorker.processPartition(partition); + } + + verify(coordinator) + .failPartitionWithoutRetry( + eq(partition.getId()), startsWith(VectorIndexService.UNRECORDED_STAGED_DELETE)); + verify(coordinator, never()).failPartition(any(), any()); + verify(coordinator, never()).completePartition(any(), anyLong(), anyLong(), anyLong()); + } + @Test void processPartitionAdjustsSuccessCountsForProcessFailures() { PartitionWorker partitionWorker = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryEmbeddingsValidationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryEmbeddingsValidationTest.java index 727820954cc2..2e2e752cbdc3 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryEmbeddingsValidationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryEmbeddingsValidationTest.java @@ -142,7 +142,11 @@ void testVectorServiceInitFailureWithEmbeddingClientOk() { assertFalse(result.getPassed()); assertTrue(result.getMessage().contains("OpenSearch connection refused")); - assertTrue(result.getMessage().contains("OpenSearch vector service failed to start")); + assertTrue( + result + .getMessage() + .contains( + "The embedding client is configured but the vector service failed to start.")); } @Test diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/DefaultRecreateHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/DefaultRecreateHandlerTest.java index db4c4a6cd3d7..efcf98fd6d4e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/DefaultRecreateHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/DefaultRecreateHandlerTest.java @@ -32,10 +32,12 @@ import org.openmetadata.service.Entity; import org.openmetadata.service.apps.bundles.searchIndex.ReindexingMetrics; import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.vector.VectorIndexService; @ExtendWith(MockitoExtension.class) @DisplayName("DefaultRecreateHandler Tests") class DefaultRecreateHandlerTest { + private static final String STAGED_CHUNKS = "data_asset_embeddings_chunks_g1700000000000"; @Nested @DisplayName("promoteEntityIndex Tests") @@ -152,6 +154,100 @@ void testPromoteEntityIndexStampsMappingVersion() throws Exception { verify(tracker).updateMappingVersion("table"); } + @Test + @DisplayName("A promoted staged index tells the staged chunk generation it went live") + void aPromotedStagedIndexTellsTheChunkGenerationItWentLive() { + AliasState aliasState = new AliasState(); + aliasState.put("table_search_index_rebuild_old", Set.of("table", "table_search_index")); + aliasState.put("table_search_index_rebuild_new", new HashSet<>()); + SearchClient client = aliasState.toMock(); + SearchRepository repo = mock(SearchRepository.class); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(repo.getSearchClient()).thenReturn(client); + when(repo.getClusterAlias()).thenReturn(""); + when(repo.getVectorIndexService()).thenReturn(vectorService); + when(repo.getIndexMapping("table")) + .thenReturn( + IndexMapping.builder() + .indexName("table_search_index") + .alias("table") + .parentAliases(List.of("all")) + .childAliases(List.of()) + .build()); + + try (MockedStatic entityMock = mockStatic(Entity.class)) { + entityMock.when(Entity::getSearchRepository).thenReturn(repo); + new RecreateWithEmbeddings().promoteEntityIndex(stagedTable(), true); + } + + verify(vectorService).markEntityTypeReindexed("table", true, STAGED_CHUNKS); + } + + @Test + @DisplayName("A run that could not record a staged chunk delete keeps the live chunks") + void aRunThatCouldNotRecordAStagedChunkDeleteKeepsTheLiveChunks() { + AliasState aliasState = new AliasState(); + aliasState.put("table_search_index_rebuild_old", Set.of("table", "table_search_index")); + aliasState.put("table_search_index_rebuild_new", new HashSet<>()); + SearchClient client = aliasState.toMock(); + when(client.getIndexedDocumentCount("table_search_index_rebuild_new")).thenReturn(4L); + SearchRepository repo = mock(SearchRepository.class); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(repo.getSearchClient()).thenReturn(client); + when(repo.getClusterAlias()).thenReturn(""); + when(repo.getVectorIndexService()).thenReturn(vectorService); + when(repo.getIndexMapping("table")) + .thenReturn( + IndexMapping.builder() + .indexName("table_search_index") + .alias("table") + .parentAliases(List.of("all")) + .childAliases(List.of()) + .build()); + EntityReindexContext context = stagedTable(); + context.setStagedChunkDeleteUnrecorded(true); + + boolean promoted; + try (MockedStatic entityMock = mockStatic(Entity.class)) { + entityMock.when(Entity::getSearchRepository).thenReturn(repo); + promoted = new RecreateWithEmbeddings().promoteEntityIndex(context, false); + } + + assertTrue(promoted, "the entity index still promotes its partial data"); + verify(vectorService).markEntityTypeReindexed("table", false, STAGED_CHUNKS); + } + + @Test + @DisplayName("A discarded empty staged index keeps the type's live chunks") + void aDiscardedEmptyStagedIndexKeepsTheTypesLiveChunks() { + AliasState aliasState = new AliasState(); + aliasState.put("table_search_index_rebuild_new", new HashSet<>()); + SearchClient client = aliasState.toMock(); + when(client.getIndexedDocumentCount("table_search_index_rebuild_new")).thenReturn(0L); + SearchRepository repo = mock(SearchRepository.class); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(repo.getSearchClient()).thenReturn(client); + when(repo.getVectorIndexService()).thenReturn(vectorService); + + boolean finished; + try (MockedStatic entityMock = mockStatic(Entity.class)) { + entityMock.when(Entity::getSearchRepository).thenReturn(repo); + finished = new RecreateWithEmbeddings().promoteEntityIndex(stagedTable(), false); + } + + assertTrue(finished, "discarding an empty staged index is a terminal outcome"); + verify(vectorService).markEntityTypeReindexed("table", false, STAGED_CHUNKS); + } + + private static EntityReindexContext stagedTable() { + return EntityReindexContext.builder() + .entityType("table") + .canonicalIndex("table_search_index") + .stagedIndex("table_search_index_rebuild_new") + .stagedChunkIndex(STAGED_CHUNKS) + .build(); + } + @Test @DisplayName("Should not stamp mapping version when promotion fails") void testPromoteEntityIndexDoesNotStampOnFailure() throws Exception { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/RecreateWithEmbeddingsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/RecreateWithEmbeddingsTest.java index 96caca4804cd..d71daa26e301 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/RecreateWithEmbeddingsTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/RecreateWithEmbeddingsTest.java @@ -1,21 +1,65 @@ package org.openmetadata.service.search; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import org.openmetadata.schema.system.EventPublisherJob; import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; class RecreateWithEmbeddingsTest { + private static final String STAGED_CHUNKS = "data_asset_embeddings_chunks_g1700000000000"; + + private final VectorIndexService vectorService = mock(VectorIndexService.class); + private final SearchRepository searchRepository = mock(SearchRepository.class); + + @Test + void aFullJobDrivenRecreateStagesAChunkGenerationOnTheRepositorysVectorService() { + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); + when(vectorService.beginStagedChunkRecreate()).thenReturn(STAGED_CHUNKS); + DefaultRecreateHandler handler = + new RecreateWithEmbeddings().withJobData(new EventPublisherJob()); + + ReindexContext context; + try (MockedStatic entity = mockStatic(Entity.class)) { + entity.when(Entity::getSearchRepository).thenReturn(searchRepository); + context = handler.reCreateIndexes(Set.copyOf(AvailableEntityTypes.LIST)); + } + + assertEquals(Optional.of(STAGED_CHUNKS), context.getStagedChunkIndex()); + } + + @Test + void finalizingATypeWithNoStagedEntityIndexReportsItAsNotPromoted() { + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); + // Without a staged entity index nothing replaces the live one, so the chunks stay live too. + EntityReindexContext context = + EntityReindexContext.builder().entityType("table").stagedChunkIndex(STAGED_CHUNKS).build(); + + try (MockedStatic entity = mockStatic(Entity.class)) { + entity.when(Entity::getSearchRepository).thenReturn(searchRepository); + new RecreateWithEmbeddings().finalizeReindex(context, true); + } + + verify(vectorService).markEntityTypeReindexed("table", false, STAGED_CHUNKS); + } @Test void coversAllVectorTypes_matchesCanonicalCamelCaseNames() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/ChunkSetBoundTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/ChunkSetBoundTest.java new file mode 100644 index 000000000000..d0ea281588b9 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/ChunkSetBoundTest.java @@ -0,0 +1,392 @@ +package org.openmetadata.service.search.vector; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.UUID; +import java.util.function.Predicate; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.service.search.vector.client.EmbeddingClient; + +/** + * Chunk 0's {@code chunkCount} bounds every chunk id stored for a parent. These scenarios run the + * shared write and delete code against an in-memory cluster whose delete-by-query, like a real + * one, sees only refreshed documents, and they never refresh between steps: the by-id bound alone + * must reach what a failed write left behind. + */ +class ChunkSetBoundTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String LIVE = "data_asset_embeddings_chunks"; + private static final String STAGED = LIVE + "_g1"; + private static final String ENTITY_INDEX = "table_search_index"; + + private FakeCluster cluster; + private InMemoryVectorService service; + private EmbeddingClient embeddingClient; + private Table table; + private String parentId; + + @BeforeEach + void setUp() { + embeddingClient = mock(EmbeddingClient.class); + when(embeddingClient.embed(any(String.class))).thenReturn(new float[] {0.1f, 0.2f, 0.3f}); + when(embeddingClient.getDimension()).thenReturn(3); + when(embeddingClient.isAvailable()).thenReturn(true); + cluster = new FakeCluster(); + service = new InMemoryVectorService(embeddingClient, cluster); + table = new Table().withId(UUID.randomUUID()).withName("orders").withUpdatedAt(1L); + parentId = table.getId().toString(); + } + + @ParameterizedTest(name = "into {0}") + @ValueSource(strings = {LIVE, STAGED}) + void aDeleteAfterAGrowthWhoseHeaderFailedLeavesNoChunk(String target) { + growFromOneToThreeChunksWithTheHeaderFailing(target); + + service.deleteEntityChunks(parentId); + + assertEquals(Set.of(), cluster.chunkIds(target, parentId)); + } + + @ParameterizedTest(name = "into {0}") + @ValueSource(strings = {LIVE, STAGED}) + void aShrinkAfterAGrowthWhoseHeaderFailedLeavesNoTrailingChunk(String target) { + growFromOneToThreeChunksWithTheHeaderFailing(target); + + assertTrue(write(target, chunks(1))); + + assertEquals(Set.of(parentId + "_0"), cluster.chunkIds(target, parentId)); + assertEquals(1, cluster.header(target, parentId).path("chunkCount").asInt()); + } + + @ParameterizedTest(name = "into {0}") + @ValueSource(strings = {LIVE, STAGED}) + void aLaterFullWriteAfterAGrowthWhoseHeaderFailedKeepsOnlyItsChunks(String target) { + growFromOneToThreeChunksWithTheHeaderFailing(target); + List> twoChunks = chunks(2); + + assertTrue(write(target, twoChunks)); + + assertEquals(Set.of(parentId + "_0", parentId + "_1"), cluster.chunkIds(target, parentId)); + assertEquals( + twoChunks.getFirst().get("fingerprint"), + cluster.header(target, parentId).path("fingerprint").asText()); + } + + @Test + void aLiveEditMirroredIntoTheStagedGenerationKeepsItsBound() { + service.latchParticipantStagedTarget(STAGED); + assertTrue(write(STAGED, chunks(1))); + cluster.rejectHeaderWritesTo(STAGED); + + service.updateEntityEmbeddings(withChunks(3), ENTITY_INDEX); + cluster.acceptAllWrites(); + service.deleteEntityChunks(parentId); + + assertEquals(Set.of(), cluster.chunkIds(STAGED, parentId)); + assertEquals(Set.of(), cluster.chunkIds(LIVE, parentId)); + } + + @Test + void aGrowthWhoseHeaderFailedLeavesAHeaderThatNoUpdateReadsAsCurrent() { + growFromOneToThreeChunksWithTheHeaderFailing(LIVE); + + JsonNode header = cluster.header(LIVE, parentId); + assertFalse(header.has("fingerprint"), header::toString); + assertEquals(3, header.path("chunkCount").asInt()); + } + + @Test + void aWriteThatKeepsWithinTheBoundSendsNoReservation() { + assertTrue(write(LIVE, chunks(3))); + int requestsBefore = cluster.bulkRequests; + + assertTrue(write(LIVE, chunks(3))); + + assertEquals(2, cluster.bulkRequests - requestsBefore, "the chunks, then the header"); + } + + @ParameterizedTest(name = "into {0}") + @ValueSource(strings = {LIVE, STAGED}) + void aDeleteRemovesChunksAHeaderThatIsBehindDoesNotCover(String target) { + service.latchParticipantStagedTarget(STAGED); + assertTrue(write(target, chunks(1))); + cluster.storeRefreshed(target, parentId + "_1", Map.of("parentId", parentId, "chunkIndex", 1)); + cluster.storeRefreshed(target, parentId + "_4", Map.of("parentId", parentId, "chunkIndex", 4)); + + service.deleteEntityChunks(parentId); + + assertEquals(Set.of(), cluster.chunkIds(target, parentId)); + } + + @Test + void aDeleteRemovesChunksStoredWithoutAHeader() { + cluster.storeRefreshed(LIVE, parentId + "_2", Map.of("parentId", parentId, "chunkIndex", 2)); + + service.deleteEntityChunks(parentId); + + assertEquals(Set.of(), cluster.chunkIds(LIVE, parentId)); + } + + @Test + void aDeleteBeforeTheChunkIndexExistsSendsNothingToIt() { + service.latchParticipantStagedTarget(STAGED); + + service.deleteEntityChunks(parentId); + + assertEquals(0, cluster.requestsToMissingIndices); + } + + private void growFromOneToThreeChunksWithTheHeaderFailing(String target) { + service.latchParticipantStagedTarget(STAGED); + assertTrue(write(target, chunks(1))); + cluster.rejectHeaderWritesTo(target); + assertFalse(write(target, chunks(3)), "the header write fails"); + cluster.acceptAllWrites(); + assertEquals( + Set.of(parentId + "_0", parentId + "_1", parentId + "_2"), + cluster.chunkIds(target, parentId), + "the failed write left chunks past the old count"); + } + + private boolean write(String target, List> chunkDocs) { + return service.writeEntityChunks(parentId, chunkDocs, LIVE.equals(target) ? null : target); + } + + private List> chunks(int count) { + List> chunkDocs = + VectorDocBuilder.fromEntity(withChunks(count), embeddingClient); + assertEquals(count, chunkDocs.size(), "the description spans the expected chunk count"); + return chunkDocs; + } + + private Table withChunks(int count) { + String description = count == 1 ? "Orders placed online." : "word ".repeat(380 * count - 200); + return table.withDescription(description); + } + + /** The shared vector index code over {@link FakeCluster}. */ + private static final class InMemoryVectorService extends AbstractVectorIndexService { + private final FakeCluster cluster; + + InMemoryVectorService(EmbeddingClient embeddingClient, FakeCluster cluster) { + super(embeddingClient, parameters -> Set.of()); + this.cluster = cluster; + } + + @Override + protected String engineName() { + return "InMemory"; + } + + @Override + protected RawResponse performRequest(String method, String endpoint, String body) + throws IOException { + return cluster.handle(method, endpoint, body); + } + + @Override + protected ObjectNode chunkIndexSettings() { + return MAPPER.createObjectNode(); + } + + @Override + protected ObjectNode embeddingFieldMapping(int dimension) { + return MAPPER.createObjectNode().put("type", "float"); + } + + @Override + protected String buildKnnSearch( + float[] vector, VectorSearchParameters parameters, Set readableAnchorIds) { + return "{}"; + } + + @Override + protected boolean knnReturnsAtMostK(double threshold) { + return true; + } + + @Override + protected boolean chunksOntologyTerms() { + return true; + } + } + + /** + * Documents by index and id. A by-id read sees every write, as a realtime GET does; a + * delete-by-query sees only documents stored as refreshed. A rejected header write is a chunk 0 + * that carries a fingerprint. An index exists once it is created or written to; a delete sent to + * one that does not fails, as on a real cluster. + */ + private static final class FakeCluster { + private static final String DOC = "/_doc/"; + private final Map> indices = new HashMap<>(); + private final Set existing = new HashSet<>(); + private final Set refreshed = new HashSet<>(); + private int requestsToMissingIndices; + private Predicate rejectHeaderIndex = index -> false; + private int bulkRequests; + + void rejectHeaderWritesTo(String index) { + rejectHeaderIndex = index::equals; + } + + void acceptAllWrites() { + rejectHeaderIndex = index -> false; + } + + void storeRefreshed(String index, String id, Map source) { + existing.add(index); + docs(index).put(id, MAPPER.valueToTree(source)); + refreshed.add(index + DOC + id); + } + + Set chunkIds(String index, String parentId) { + Set ids = new TreeSet<>(); + docs(index) + .forEach( + (id, source) -> { + if (parentId.equals(source.path("parentId").asText())) { + ids.add(id); + } + }); + return ids; + } + + JsonNode header(String index, String parentId) { + return docs(index).get(parentId + "_0"); + } + + AbstractVectorIndexService.RawResponse handle(String method, String endpoint, String body) + throws IOException { + AbstractVectorIndexService.RawResponse response = ok("{}"); + String index = endpoint.substring(1).split("[/?]")[0]; + boolean wholeIndex = endpoint.indexOf('/', 1) < 0; + if (wholeIndex && "PUT".equals(method)) { + existing.add(index); + } else if (wholeIndex && "HEAD".equals(method)) { + response = + new AbstractVectorIndexService.RawResponse(existing.contains(index) ? 200 : 404, null); + } else if (endpoint.endsWith("/_alias")) { + response = new AbstractVectorIndexService.RawResponse(404, "{\"status\":404}"); + } else if (endpoint.equals("/_bulk")) { + response = bulk(body); + } else if (endpoint.contains("/_delete_by_query")) { + response = deleteByQuery(index, body); + } else if (endpoint.contains(DOC)) { + response = getById(method, endpoint); + } + return response; + } + + private AbstractVectorIndexService.RawResponse getById(String method, String endpoint) { + String index = endpoint.substring(1, endpoint.indexOf(DOC)); + String id = endpoint.substring(endpoint.indexOf(DOC) + DOC.length(), endpoint.indexOf('?')); + JsonNode source = docs(index).get(id); + ObjectNode body = MAPPER.createObjectNode().put("found", source != null); + if (source != null) { + body.set("_source", source); + } + boolean head = "HEAD".equals(method); + return new AbstractVectorIndexService.RawResponse( + source == null && head ? 404 : 200, head ? null : body.toString()); + } + + private AbstractVectorIndexService.RawResponse bulk(String body) throws IOException { + bulkRequests++; + boolean errors = false; + String[] lines = body.split("\n"); + for (int i = 0; i < lines.length; i++) { + JsonNode action = MAPPER.readTree(lines[i]); + if (action.has("delete")) { + errors |= !remove(action.path("delete")); + } else { + JsonNode meta = action.path("index"); + JsonNode source = MAPPER.readTree(lines[++i]); + errors |= !index(meta, source); + } + } + return ok("{\"errors\":" + errors + ",\"items\":[]}"); + } + + private boolean index(JsonNode meta, JsonNode source) { + String index = meta.path("_index").asText(); + String id = meta.path("_id").asText(); + boolean rejected = + rejectHeaderIndex.test(index) && id.endsWith("_0") && source.has("fingerprint"); + if (!rejected) { + existing.add(index); + docs(index).put(id, source); + refreshed.remove(index + DOC + id); + } + return !rejected; + } + + private boolean remove(JsonNode meta) { + String index = meta.path("_index").asText(); + boolean found = existsOrCount(index); + docs(index).remove(meta.path("_id").asText()); + return found; + } + + private boolean existsOrCount(String index) { + boolean found = existing.contains(index); + if (!found) { + requestsToMissingIndices++; + } + return found; + } + + private AbstractVectorIndexService.RawResponse deleteByQuery(String index, String body) + throws IOException { + AbstractVectorIndexService.RawResponse response = + new AbstractVectorIndexService.RawResponse(404, "{\"error\":\"index_not_found\"}"); + if (existsOrCount(index)) { + JsonNode bool = MAPPER.readTree(body).path("query").path("bool"); + String parentId = bool.path("filter").path(0).path("term").path("parentId").asText(); + Set kept = new HashSet<>(); + bool.path("must_not") + .path(0) + .path("ids") + .path("values") + .forEach(id -> kept.add(id.asText())); + docs(index) + .entrySet() + .removeIf( + doc -> + refreshed.contains(index + DOC + doc.getKey()) + && !kept.contains(doc.getKey()) + && parentId.equals(doc.getValue().path("parentId").asText())); + response = ok("{\"failures\":[]}"); + } + return response; + } + + private Map docs(String index) { + return indices.computeIfAbsent(index, ignored -> new HashMap<>()); + } + + private static AbstractVectorIndexService.RawResponse ok(String body) { + return new AbstractVectorIndexService.RawResponse(200, body); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/ElasticSearchVectorServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/ElasticSearchVectorServiceTest.java index b4b5db88cea1..20eda44270f0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/ElasticSearchVectorServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/ElasticSearchVectorServiceTest.java @@ -1,5 +1,6 @@ package org.openmetadata.service.search.vector; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -7,8 +8,14 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -18,32 +25,43 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; import es.co.elastic.clients.elasticsearch.ElasticsearchClient; import es.co.elastic.clients.transport.rest5_client.Rest5ClientTransport; import es.co.elastic.clients.transport.rest5_client.low_level.Request; import es.co.elastic.clients.transport.rest5_client.low_level.Response; +import es.co.elastic.clients.transport.rest5_client.low_level.ResponseException; import es.co.elastic.clients.transport.rest5_client.low_level.Rest5Client; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; +import java.util.stream.Stream; +import org.apache.commons.lang3.function.FailableRunnable; import org.apache.hc.core5.http.HttpEntity; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.search.OntologyTermSearch; import org.openmetadata.service.search.vector.client.EmbeddingClient; +import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; import org.openmetadata.service.search.vector.utils.DTOs; import org.openmetadata.service.security.policyevaluator.SubjectContext; import org.slf4j.LoggerFactory; @@ -75,6 +93,19 @@ void setup() throws Exception { vectorService = new ElasticSearchVectorService(mockEsClient, mockEmbeddingClient); } + private final ListAppender serviceLog = new ListAppender<>(); + + @BeforeEach + void captureServiceLog() { + serviceLog.start(); + ((Logger) LoggerFactory.getLogger(AbstractVectorIndexService.class)).addAppender(serviceLog); + } + + @AfterEach + void releaseServiceLog() { + ((Logger) LoggerFactory.getLogger(AbstractVectorIndexService.class)).detachAppender(serviceLog); + } + @Test void readableAnchorsAreResolvedOnceAndReachEveryOverfetchPage() throws Exception { String anchorId = UUID.randomUUID().toString(); @@ -125,39 +156,6 @@ void readableAnchorsAreResolvedOnceAndReachEveryOverfetchPage() throws Exception } } - @Test - void reindexReusesOnlyStoredEmbeddingsWhoseFingerprintIsCurrent() throws Exception { - long updatedAt = 1_700_000_000_000L; - Table unchanged = table("orders", "Orders placed online", updatedAt); - Table textChanged = table("payments", "Customer payments by card", updatedAt); - // Stand-in for the text an older release built for the same entity: same updatedAt, other text. - Table textChangedAsLastEmbedded = - table("payments", "Customer payments", updatedAt).withId(textChanged.getId()); - Table unfingerprintable = table("refunds", "Refunds issued", updatedAt); - answerIdSearchesFrom( - Map.of( - id(unchanged), storedEntityDoc(unchanged, unchanged), - id(textChanged), storedEntityDoc(textChanged, textChangedAsLastEmbedded), - id(unfingerprintable), storedEntityDoc(unfingerprintable, unfingerprintable))); - - Map reusable = - vectorService.getExistingEmbeddingsBatch( - "table_search_index", - Map.of( - id(unchanged), currentFingerprint(unchanged), - id(textChanged), currentFingerprint(textChanged), - id(unfingerprintable), - () -> { - throw new IllegalStateException("tag without an FQN"); - }, - UUID.randomUUID().toString(), currentFingerprint(unchanged))); - - assertEquals(Set.of(id(unchanged)), reusable.keySet()); - assertEquals( - VectorDocBuilder.computeFingerprintForEntity(unchanged), - reusable.get(id(unchanged)).path("fingerprint").asText()); - } - @Test void searchEmbedsTheQueryAsAQueryNotADocument() throws Exception { // Providers that distinguish the two (Cohere on Bedrock: search_query vs search_document) @@ -189,7 +187,7 @@ void twoArgOverloadRefusesOntologyConceptWithoutWritingOrEmbedding() throws Exce .withDescription("A purchase") .withDeleted(false); - Logger logger = (Logger) LoggerFactory.getLogger(ElasticSearchVectorService.class); + Logger logger = (Logger) LoggerFactory.getLogger(AbstractVectorIndexService.class); ListAppender appender = new ListAppender<>(); appender.start(); logger.addAppender(appender); @@ -211,60 +209,6 @@ void twoArgOverloadRefusesOntologyConceptWithoutWritingOrEmbedding() throws Exce } } - @Test - void testThresholdFilteringRemovesLowScoreResults() throws Exception { - String esResponse = - """ - { - "hits": { - "total": {"value": 4}, - "hits": [ - {"_score": 0.9, "_source": {"parentId": "parent1", "chunkIndex": 0, "text": "High score chunk"}}, - {"_score": 0.7, "_source": {"parentId": "parent2", "chunkIndex": 0, "text": "Medium score chunk"}}, - {"_score": 0.4, "_source": {"parentId": "parent3", "chunkIndex": 0, "text": "Low score chunk"}}, - {"_score": 0.2, "_source": {"parentId": "parent4", "chunkIndex": 0, "text": "Very low score chunk"}} - ] - } - } - """; - - mockRestClientResponse(esResponse); - - DTOs.VectorSearchResponse results = - vectorService.search("test query", Map.of(), 10, 0, 100, 0.5); - - assertNotNull(results); - assertEquals(2, results.hits.size(), "Should return 2 results (scores 0.9 and 0.7)"); - for (Map result : results.hits) { - double score = (double) result.get("_score"); - assertTrue(score >= 0.5, "All results should have score >= 0.5, got: " + score); - } - } - - @Test - void testScoreFieldIncludedInResults() throws Exception { - String esResponse = - """ - { - "hits": { - "total": {"value": 1}, - "hits": [ - {"_score": 0.85, "_source": {"parentId": "parent1", "chunkIndex": 0, "text": "Test chunk"}} - ] - } - } - """; - - mockRestClientResponse(esResponse); - - DTOs.VectorSearchResponse results = - vectorService.search("test query", Map.of(), 10, 0, 100, 0.0); - - assertEquals(1, results.hits.size()); - assertTrue(results.hits.get(0).containsKey("_score"), "Result should contain _score field"); - assertEquals(0.85, (double) results.hits.get(0).get("_score"), 0.001); - } - @Test void testParentIdFallbackToDocIdIsWrittenIntoResultMap() throws Exception { // _source has no parentId; collectSearchHits falls back to the document _id for grouping. @@ -296,86 +240,6 @@ void testParentIdFallbackToDocIdIsWrittenIntoResultMap() throws Exception { "Result map must carry the fallback parentId (= _id) when _source has none"); } - @Test - void testParentGroupingLimitsDistinctParents() throws Exception { - // size=2 → requestedParents=3; 4 distinct parents in response causes loop to exit after 1 page - String esResponse = - """ - { - "hits": { - "total": {"value": 8}, - "hits": [ - {"_score": 0.9, "_source": {"parentId": "parent1", "chunkIndex": 0}}, - {"_score": 0.88, "_source": {"parentId": "parent1", "chunkIndex": 1}}, - {"_score": 0.85, "_source": {"parentId": "parent1", "chunkIndex": 2}}, - {"_score": 0.8, "_source": {"parentId": "parent2", "chunkIndex": 0}}, - {"_score": 0.78, "_source": {"parentId": "parent2", "chunkIndex": 1}}, - {"_score": 0.7, "_source": {"parentId": "parent3", "chunkIndex": 0}}, - {"_score": 0.68, "_source": {"parentId": "parent3", "chunkIndex": 1}}, - {"_score": 0.6, "_source": {"parentId": "parent4", "chunkIndex": 0}} - ] - } - } - """; - - mockRestClientResponse(esResponse); - - DTOs.VectorSearchResponse results = - vectorService.search("test query", Map.of(), 2, 0, 100, 0.0); - - assertEquals(5, results.hits.size(), "Should return all chunks from first 2 parents (3+2=5)"); - long distinctParents = results.hits.stream().map(r -> r.get("parentId")).distinct().count(); - assertEquals(2, distinctParents, "Should have chunks from exactly 2 distinct parents"); - } - - @Test - void testZeroThresholdReturnsAllResults() throws Exception { - String esResponse = - """ - { - "hits": { - "total": {"value": 3}, - "hits": [ - {"_score": 0.9, "_source": {"parentId": "p1", "chunkIndex": 0}}, - {"_score": 0.5, "_source": {"parentId": "p2", "chunkIndex": 0}}, - {"_score": 0.1, "_source": {"parentId": "p3", "chunkIndex": 0}} - ] - } - } - """; - - mockRestClientResponse(esResponse); - - DTOs.VectorSearchResponse results = - vectorService.search("test query", Map.of(), 10, 0, 100, 0.0); - - assertEquals(3, results.hits.size(), "With threshold 0.0, should return all 3 results"); - } - - @Test - void testHighThresholdFiltersAllResults() throws Exception { - String esResponse = - """ - { - "hits": { - "total": {"value": 3}, - "hits": [ - {"_score": 0.5, "_source": {"parentId": "p1", "chunkIndex": 0}}, - {"_score": 0.3, "_source": {"parentId": "p2", "chunkIndex": 0}}, - {"_score": 0.1, "_source": {"parentId": "p3", "chunkIndex": 0}} - ] - } - } - """; - - mockRestClientResponse(esResponse); - - DTOs.VectorSearchResponse results = - vectorService.search("test query", Map.of(), 10, 0, 100, 0.9); - - assertEquals(0, results.hits.size(), "With threshold 0.9, all results should be filtered out"); - } - @Test void testChunksWithoutParentIdGroupedByDocumentId() throws Exception { // Chunks without parentId in _source fall back to the document's _id field @@ -402,40 +266,6 @@ void testChunksWithoutParentIdGroupedByDocumentId() throws Exception { 3, results.hits.size(), "Orphan chunk should be included, grouped by document _id"); } - @Test - void testRequestedSizeLimitsDistinctParents() throws Exception { - // size=3 → requestedParents=4; 10 distinct parents in response exits loop immediately - String esResponse = - """ - { - "hits": { - "total": {"value": 10}, - "hits": [ - {"_score": 0.9, "_source": {"parentId": "p1", "chunkIndex": 0}}, - {"_score": 0.8, "_source": {"parentId": "p2", "chunkIndex": 0}}, - {"_score": 0.7, "_source": {"parentId": "p3", "chunkIndex": 0}}, - {"_score": 0.6, "_source": {"parentId": "p4", "chunkIndex": 0}}, - {"_score": 0.5, "_source": {"parentId": "p5", "chunkIndex": 0}}, - {"_score": 0.4, "_source": {"parentId": "p6", "chunkIndex": 0}}, - {"_score": 0.3, "_source": {"parentId": "p7", "chunkIndex": 0}}, - {"_score": 0.2, "_source": {"parentId": "p8", "chunkIndex": 0}}, - {"_score": 0.15, "_source": {"parentId": "p9", "chunkIndex": 0}}, - {"_score": 0.1, "_source": {"parentId": "p10", "chunkIndex": 0}} - ] - } - } - """; - - mockRestClientResponse(esResponse); - - DTOs.VectorSearchResponse results = - vectorService.search("test query", Map.of(), 3, 0, 100, 0.0); - - assertEquals(3, results.hits.size(), "Should limit to 3 distinct parents"); - long distinctParents = results.hits.stream().map(r -> r.get("parentId")).distinct().count(); - assertEquals(3, distinctParents, "Should have exactly 3 distinct parents"); - } - @Test void testEmptyHitsResponseReturnsEmptyList() throws Exception { String esResponse = @@ -630,28 +460,551 @@ void testGetExistingFingerprintsBatchReturnsEmptyForEmptyInput() { assertTrue(result.isEmpty()); } - /** Returns a fresh stream on every call — safe for multi-iteration loops. */ @Test - void testExecuteGenericRequestHandlesNullEntityWithout4xxNPE() throws Exception { - // Some ES endpoints return no body on 4xx; getEntity() may be null. The previous - // code dereferenced response.getEntity().getContent() unconditionally and NPE'd, - // masking the actual HTTP status. We must surface the status (400) and an empty - // body in the error message. - Response mockResponse = mock(Response.class); - when(mockResponse.getStatusCode()).thenReturn(400); - when(mockResponse.getEntity()).thenReturn(null); - when(mockRestClient.performRequest(any(Request.class))).thenReturn(mockResponse); + void aClientErrorWithoutABodySurfacesItsStatus() throws Exception { + // Some Elasticsearch endpoints answer 4xx with no entity at all. + Response noBody = mock(Response.class); + when(noBody.getStatusCode()).thenReturn(400); + when(noBody.getEntity()).thenReturn(null); + when(mockRestClient.performRequest(any(Request.class))).thenReturn(noBody); + + RuntimeException error = + assertThrows( + RuntimeException.class, + () -> vectorService.executeGenericRequest("GET", "/_some/path", null)); - RuntimeException ex = + assertEquals("Elasticsearch generic request failed", error.getMessage()); + assertEquals( + "Elasticsearch request failed with status 400: no body", error.getCause().getMessage()); + } + + @Test + void aServerErrorThrownByTheClientSurfacesItsStatusAndBody() throws Exception { + // Rest5Client returns 4xx responses but throws 5xx ones. + ResponseException thrown = mock(ResponseException.class); + Response unavailable = response(503, "{\"error\":\"unavailable\"}"); + when(thrown.getResponse()).thenReturn(unavailable); + when(mockRestClient.performRequest(any(Request.class))).thenThrow(thrown); + + RuntimeException error = assertThrows( RuntimeException.class, () -> vectorService.executeGenericRequest("GET", "/_some/path", null)); + + assertEquals( + "Elasticsearch request failed with status 503: {\"error\":\"unavailable\"}", + error.getCause().getMessage()); + } + + @Test + void theChunkIndexMapsTheEmbeddingAsADenseVector() throws Exception { + when(mockEmbeddingClient.getDimension()).thenReturn(3); + Response noSuchIndex = response(404, "{\"status\":404}"); + answerByEndpointSuffix(Map.of("/_alias", noSuchIndex)); + + vectorService.writeEntityChunks("parent-1", List.of(), null); + + JsonNode index = bodyOf(sentRequest("PUT", "/data_asset_embeddings_chunks")); + JsonNode properties = index.path("mappings").path("properties"); + assertEquals( + "{\"type\":\"dense_vector\",\"dims\":3,\"index\":true,\"similarity\":\"cosine\"}", + properties.path("embedding").toString()); + assertEquals("{\"type\":\"keyword\"}", properties.path("parentId").toString()); + assertEquals("{\"dataAssetEmbeddings\":{}}", index.path("aliases").toString()); + assertFalse( + index.has("settings"), "index.knn is an OpenSearch setting; Elasticsearch has none"); + } + + @Test + void passagesOfOneParentComeFromAKnnSearchFilteredToItsChunks() throws Exception { + Response chunkHits = + response( + 200, + "{\"hits\":{\"hits\":[{\"_source\":{\"textToLLMContext\":\"Retention is 30 days\"}}]}}"); + answerByEndpointSuffix(Map.of("/_search", chunkHits)); + + List passages = vectorService.searchChunksByParent("parent-1", "retention", 2, null); + + assertEquals(List.of("Retention is 30 days"), passages); + JsonNode search = bodyOf(sentRequest("POST", "/data_asset_embeddings_chunks/_search")); + JsonNode knn = search.path("knn"); + assertEquals(2, search.path("size").asInt()); + assertFalse(search.has("query"), "Elasticsearch takes knn as a top-level clause"); + assertEquals("embedding", knn.path("field").asText()); + assertEquals("[0.1,0.2,0.3]", knn.path("query_vector").toString()); + assertEquals(2, knn.path("k").asInt()); + assertEquals(100, knn.path("num_candidates").asInt()); + assertEquals( + "[{\"term\":{\"deleted\":false}},{\"term\":{\"parentId\":\"parent-1\"}}]", + knn.path("filter").path("bool").path("must").toString()); + } + + @Test + void aSearchWithAThresholdNeverAsksForMoreThanKHitsPerPage() throws Exception { + answerByEndpointSuffix(Map.of("/_search", response(200, EMPTY_HITS_RESPONSE))); + + vectorService.search("retention", Map.of(), 10, 0, 5, 0.5); + + JsonNode search = bodyOf(sentRequest("POST", "/dataAssetEmbeddings/_search")); + assertEquals(5, search.path("size").asInt()); + assertEquals(5, search.path("knn").path("k").asInt()); + } + + @Test + void anUnwritableChunkIndexStillRefreshesTheEntityDocEmbedding() throws Exception { + when(mockEmbeddingClient.isAvailable()).thenReturn(true); + when(mockEmbeddingClient.getDimension()).thenReturn(3); + Table table = + new Table() + .withId(UUID.randomUUID()) + .withName("orders") + .withFullyQualifiedName("svc.db.schema.orders") + .withDescription("Orders placed online") + .withUpdatedAt(1L); + String parentId = table.getId().toString(); + String fingerprint = VectorDocBuilder.computeFingerprintForEntity(table); + answerByEndpointSuffix( + Map.of( + "/_alias", response(404, "{\"status\":404}"), + "/data_asset_embeddings_chunks", response(503, "{\"error\":\"max shards\"}"))); + + vectorService.backfillEntityChunks(table, null); + vectorService.updateEntityEmbeddings(table, "table_search_index"); + + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(mockRestClient, atLeastOnce()).performRequest(sent.capture()); + assertTrue( + sent.getAllValues().stream().noneMatch(r -> r.getEndpoint().endsWith("/_bulk")), + "no chunk document may be written while the chunk index is missing"); + JsonNode update = + bodyOf( + sentRequest( + "POST", "/table_search_index/_update/" + parentId + "?retry_on_conflict=3")); + assertEquals(fingerprint, update.path("doc").path("fingerprint").asText()); + assertEquals("[0.1,0.2,0.3]", update.path("doc").path("embedding").toString()); + } + + @Test + void anOntologyTermKeepsItsVectorOnItsTermDocumentAndWritesNoChunk() throws Exception { + when(mockEmbeddingClient.isAvailable()).thenReturn(true); + when(mockEmbeddingClient.getDimension()).thenReturn(3); + OntologyConcept concept = + spy( + new OntologyConcept() + .withId(UUID.randomUUID()) + .withName("Customer") + .withDescription("A person who buys")); + doReturn( + new EntityReference() + .withId(concept.getId()) + .withName("Customer") + .withType(Entity.ONTOLOGY_CONCEPT)) + .when(concept) + .getEntityReference(); + String termIndex = "ontology_concept_search_index"; + String releaseBody = "Customer: A person who buys"; + answerByEndpointSuffix(Map.of()); + + try (MockedStatic terms = + mockStatic(OntologyTermSearch.class, CALLS_REAL_METHODS)) { + terms + .when(() -> OntologyTermSearch.writeCurrentEmbedding(any(), any(), any())) + .thenAnswer( + invocation -> { + invocation.>getArgument(2).run(); + return null; + }); + vectorService.updateEntityEmbeddingChunks(concept); + vectorService.updateEntityEmbeddings(concept, termIndex, releaseBody); + } + + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(mockRestClient, atLeastOnce()).performRequest(sent.capture()); + assertTrue( + sent.getAllValues().stream() + .noneMatch( + r -> r.getEndpoint().endsWith("/_bulk") || r.getEndpoint().contains("chunks")), + "Elasticsearch keeps no ontology chunk index"); + JsonNode update = + bodyOf( + sentRequest( + "POST", "/" + termIndex + "/_update/" + concept.getId() + "?retry_on_conflict=3")); + assertEquals( + VectorDocBuilder.computeFingerprintForEntity(concept, releaseBody), + update.path("doc").path("fingerprint").asText()); + } + + @Test + void aReindexRetryMergesTheEmbeddingIntoTheEntityDocAndReportsWhetherItWasWritten() + throws Exception { + String entityId = UUID.randomUUID().toString(); + Map fields = Map.of("fingerprint", "fp", "embedding", List.of(0.1, 0.2, 0.3)); + String update = "/table_search_index_staged/_update/" + entityId + "?retry_on_conflict=3"; + answerByEndpointSuffix(Map.of()); + + assertTrue(vectorService.writeEntityEmbedding("table_search_index_staged", entityId, fields)); + JsonNode doc = bodyOf(sentRequest("POST", update)).path("doc"); + assertEquals("fp", doc.path("fingerprint").asText()); + assertEquals("[0.1,0.2,0.3]", doc.path("embedding").toString()); + + answerByEndpointSuffix( + Map.of(update, response(404, "{\"error\":{\"type\":\"document_missing_exception\"}}"))); + assertFalse(vectorService.writeEntityEmbedding("table_search_index_staged", entityId, fields)); + } + + static Stream rejectedChunkBulks() throws Exception { + return Stream.of( + Arguments.of("an HTTP failure", response(503, "{\"error\":\"unavailable\"}")), + Arguments.of( + "an item failure in a 200", + response( + 200, + "{\"errors\":true,\"items\":[{\"index\":{\"status\":429,\"error\":" + + "{\"type\":\"es_rejected_execution_exception\"}}}]}"))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("rejectedChunkBulks") + void aRejectedChunkBulkStillRefreshesTheEntityDocAndTheNextUpdateRewritesTheChunks( + String failure, Response rejectedBulk) throws Exception { + when(mockEmbeddingClient.isAvailable()).thenReturn(true); + when(mockEmbeddingClient.getDimension()).thenReturn(3); + Table table = orders(); + String parentId = table.getId().toString(); + String fingerprint = VectorDocBuilder.computeFingerprintForEntity(table); + answerByEndpointSuffix( + Map.of("/_alias", response(404, "{\"status\":404}"), "/_bulk", rejectedBulk)); + + vectorService.updateEntityEmbeddings(table, "table_search_index"); + + JsonNode update = + bodyOf( + sentRequest( + "POST", "/table_search_index/_update/" + parentId + "?retry_on_conflict=3")); + assertEquals(fingerprint, update.path("doc").path("fingerprint").asText()); + assertEquals("[0.1,0.2,0.3]", update.path("doc").path("embedding").toString()); + assertTrue( + logged(Level.ERROR, "Failed to write chunks for " + parentId), "the failure is logged"); + + clearInvocations(mockRestClient); + answerByEndpointSuffix( + Map.of( + "/table_search_index/_search", + response( + 200, + "{\"hits\":{\"hits\":[{\"_source\":{\"fingerprint\":\"" + fingerprint + "\"}}]}}"), + "/_bulk", + response(200, "{\"errors\":false,\"items\":[]}"))); + + vectorService.updateEntityEmbeddings(table, "table_search_index"); + + assertTrue( + bodyText(sentRequest("POST", "/_bulk")).contains(parentId + "_0"), + "the next update rewrites the chunks although the entity doc is current"); + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(mockRestClient, atLeastOnce()).performRequest(sent.capture()); assertTrue( - ex.getMessage().contains("400"), - "Error must surface the HTTP status, not a NPE: " + ex.getMessage()); + sent.getAllValues().stream().noneMatch(r -> r.getEndpoint().contains("/_update/")), + "a current entity doc is not updated again"); + } + + @Test + void aChunkRejectedBesideTheHeaderNeverMovesTheHeaderForward() throws Exception { + when(mockEmbeddingClient.isAvailable()).thenReturn(true); + when(mockEmbeddingClient.getDimension()).thenReturn(3); + Table table = orders().withDescription("Orders placed online. ".repeat(300)); + String parentId = table.getId().toString(); + assertTrue( + VectorDocBuilder.fromEntity(table, mockEmbeddingClient).size() > 1, + "the entity spans several chunks"); + Response ok = response(200, "{\"errors\":false,\"items\":[]}"); + Response noAlias = response(404, "{\"status\":404}"); + Response rejected = + response( + 200, + "{\"errors\":true,\"items\":[{\"index\":{\"status\":429,\"error\":" + + "{\"type\":\"es_rejected_execution_exception\"}}}]}"); + when(mockRestClient.performRequest(any(Request.class))) + .thenAnswer( + invocation -> { + Request request = invocation.getArgument(0); + Response answer = request.getEndpoint().endsWith("/_alias") ? noAlias : ok; + if ("/_bulk".equals(request.getEndpoint()) + && bodyText(request).contains("\"_id\":\"" + parentId + "_1\"")) { + answer = rejected; + } + return answer; + }); + + vectorService.updateEntityEmbeddings(table, "table_search_index"); + + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(mockRestClient, atLeastOnce()).performRequest(sent.capture()); + List bulks = new ArrayList<>(); + for (Request request : sent.getAllValues()) { + if (request.getEndpoint().equals("/_bulk")) { + bulks.add(bodyText(request)); + } + } + assertEquals(2, bulks.size(), "the reservation, then the rejected bulk that stops the write"); + assertTrue(bulks.getFirst().contains("\"_id\":\"" + parentId + "_0\""), bulks::toString); assertFalse( - ex.getCause() instanceof NullPointerException, - "Null entity must not cause a NullPointerException"); + bulks.getFirst().contains("\"fingerprint\""), + "the reservation raises the count without marking the set current"); + assertTrue(bulks.get(1).contains("\"_id\":\"" + parentId + "_1\""), bulks::toString); + assertFalse( + bulks.get(1).contains("\"_id\":\"" + parentId + "_0\""), + "the header is not written beside the rejected chunk"); + } + + @Test + void aMissedChunkWriteNeverBlocksPromotion() throws Exception { + when(mockEmbeddingClient.isAvailable()).thenReturn(true); + when(mockEmbeddingClient.getDimension()).thenReturn(3); + Table table = orders(); + answerByEndpointContaining( + freshInstallRules("/_bulk", response(503, "{\"error\":\"unavailable\"}"))); + String staged = vectorService.beginStagedChunkRecreate(); + assertNotNull(staged); + + boolean written = + vectorService.writeEntityChunks( + table.getId().toString(), + VectorDocBuilder.fromEntity(table, mockEmbeddingClient), + staged); + promoteEveryEntityIndex(staged); + + assertFalse(written, "the caller is told about the miss, to count and retry it"); + assertEquals(0, sentCount("PUT", "/" + staged + "/_mapping"), "a missed write saves no flag"); + assertEquals(1, sentCount("POST", "/_aliases"), "the generation goes live"); + } + + @Test + void aProviderFailureWithNoLiveChunksStillPromotes() throws Exception { + when(mockEmbeddingClient.isAvailable()).thenReturn(true); + when(mockEmbeddingClient.embed(any(String.class))).thenThrow(new IllegalStateException("429")); + answerByEndpointContaining(freshInstallRules(LIVE_DOC, response(404, "{}"))); + String staged = vectorService.beginStagedChunkRecreate(); + + boolean written = vectorService.backfillEntityChunks(orders(), staged); + promoteEveryEntityIndex(staged); + + assertFalse(written); + assertEquals(0, sentCount("PUT", "/" + staged + "/_mapping")); + assertEquals(1, sentCount("POST", "/_aliases"), "the generation goes live"); + } + + @Test + void anOpenCircuitSkipsTheProviderCallAndReportsTheMiss() throws Exception { + when(mockEmbeddingClient.isAvailable()).thenReturn(false); + String staged = vectorService.getChunkIndexName() + "_g1"; + vectorService.latchParticipantStagedTarget(staged); + answerByEndpointContaining(rules(LIVE_DOC, response(404, "{}"))); + + boolean written = vectorService.backfillEntityChunks(orders(), staged); + + assertFalse(written); + verify(mockEmbeddingClient, never()).embed(any(String.class)); + } + + @Test + void aFailedDeleteBlocksPromotionAndSavesItsFlagOnce() throws Exception { + answerByEndpointContaining( + freshInstallRules( + "/_bulk", response(503, "{\"error\":\"unavailable\"}"), "/_doc/", chunkHeader())); + String staged = vectorService.beginStagedChunkRecreate(); + + for (int i = 0; i < 3; i++) { + vectorService.deleteEntityChunks(UUID.randomUUID().toString()); + } + promoteEveryEntityIndex(staged); + + JsonNode flag = bodyOf(sentRequest("PUT", "/" + staged + "/_mapping")); + assertTrue(flag.path("_meta").path("incompleteChunkWrites").asBoolean()); + assertEquals(1, sentCount("PUT", "/" + staged + "/_mapping"), "one flag per generation"); + assertEquals(0, sentCount("POST", "/_aliases"), "no alias swap"); + assertTrue(logged(Level.WARN, "a delete of a removed entity's chunks failed")); + } + + @Test + void aParticipantThatCannotSaveTheDeleteFlagFailsItsPartitionUntilARetrySavesIt() + throws Exception { + String staged = vectorService.getChunkIndexName() + "_g1"; + vectorService.latchParticipantStagedTarget(staged); + answerByEndpointContaining( + rules( + "/_bulk", + response(503, "{\"error\":\"unavailable\"}"), + "/" + staged + "/_mapping", + response(503, "{\"error\":\"unavailable\"}"), + "/_doc/", + chunkHeader())); + + vectorService.deleteEntityChunks(orders().getId().toString()); + + assertThrows(IllegalStateException.class, vectorService::requireStagedChunkFailuresRecorded); + + answerByEndpointContaining(rules()); + assertDoesNotThrow(vectorService::requireStagedChunkFailuresRecorded); + JsonNode flag = bodyOf(sentRequest("PUT", "/" + staged + "/_mapping")); + assertTrue(flag.path("_meta").path("incompleteChunkWrites").asBoolean()); + } + + @Test + void aTypeWhoseEntityIndexStayedLiveKeepsTheLiveChunks() throws Exception { + answerByEndpointContaining(freshInstallRules()); + String staged = vectorService.beginStagedChunkRecreate(); + + AvailableEntityTypes.SET.forEach( + type -> vectorService.markEntityTypeReindexed(type, !"table".equals(type), staged)); + + assertEquals(0, sentCount("POST", "/_aliases"), "no alias swap"); + assertTrue(logged(Level.WARN, "the entity indexes of [table] kept their live index")); + } + + @Test + void anEmptyGenerationNeverReplacesANonEmptyLiveOne() throws Exception { + String live = vectorService.getChunkIndexName(); + answerByEndpointContaining( + rules( + "/_aliases", + response(200, "{}"), + "/_alias", + response(200, "{\"" + live + "\":{\"aliases\":{}}}"), + "/" + live + "/_count", + response(200, "{\"count\":5}"), + "/_count", + response(200, "{\"count\":0}"))); + String staged = vectorService.beginStagedChunkRecreate(); + + promoteEveryEntityIndex(staged); + + assertEquals(0, sentCount("POST", "/_aliases"), "the live chunks stay"); + assertTrue(logged(Level.WARN, "holds no chunks while the live index does")); + } + + @Test + void aChunkCountThatCannotBeReadKeepsTheLiveChunks() throws Exception { + answerByEndpointContaining( + freshInstallRules("/_count", response(503, "{\"error\":\"unavailable\"}"))); + String staged = vectorService.beginStagedChunkRecreate(); + + promoteEveryEntityIndex(staged); + + assertEquals(0, sentCount("POST", "/_aliases"), "the live chunks stay"); + } + + private static final String LIVE_DOC = "/data_asset_embeddings_chunks/_doc/"; + + private void promoteEveryEntityIndex(String staged) { + AvailableEntityTypes.SET.forEach( + type -> vectorService.markEntityTypeReindexed(type, true, staged)); + } + + /** No chunk index exists yet, and any staged generation counts one chunk. */ + private static Map freshInstallRules(Object... first) throws Exception { + Map rules = rules(first); + rules.putIfAbsent("/_aliases", response(200, "{}")); + rules.putIfAbsent("/_alias", response(404, "{\"status\":404}")); + rules.putIfAbsent("/_count", response(200, "{\"count\":1}")); + return rules; + } + + private static Map rules(Object... endpointAndResponse) { + Map rules = new LinkedHashMap<>(); + for (int i = 0; i < endpointAndResponse.length; i += 2) { + rules.put((String) endpointAndResponse[i], (Response) endpointAndResponse[i + 1]); + } + return rules; + } + + private static Response chunkHeader() throws Exception { + return response(200, "{\"found\":true,\"_source\":{\"fingerprint\":\"fp\",\"chunkCount\":1}}"); + } + + private long sentCount(String method, String endpoint) throws Exception { + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(mockRestClient, atLeastOnce()).performRequest(sent.capture()); + return sent.getAllValues().stream() + .filter(request -> method.equals(request.getMethod())) + .filter(request -> endpoint.equals(request.getEndpoint())) + .count(); + } + + /** Answers a request from the first rule its endpoint contains, and any other with 200 and {}. */ + private void answerByEndpointContaining(Map rules) throws Exception { + Response ok = response(200, "{}"); + when(mockRestClient.performRequest(any(Request.class))) + .thenAnswer( + invocation -> { + String endpoint = invocation.getArgument(0).getEndpoint(); + return rules.entrySet().stream() + .filter(rule -> endpoint.contains(rule.getKey())) + .map(Map.Entry::getValue) + .findFirst() + .orElse(ok); + }); + } + + private static Table orders() { + return new Table() + .withId(UUID.randomUUID()) + .withName("orders") + .withFullyQualifiedName("svc.db.schema.orders") + .withDescription("Orders placed online") + .withUpdatedAt(1L); + } + + private boolean logged(Level level, String text) { + return serviceLog.list.stream() + .anyMatch(event -> event.getLevel() == level && event.getFormattedMessage().contains(text)); + } + + private static String bodyText(Request request) throws Exception { + try (InputStream content = request.getEntity().getContent()) { + return new String(content.readAllBytes(), StandardCharsets.UTF_8); + } + } + + /** Answers a request from the rule its endpoint ends with, and any other with 200 and {}. */ + private void answerByEndpointSuffix(Map responsesBySuffix) throws Exception { + Response ok = response(200, "{}"); + when(mockRestClient.performRequest(any(Request.class))) + .thenAnswer( + invocation -> { + String endpoint = invocation.getArgument(0).getEndpoint(); + return responsesBySuffix.entrySet().stream() + .filter(rule -> endpoint.endsWith(rule.getKey())) + .map(Map.Entry::getValue) + .findFirst() + .orElse(ok); + }); + } + + private static Response response(int status, String json) throws Exception { + Response response = mock(Response.class); + HttpEntity entity = mock(HttpEntity.class); + when(response.getStatusCode()).thenReturn(status); + when(response.getEntity()).thenReturn(entity); + when(entity.getContent()) + .thenAnswer(inv -> new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))); + return response; + } + + private Request sentRequest(String method, String endpoint) throws Exception { + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(mockRestClient, atLeastOnce()).performRequest(sent.capture()); + return sent.getAllValues().stream() + .filter(request -> method.equals(request.getMethod())) + .filter(request -> endpoint.equals(request.getEndpoint())) + .findFirst() + .orElseThrow(() -> new AssertionError("No " + method + " " + endpoint + " was sent")); + } + + private static JsonNode bodyOf(Request request) throws Exception { + try (InputStream content = request.getEntity().getContent()) { + return JsonUtils.readTree(new String(content.readAllBytes(), StandardCharsets.UTF_8)); + } } private void mockRestClientResponse(String responseJson) throws Exception { @@ -758,72 +1111,4 @@ private void mockRestClientResponseSequence(String... responses) throws Exceptio return new ByteArrayInputStream(responses[idx].getBytes(StandardCharsets.UTF_8)); }); } - - private static Table table(String name, String description, long updatedAt) { - return new Table() - .withId(UUID.randomUUID()) - .withName(name) - .withFullyQualifiedName("svc.db.schema." + name) - .withDescription(description) - .withUpdatedAt(updatedAt); - } - - private static String id(Table table) { - return table.getId().toString(); - } - - private static Supplier currentFingerprint(Table table) { - return () -> VectorDocBuilder.computeFingerprintForEntity(table); - } - - /** An entity doc as a reindex left it: current updatedAt, embedding of {@code embeddedAs}. */ - private static ObjectNode storedEntityDoc(Table current, Table embeddedAs) { - ObjectNode doc = JsonUtils.getObjectNode(); - doc.put("name", current.getName()); - doc.put("updatedAt", current.getUpdatedAt()); - doc.put("fingerprint", VectorDocBuilder.computeFingerprintForEntity(embeddedAs)); - doc.putArray("embedding").add(0.1).add(0.2).add(0.3); - doc.put("parentId", id(current)); - return doc; - } - - /** Answers an ids query like the engine: only stored ids, only the requested _source fields. */ - private void answerIdSearchesFrom(Map storedById) throws Exception { - when(mockRestClient.performRequest(any(Request.class))) - .thenAnswer( - invocation -> { - Request request = invocation.getArgument(0); - JsonNode query; - try (InputStream content = request.getEntity().getContent()) { - query = - JsonUtils.readTree(new String(content.readAllBytes(), StandardCharsets.UTF_8)); - } - ObjectNode body = JsonUtils.getObjectNode(); - var hits = body.putObject("hits").putArray("hits"); - for (JsonNode id : query.path("query").path("ids").path("values")) { - ObjectNode stored = storedById.get(id.asText()); - if (stored != null) { - ObjectNode hit = hits.addObject().put("_id", id.asText()); - ObjectNode source = hit.putObject("_source"); - query.path("_source").forEach(field -> copyField(stored, source, field.asText())); - } - } - return responseWith(body.toString()); - }); - } - - private static void copyField(ObjectNode from, ObjectNode to, String field) { - if (from.has(field)) { - to.set(field, from.get(field)); - } - } - - private static Response responseWith(String json) throws Exception { - Response response = mock(Response.class); - HttpEntity entity = mock(HttpEntity.class); - when(response.getEntity()).thenReturn(entity); - when(entity.getContent()) - .thenAnswer(inv -> new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))); - return response; - } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceChunkStagingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceChunkStagingTest.java index 9e2fe11ba177..f90bac7b089d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceChunkStagingTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceChunkStagingTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -13,25 +14,17 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Map; import java.util.Optional; -import java.util.function.Function; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatchers; import org.openmetadata.service.search.vector.client.EmbeddingClient; import os.org.opensearch.client.opensearch.OpenSearchClient; -import os.org.opensearch.client.opensearch._types.ErrorResponse; -import os.org.opensearch.client.opensearch._types.OpenSearchException; +import os.org.opensearch.client.opensearch.generic.Body; import os.org.opensearch.client.opensearch.generic.OpenSearchGenericClient; import os.org.opensearch.client.opensearch.generic.Request; import os.org.opensearch.client.opensearch.generic.Response; -import os.org.opensearch.client.opensearch.indices.GetAliasRequest; -import os.org.opensearch.client.opensearch.indices.GetAliasResponse; -import os.org.opensearch.client.opensearch.indices.OpenSearchIndicesClient; -import os.org.opensearch.client.opensearch.indices.get_alias.IndexAliases; -import os.org.opensearch.client.util.ObjectBuilder; class OpenSearchVectorServiceChunkStagingTest { @@ -40,33 +33,33 @@ class OpenSearchVectorServiceChunkStagingTest { @Test void chunkGenerationNumber_parsesGenerationStamps() { - assertEquals(1L, OpenSearchVectorService.chunkGenerationNumber(BASE + "_g1", BASE)); + assertEquals(1L, AbstractVectorIndexService.chunkGenerationNumber(BASE + "_g1", BASE)); assertEquals( 1784030121722L, - OpenSearchVectorService.chunkGenerationNumber(BASE + "_g1784030121722", BASE)); + AbstractVectorIndexService.chunkGenerationNumber(BASE + "_g1784030121722", BASE)); } @Test void chunkGenerationNumber_zeroForLegacyAndForeignNames() { - assertEquals(0L, OpenSearchVectorService.chunkGenerationNumber(BASE, BASE)); - assertEquals(0L, OpenSearchVectorService.chunkGenerationNumber(null, BASE)); - assertEquals(0L, OpenSearchVectorService.chunkGenerationNumber(BASE + "_gX", BASE)); - assertEquals(0L, OpenSearchVectorService.chunkGenerationNumber("other_index", BASE)); + assertEquals(0L, AbstractVectorIndexService.chunkGenerationNumber(BASE, BASE)); + assertEquals(0L, AbstractVectorIndexService.chunkGenerationNumber(null, BASE)); + assertEquals(0L, AbstractVectorIndexService.chunkGenerationNumber(BASE + "_gX", BASE)); + assertEquals(0L, AbstractVectorIndexService.chunkGenerationNumber("other_index", BASE)); } @Test void nextChunkGenerationName_isRunUniqueAndParseable() { // Run-unique names: a superseded run's pending promote must miss (loudly) instead of aliasing // another run's half-built index. - String name = OpenSearchVectorService.nextChunkGenerationName(BASE); + String name = AbstractVectorIndexService.nextChunkGenerationName(BASE); assertTrue(name.startsWith(BASE + "_g")); - assertTrue(OpenSearchVectorService.chunkGenerationNumber(name, BASE) > 0); + assertTrue(AbstractVectorIndexService.chunkGenerationNumber(name, BASE) > 0); } @Test void buildChunkPromoteActions_swapsAliasesAndRemovesOldTargetAtomically() throws Exception { String body = - OpenSearchVectorService.buildChunkPromoteActions( + AbstractVectorIndexService.buildChunkPromoteActions( BASE + "_g2", BASE, "dataAssetEmbeddings", BASE + "_g1"); JsonNode actions = MAPPER.readTree(body).path("actions"); assertEquals(3, actions.size()); @@ -81,7 +74,7 @@ void buildChunkPromoteActions_firstPromotionRemovesTheLegacyPhysicalIndex() thro // Migration path: the previous target IS the read-alias name (the legacy physical index). // remove_index + add in one atomic call is what makes the name hand-over gapless. String body = - OpenSearchVectorService.buildChunkPromoteActions( + AbstractVectorIndexService.buildChunkPromoteActions( BASE + "_g1", BASE, "dataAssetEmbeddings", BASE); JsonNode actions = MAPPER.readTree(body).path("actions"); assertEquals(3, actions.size()); @@ -91,7 +84,7 @@ void buildChunkPromoteActions_firstPromotionRemovesTheLegacyPhysicalIndex() thro @Test void buildChunkPromoteActions_freshInstallEmitsNoRemoval() throws Exception { String body = - OpenSearchVectorService.buildChunkPromoteActions( + AbstractVectorIndexService.buildChunkPromoteActions( BASE + "_g1", BASE, "dataAssetEmbeddings", null); JsonNode actions = MAPPER.readTree(body).path("actions"); assertEquals(2, actions.size()); @@ -108,22 +101,19 @@ void beginStagedChunkRecreate_skipsStagingWhenTheLiveTargetProbeIsIndeterminate( // run before its first record. Skipping the stage touches nothing: the orphan sweep below the // probe never runs, so the live generation it might have mistaken for an orphan is safe. OpenSearchClient client = mock(OpenSearchClient.class); - OpenSearchIndicesClient indices = mock(OpenSearchIndicesClient.class); + OpenSearchGenericClient generic = mock(OpenSearchGenericClient.class); EmbeddingClient embeddingClient = mock(EmbeddingClient.class); when(embeddingClient.embedQuery(any(String.class))).thenReturn(new float[] {0.1f}); - when(client.indices()).thenReturn(indices); - when(indices.getAlias( - ArgumentMatchers - .>>any())) - .thenThrow(new IOException("cluster unreachable")); + when(client.generic()).thenReturn(generic); + when(generic.execute(any(Request.class))).thenThrow(new IOException("cluster unreachable")); OpenSearchVectorService service = new OpenSearchVectorService(client, embeddingClient); assertNull( service.beginStagedChunkRecreate(), "an indeterminate live-target probe must read as 'not staged', not as a failure"); - // No sweep, no generation create — nothing in the cluster is touched. - verify(client, never()).generic(); + // No sweep, no generation create: the probe is the only request the cluster sees. + assertEquals(List.of("GET /" + BASE + "/_alias"), requestsSentTo(generic)); } @Test @@ -131,34 +121,23 @@ void resolveLiveChunkTarget_asksForTheChunkIndexByName_notForAClusterWideAliasLo throws IOException { // The probe must name the index in the path (GET /{base}/_alias). The alias-scoped forms // (HEAD|GET /_alias/{base}) name no index, so the cluster resolves them against _all and a - // search role confined to this deployment's * prefix is denied with a 403 — - // which opensearch-java raises before any boolean-endpoint mapping, so it can never read as - // "no alias". That 403 took down search indexing on every shared-tenancy cluster. + // search role confined to this deployment's * prefix is denied with a 403, + // which can never read as "no alias". That 403 took down search indexing on every + // shared-tenancy cluster. OpenSearchClient client = mock(OpenSearchClient.class); - OpenSearchIndicesClient indices = mock(OpenSearchIndicesClient.class); EmbeddingClient embeddingClient = mock(EmbeddingClient.class); when(embeddingClient.embedQuery(any(String.class))).thenReturn(new float[] {0.1f}); - when(client.indices()).thenReturn(indices); - - GetAliasResponse response = mock(GetAliasResponse.class); - when(response.result()).thenReturn(Map.of(BASE + "_g7", mock(IndexAliases.class))); - ArgumentCaptor>> captor = - ArgumentCaptor.captor(); - when(indices.getAlias(captor.capture())).thenReturn(response); - OpenSearchGenericClient generic = okGenericClient(); + String aliasedGeneration = "{\"" + BASE + "_g7\":{\"aliases\":{\"" + BASE + "\":{}}}}"; + OpenSearchGenericClient generic = genericClientAnsweringAliasProbe(200, aliasedGeneration); when(client.generic()).thenReturn(generic); OpenSearchVectorService service = new OpenSearchVectorService(client, embeddingClient); service.beginStagedChunkRecreate(); - GetAliasRequest request = captor.getValue().apply(new GetAliasRequest.Builder()).build(); assertEquals( - List.of(BASE), - request.index(), + "GET /" + BASE + "/_alias", + requestsSentTo(generic).getFirst(), "the chunk index must be named in the request path, not left to resolve against _all"); - assertTrue( - request.name().isEmpty(), - "naming the alias instead of the index is the cluster-wide form that 403s"); } @Test @@ -168,16 +147,12 @@ void resolveLiveChunkTarget_treatsA404AsFreshInstallRatherThanAnIndeterminatePro // stage proceeds and creates the first generation — it must not be confused with a probe that // could not be answered. OpenSearchClient client = mock(OpenSearchClient.class); - OpenSearchIndicesClient indices = mock(OpenSearchIndicesClient.class); EmbeddingClient embeddingClient = mock(EmbeddingClient.class); when(embeddingClient.embedQuery(any(String.class))).thenReturn(new float[] {0.1f}); - when(client.indices()).thenReturn(indices); - when(indices.getAlias( - ArgumentMatchers - .>>any())) - .thenThrow(notFound()); - - OpenSearchGenericClient generic = okGenericClient(); + String notFound = + "{\"error\":{\"type\":\"index_not_found_exception\",\"reason\":\"no such index\"}," + + "\"status\":404}"; + OpenSearchGenericClient generic = genericClientAnsweringAliasProbe(404, notFound); when(client.generic()).thenReturn(generic); OpenSearchVectorService service = new OpenSearchVectorService(client, embeddingClient); @@ -188,22 +163,32 @@ void resolveLiveChunkTarget_treatsA404AsFreshInstallRatherThanAnIndeterminatePro "a 404 probe means fresh install: stage the first generation. Got: " + generation); } - /** Generic client that answers every request 200/no-body, so staging can run to completion. */ - private static OpenSearchGenericClient okGenericClient() throws IOException { + /** Answers the alias probe as given and every other request 200/no-body, so staging can run. */ + private static OpenSearchGenericClient genericClientAnsweringAliasProbe(int status, String body) + throws IOException { OpenSearchGenericClient generic = mock(OpenSearchGenericClient.class); - Response response = mock(Response.class); - when(response.getStatus()).thenReturn(200); - when(response.getBody()).thenReturn(Optional.empty()); - when(generic.execute(any(Request.class))).thenReturn(response); + Body probeBody = Body.from(body.getBytes(StandardCharsets.UTF_8), "application/json"); + Response probe = response(status, Optional.of(probeBody)); + Response ok = response(200, Optional.empty()); + when(generic.execute(any(Request.class))) + .thenAnswer( + call -> call.getArgument(0).getEndpoint().endsWith("/_alias") ? probe : ok); return generic; } - private static OpenSearchException notFound() { - return new OpenSearchException( - ErrorResponse.of( - e -> - e.status(404) - .error(c -> c.type("index_not_found_exception").reason("no such index")))); + private static Response response(int status, Optional body) { + Response response = mock(Response.class); + when(response.getStatus()).thenReturn(status); + when(response.getBody()).thenReturn(body); + return response; + } + + private static List requestsSentTo(OpenSearchGenericClient generic) throws IOException { + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(generic, atLeastOnce()).execute(sent.capture()); + return sent.getAllValues().stream() + .map(request -> request.getMethod() + " " + request.getEndpoint()) + .toList(); } @Test @@ -224,7 +209,6 @@ void beginStagedChunkRecreate_skipsStagingWhenTheEmbeddingProviderIsUnavailable( assertNull( service.beginStagedChunkRecreate(), "an unavailable embedding provider must read as 'not staged', not as a failure"); - verify(client, never()).indices(); verify(client, never()).generic(); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceTest.java index 98dbaad67fb2..9edd70df9048 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/OpenSearchVectorServiceTest.java @@ -6,10 +6,10 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -23,12 +23,10 @@ import java.io.IOException; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; -import java.util.function.Function; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -47,17 +45,11 @@ import org.openmetadata.service.search.vector.client.EmbeddingClient; import org.openmetadata.service.search.vector.utils.DTOs; import org.slf4j.LoggerFactory; -import os.org.opensearch.client.json.JsonData; import os.org.opensearch.client.opensearch.OpenSearchClient; -import os.org.opensearch.client.opensearch.core.MgetRequest; -import os.org.opensearch.client.opensearch.core.MgetResponse; -import os.org.opensearch.client.opensearch.core.get.GetResult; -import os.org.opensearch.client.opensearch.core.mget.MultiGetResponseItem; import os.org.opensearch.client.opensearch.generic.Body; import os.org.opensearch.client.opensearch.generic.OpenSearchGenericClient; import os.org.opensearch.client.opensearch.generic.Request; import os.org.opensearch.client.opensearch.generic.Response; -import os.org.opensearch.client.util.ObjectBuilder; class OpenSearchVectorServiceTest { private static final ObjectMapper MAPPER = new ObjectMapper(); @@ -69,25 +61,25 @@ void contentChangesReembedWhileFilterAndMappingChangesRestampStoredVectors() { int current = VectorDocBuilder.CHUNK_DOC_VERSION; assertEquals( - OpenSearchVectorService.ChunkRefresh.NONE, + AbstractVectorIndexService.ChunkRefresh.NONE, refresh(memory, header(fingerprint, current, "Approved", "unanchored"))); - assertEquals(OpenSearchVectorService.ChunkRefresh.REEMBED, refresh(memory, null)); + assertEquals(AbstractVectorIndexService.ChunkRefresh.REEMBED, refresh(memory, null)); assertEquals( - OpenSearchVectorService.ChunkRefresh.REEMBED, + AbstractVectorIndexService.ChunkRefresh.REEMBED, refresh(memory, header("stale", current, "Approved", "unanchored"))); assertEquals( - OpenSearchVectorService.ChunkRefresh.RESTAMP, + AbstractVectorIndexService.ChunkRefresh.RESTAMP, refresh(memory, header(fingerprint, current - 1, "Approved", "unanchored"))); assertEquals( - OpenSearchVectorService.ChunkRefresh.RESTAMP, + AbstractVectorIndexService.ChunkRefresh.RESTAMP, refresh(memory, header(fingerprint, current, "Deprecated", "unanchored"))); UUID anchorId = UUID.randomUUID(); memory.setPrimaryEntity(new EntityReference().withId(anchorId).withType("table")); assertEquals( - OpenSearchVectorService.ChunkRefresh.RESTAMP, + AbstractVectorIndexService.ChunkRefresh.RESTAMP, refresh(memory, header(fingerprint, current, "Approved", "unanchored"))); assertEquals( - OpenSearchVectorService.ChunkRefresh.NONE, + AbstractVectorIndexService.ChunkRefresh.NONE, refresh(memory, header(fingerprint, current, "Approved", anchorId.toString()))); } @@ -104,15 +96,15 @@ void aNewKindRestampsTheChunksWithoutReembedding() { memory.withPinned(true); assertEquals(fingerprint, VectorDocBuilder.computeFingerprintForEntity(memory)); assertEquals( - OpenSearchVectorService.ChunkRefresh.RESTAMP, + AbstractVectorIndexService.ChunkRefresh.RESTAMP, refresh(memory, header(fingerprint, current, "Approved", "unanchored"))); memory.withPinned(false).withMemoryType(ContextMemoryType.PREFERENCE); assertEquals( - OpenSearchVectorService.ChunkRefresh.RESTAMP, + AbstractVectorIndexService.ChunkRefresh.RESTAMP, refresh(memory, header(fingerprint, current, "Approved", "unanchored"))); assertEquals( - OpenSearchVectorService.ChunkRefresh.RESTAMP, + AbstractVectorIndexService.ChunkRefresh.RESTAMP, refresh(memory, header(fingerprint, current, "Approved", "unanchored", null)), "a chunk stamped before the kind existed is restamped"); } @@ -123,7 +115,7 @@ void filterMetadataOnlyAppliesToMemoryChunks() { String fingerprint = VectorDocBuilder.computeFingerprintForEntity(table); assertEquals( - OpenSearchVectorService.ChunkRefresh.NONE, + AbstractVectorIndexService.ChunkRefresh.NONE, refresh(table, header(fingerprint, VectorDocBuilder.CHUNK_DOC_VERSION, null, null, null))); } @@ -148,7 +140,7 @@ void twoArgOverloadRefusesOntologyConceptWithoutWritingOrEmbedding() throws Exce .withDescription("A purchase") .withDeleted(false); - Logger logger = (Logger) LoggerFactory.getLogger(OpenSearchVectorService.class); + Logger logger = (Logger) LoggerFactory.getLogger(AbstractVectorIndexService.class); ListAppender appender = new ListAppender<>(); appender.start(); logger.addAppender(appender); @@ -398,7 +390,7 @@ void liveUpdateWithoutARecreateDoesNotWarnAboutMissingStagedChunks() throws Exce setField("cachedSinkTargetAt", System.currentTimeMillis()); mockOpenSearchResponse("{\"found\":false,\"hits\":{\"hits\":[]},\"errors\":false}"); - Logger logger = (Logger) LoggerFactory.getLogger(OpenSearchVectorService.class); + Logger logger = (Logger) LoggerFactory.getLogger(AbstractVectorIndexService.class); ListAppender appender = new ListAppender<>(); appender.start(); logger.addAppender(appender); @@ -419,38 +411,38 @@ void liveUpdateWithoutARecreateDoesNotWarnAboutMissingStagedChunks() throws Exce } } - private static OpenSearchVectorService.ChunkRefresh refresh( + private static AbstractVectorIndexService.ChunkRefresh refresh( org.openmetadata.schema.EntityInterface entity, - OpenSearchVectorService.ChunkHeader header) { - return OpenSearchVectorService.chunkRefresh( + AbstractVectorIndexService.ChunkHeader header) { + return AbstractVectorIndexService.chunkRefresh( entity, VectorDocBuilder.computeFingerprintForEntity(entity), header); } /** A header stamped with the kind {@link #refreshableMemory} has. */ - private static OpenSearchVectorService.ChunkHeader header( + private static AbstractVectorIndexService.ChunkHeader header( String fingerprint, int docVersion, String status, String anchorId) { return header(fingerprint, docVersion, status, anchorId, MEMORY_KIND); } - private static OpenSearchVectorService.ChunkHeader header( + private static AbstractVectorIndexService.ChunkHeader header( String fingerprint, int docVersion, String status, String anchorId, - OpenSearchVectorService.MemoryKind kind) { - return new OpenSearchVectorService.ChunkHeader( + AbstractVectorIndexService.MemoryKind kind) { + return new AbstractVectorIndexService.ChunkHeader( fingerprint, 1, docVersion, status, anchorId, kind); } - private static final OpenSearchVectorService.MemoryKind MEMORY_KIND = - OpenSearchVectorService.MemoryKind.of(refreshableMemory()); + private static final AbstractVectorIndexService.MemoryKind MEMORY_KIND = + AbstractVectorIndexService.MemoryKind.of(refreshableMemory()); private static String jsonString(String value) { return value == null ? "null" : "\"" + value + "\""; } private void setField(String name, Object value) throws ReflectiveOperationException { - java.lang.reflect.Field field = OpenSearchVectorService.class.getDeclaredField(name); + java.lang.reflect.Field field = AbstractVectorIndexService.class.getDeclaredField(name); field.setAccessible(true); field.set(vectorService, value); } @@ -1069,10 +1061,12 @@ void reindexReusesOnlyStoredEmbeddingsWhoseFingerprintIsCurrent() throws IOExcep // Stand-in for the text an older release built for the same entity: same updatedAt, other text. Table textChangedAsLastEmbedded = reuseTable("payments", "Customer payments", updatedAt).withId(textChanged.getId()); + Table unfingerprintable = reuseTable("refunds", "Refunds issued", updatedAt); answerMgetsFrom( Map.of( textId(unchanged), storedEntityDoc(unchanged, unchanged), - textId(textChanged), storedEntityDoc(textChanged, textChangedAsLastEmbedded))); + textId(textChanged), storedEntityDoc(textChanged, textChangedAsLastEmbedded), + textId(unfingerprintable), storedEntityDoc(unfingerprintable, unfingerprintable))); Map reusable = vectorService.getExistingEmbeddingsBatch( @@ -1080,12 +1074,30 @@ void reindexReusesOnlyStoredEmbeddingsWhoseFingerprintIsCurrent() throws IOExcep Map.of( textId(unchanged), () -> VectorDocBuilder.computeFingerprintForEntity(unchanged), textId(textChanged), - () -> VectorDocBuilder.computeFingerprintForEntity(textChanged))); + () -> VectorDocBuilder.computeFingerprintForEntity(textChanged), + textId(unfingerprintable), + () -> { + throw new IllegalStateException("tag without an FQN"); + }, + UUID.randomUUID().toString(), + () -> VectorDocBuilder.computeFingerprintForEntity(unchanged))); assertEquals(java.util.Set.of(textId(unchanged)), reusable.keySet()); assertEquals( VectorDocBuilder.computeFingerprintForEntity(unchanged), reusable.get(textId(unchanged)).path("fingerprint").asText()); + ArgumentCaptor sent = ArgumentCaptor.forClass(Request.class); + verify(mockGenericClient, times(2)).execute(sent.capture()); + Request fingerprints = sent.getAllValues().getFirst(); + Request embeddings = sent.getAllValues().getLast(); + assertEquals("POST", fingerprints.getMethod()); + assertEquals( + "/table_search_index/_mget?_source_includes=fingerprint", fingerprints.getEndpoint()); + assertEquals( + "/table_search_index/_mget?_source_includes=fingerprint,embedding,textToLLMContext," + + "textToEmbed,chunkIndex,chunkCount,parentId", + embeddings.getEndpoint()); + assertEquals("{\"ids\":[\"" + textId(unchanged) + "\"]}", bodyOf(embeddings)); } private static Table reuseTable(String name, String description, long updatedAt) { @@ -1113,24 +1125,34 @@ private static ObjectNode storedEntityDoc(Table current, Table embeddedAs) { } /** Answers an mget like the engine: only stored ids, only the requested _source fields. */ - @SuppressWarnings("unchecked") private void answerMgetsFrom(Map storedById) throws IOException { - when(mockClient.mget(any(Function.class), eq(JsonData.class))) + when(mockGenericClient.execute(any())) .thenAnswer( invocation -> { - Function> build = - invocation.getArgument(0); - MgetRequest request = build.apply(new MgetRequest.Builder()).build(); - List> items = new ArrayList<>(); - for (String id : request.ids()) { - ObjectNode stored = storedById.get(id); + Request request = invocation.getArgument(0); + String[] sourceFields = + request.getEndpoint().split("_source_includes=")[1].split(","); + ObjectNode answer = JsonUtils.getObjectNode(); + for (JsonNode id : MAPPER.readTree(bodyOf(request)).path("ids")) { + ObjectNode stored = storedById.get(id.asText()); + ObjectNode doc = answer.withArray("docs").addObject().put("_id", id.asText()); + doc.put("found", stored != null); if (stored != null) { - ObjectNode source = JsonUtils.getObjectNode(); - request.sourceIncludes().forEach(field -> copyField(stored, source, field)); - items.add(foundItem(request.index(), id, source)); + ObjectNode source = doc.putObject("_source"); + for (String field : sourceFields) { + copyField(stored, source, field); + } } } - return new MgetResponse.Builder().docs(items).build(); + Response response = mock(Response.class); + when(response.getStatus()).thenReturn(200); + when(response.getBody()) + .thenReturn( + Optional.of( + Body.from( + answer.toString().getBytes(StandardCharsets.UTF_8), + "application/json"))); + return response; }); } @@ -1140,18 +1162,6 @@ private static void copyField(ObjectNode from, ObjectNode to, String field) { } } - private static MultiGetResponseItem foundItem( - String index, String id, ObjectNode source) { - GetResult result = - new GetResult.Builder() - .index(index) - .id(id) - .found(true) - .source(JsonData.of(source)) - .build(); - return new MultiGetResponseItem.Builder().result(result).build(); - } - private void mockOpenSearchResponse(String responseJson) throws IOException { mockOpenSearchResponses(responseJson); } @@ -1178,7 +1188,7 @@ private void mockOpenSearchResponses(String... responseJsons) throws IOException @Test void chunkMappingUpgradeBody_omitsKnnVectorButAddsDenormalizedFields() throws Exception { - Method m = OpenSearchVectorService.class.getDeclaredMethod("buildChunkMappingUpgradeBody"); + Method m = AbstractVectorIndexService.class.getDeclaredMethod("buildChunkMappingUpgradeBody"); m.setAccessible(true); String body = (String) m.invoke(vectorService); @@ -1211,7 +1221,8 @@ void chunkMappingUpgradeBody_omitsKnnVectorButAddsDenormalizedFields() throws Ex @Test void chunkMappingUpgradeBody_mapsTheMemoryStatusAsAKeyword() throws Exception { - Method method = OpenSearchVectorService.class.getDeclaredMethod("buildChunkMappingUpgradeBody"); + Method method = + AbstractVectorIndexService.class.getDeclaredMethod("buildChunkMappingUpgradeBody"); method.setAccessible(true); JsonNode body = new ObjectMapper().readTree((String) method.invoke(vectorService)); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/StoredEmbeddingReuseTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/StoredEmbeddingReuseTest.java index 167b1181735f..52fc606c8931 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/StoredEmbeddingReuseTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/StoredEmbeddingReuseTest.java @@ -81,5 +81,14 @@ void onlyAnObjectWithAVectorAndAFingerprintIsSpliced(String json, boolean splice @Test void aMissingDocIsNotSpliced() { assertFalse(StoredEmbeddingReuse.isSpliceable(null)); + assertFalse(StoredEmbeddingReuse.isSpliceable(null, 2)); + } + + @ParameterizedTest(name = "a 2-dimensional vector, index dimension {0} -> spliceable={1}") + @CsvSource({"2,true", "3,false", "0,true", "-1,true"}) + void aVectorIsSplicedOnlyIntoAnIndexOfItsDimension(int dimension, boolean spliceable) { + JsonNode stored = JsonUtils.readTree("{\"fingerprint\":\"fp\",\"embedding\":[0.1,0.2]}"); + + assertEquals(spliceable, StoredEmbeddingReuse.isSpliceable(stored, dimension)); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorDocBuilderChunkTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorDocBuilderChunkTest.java index 56b8832c43ef..ca474711fc72 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorDocBuilderChunkTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorDocBuilderChunkTest.java @@ -113,8 +113,7 @@ void legacyEmbeddingFields_fromChunkZeroMatchBuildEmbeddingFields() { Map legacy = VectorDocBuilder.buildEmbeddingFields(table, client); Map fromChunkZero = - OpenSearchVectorService.legacyEmbeddingFields( - VectorDocBuilder.fromEntity(table, client).get(0)); + VectorDocBuilder.legacyEmbeddingFields(VectorDocBuilder.fromEntity(table, client).get(0)); assertEquals(legacy.keySet(), fromChunkZero.keySet(), "legacy payload keys must match"); for (String key : legacy.keySet()) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorIndexServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorIndexServiceTest.java deleted file mode 100644 index 4c7bebc828a8..000000000000 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorIndexServiceTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2026 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.search.vector; - -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Test; -import org.mockito.Answers; -import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; - -class VectorIndexServiceTest { - - @Test - void parameterSearchDelegatesWhenNoCompiledFilterIsPresent() { - VectorIndexService service = mock(VectorIndexService.class, Answers.CALLS_REAL_METHODS); - VectorSearchResponse expected = new VectorSearchResponse(1L, List.of()); - doReturn(expected) - .when(service) - .search(eq("query"), eq(Map.of()), eq(10), eq(2), eq(100), eq(0.4), isNull(), isNull()); - VectorSearchParameters parameters = - new VectorSearchParameters("query", Map.of(), 10, 2, 100, 0.4, null, null, null); - - assertSame(expected, service.search(parameters)); - } - - @Test - void parameterSearchRejectsACompiledFilterUnlessTheBackendImplementsIt() { - VectorIndexService service = mock(VectorIndexService.class, Answers.CALLS_REAL_METHODS); - VectorSearchParameters parameters = - new VectorSearchParameters( - "query", Map.of(), 10, 0, 100, 0.0, null, null, "{\"query\":{\"match_all\":{}}}"); - - assertThrows(UnsupportedOperationException.class, () -> service.search(parameters)); - } -}