Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,20 @@ 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
Expand All @@ -344,13 +358,13 @@ public void updateEntityEmbeddings(
}

Map<String, Object> embeddingFields = generateEmbeddingFields(entity, ontologyBody);
if (ontologyBody == null) {
partialUpdateEntity(entityIndexName, entityId, embeddingFields);
} else {
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,20 @@ public void updateEntityEmbeddings(
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));
Expand All @@ -378,7 +392,7 @@ public void updateEntityEmbeddings(
? rebuildChunksReusingEmbeddings(
entity, chunkIndexName, parentId, header, ontologyBody)
: VectorDocBuilder.fromEntity(entity, embeddingClient, ontologyBody);
if (ontologyBody == null) {
if (!OntologyTermSearch.isTerm(type)) {
if (refresh != ChunkRefresh.NONE) {
replaceChunks(chunkIndexName, parentId, chunkDocs, previousCount(header));
mirrorToStagedGeneration(parentId, chunkDocs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1855,6 +1855,13 @@ public Integer reembed(

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) {
Expand Down Expand Up @@ -2062,6 +2069,15 @@ private int calculateReembedTotalBatches(int batchSize, Map<String, Integer> ent
int totalBatches = 0;
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 ADR
// 2026-11-23). The reembed CLI embeds raw working rows, so it must skip term types.
LOG.info(
"Skipping ontology term type {} in re-embed; rebuild its embeddings via reindex",
entityType);
continue;
}
try {
int totalRecords = Entity.getEntityRepository(entityType).getDao().listTotalCount();
entityTotals.put(entityType, totalRecords);
Expand All @@ -2074,6 +2090,17 @@ private int calculateReembedTotalBatches(int batchSize, Map<String, Integer> ent
return totalBatches;
}

/**
* Whether the {@code reembed} CLI may embed an entity type from its raw working row. Ontology
* terms are excluded: their embeddings are rebuilt only via the release-aware reindex path,
* which publishes terms through the gated writer that keeps drafts out of search (ADR
* 2026-11-23). The 2-arg {@code updateEntityEmbeddings} overload refuses terms defensively as
* well, so a term that reached {@code reembed} would be skipped at write time regardless.
*/
static boolean isReembedableEntityType(String entityType) {
return !org.openmetadata.service.search.OntologyTermSearch.isTerm(entityType);
}

private int calculateReembedNumberOfBatches(int totalRecords, int batchSize) {
if (totalRecords <= 0 || batchSize <= 0) {
return 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
import static org.mockito.Mockito.verify;
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 com.fasterxml.jackson.databind.node.ObjectNode;
import es.co.elastic.clients.elasticsearch.ElasticsearchClient;
Expand All @@ -33,12 +37,16 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
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.utils.JsonUtils;
import org.openmetadata.service.Entity;
import org.openmetadata.service.search.vector.client.EmbeddingClient;
import org.openmetadata.service.search.vector.utils.DTOs;
import org.openmetadata.service.security.policyevaluator.SubjectContext;
import org.slf4j.LoggerFactory;

class ElasticSearchVectorServiceTest {

Expand Down Expand Up @@ -163,6 +171,46 @@ void searchEmbedsTheQueryAsAQueryNotADocument() throws Exception {
verify(mockEmbeddingClient, never()).embed("test query");
}

/**
* The 2-arg {@code updateEntityEmbeddings} overload must refuse ontology terms: the
* release-aware writer needs the published release-snapshot body, and embedding from the mutable
* working (draft) row would publish drafts into search with no publication check. Manual term
* reindexing goes through the release-aware bulk writer (reindex). Mirrors the OpenSearch fix.
*/
@Test
void twoArgOverloadRefusesOntologyConceptWithoutWritingOrEmbedding() throws Exception {
EntityInterface.CANONICAL_ENTITY_NAME_MAP.putIfAbsent(
"ontologyconcept", Entity.ONTOLOGY_CONCEPT);
OntologyConcept term =
new OntologyConcept()
.withId(UUID.randomUUID())
.withName("order")
.withFullyQualifiedName("shop.order")
.withDescription("A purchase")
.withDeleted(false);

Logger logger = (Logger) LoggerFactory.getLogger(ElasticSearchVectorService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
vectorService.updateEntityEmbeddings(term, "entityIndex");

verify(mockRestClient, never()).performRequest(any(Request.class));
verify(mockEmbeddingClient, never()).embed(any(String.class));
assertTrue(
appender.list.stream()
.anyMatch(
event ->
event.getLevel() == Level.WARN
&& event.getFormattedMessage().contains("release-aware reindex path")),
"must warn that term rebuilds go through the release-aware path");
} finally {
logger.detachAppender(appender);
appender.stop();
}
}

@Test
void testThresholdFilteringRemovesLowScoreResults() throws Exception {
String esResponse =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
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.verify;
import static org.mockito.Mockito.when;

Expand All @@ -31,9 +32,12 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.openmetadata.schema.EntityInterface;
import org.openmetadata.schema.entity.context.ContextMemory;
import org.openmetadata.schema.entity.context.ContextMemoryStatus;
import org.openmetadata.schema.entity.context.ContextMemoryType;
import org.openmetadata.schema.entity.data.OntologyConcept;
import org.openmetadata.schema.entity.data.OntologyProperty;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.schema.type.EntityReference;
import org.openmetadata.schema.utils.JsonUtils;
Expand Down Expand Up @@ -123,6 +127,93 @@ void filterMetadataOnlyAppliesToMemoryChunks() {
refresh(table, header(fingerprint, VectorDocBuilder.CHUNK_DOC_VERSION, null, null, null)));
}

/**
* The 2-arg {@code updateEntityEmbeddings} overload (used only by the {@code reembed} CLI) must
* refuse ontology terms: the release-aware writer needs the published release-snapshot body,
* and embedding from the mutable working (draft) row would publish drafts, deprecated, and
* not-in-active-release terms straight into the searchable ontology chunk index. Manual term
* reindexing goes through the release-aware bulk writer (reindex), which passes the body into the
* 3-arg overload. This is the regression for the {@code reembed} draft-leak bug.
*/
@Test
void twoArgOverloadRefusesOntologyConceptWithoutWritingOrEmbedding() throws Exception {
EntityInterface.CANONICAL_ENTITY_NAME_MAP.putIfAbsent(
"ontologyconcept", Entity.ONTOLOGY_CONCEPT);
when(mockEmbeddingClient.isAvailable()).thenReturn(true);
OntologyConcept term =
new OntologyConcept()
.withId(UUID.randomUUID())
.withName("order")
.withFullyQualifiedName("shop.order")
.withDescription("A purchase")
.withDeleted(false);

Logger logger = (Logger) LoggerFactory.getLogger(OpenSearchVectorService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
vectorService.updateEntityEmbeddings(term, "entityIndex");

// No chunk write, no entity-doc partial update, and crucially no embedding provider call:
// the guard refuses before building chunk docs, so drafts are never paid for or published.
verify(mockGenericClient, never()).execute(any());
verify(mockEmbeddingClient, never()).embed(any(String.class));
assertTrue(
appender.list.stream()
.anyMatch(
event ->
event.getLevel() == Level.WARN
&& event.getFormattedMessage().contains("release-aware reindex path")),
"must warn that term rebuilds go through the release-aware path");
} finally {
logger.detachAppender(appender);
appender.stop();
}
}

/** The refusal must cover both ontology term types (concept and property). */
@Test
void twoArgOverloadRefusesOntologyPropertyWithoutWritingOrEmbedding() throws Exception {
EntityInterface.CANONICAL_ENTITY_NAME_MAP.putIfAbsent(
"ontologyproperty", Entity.ONTOLOGY_PROPERTY);
when(mockEmbeddingClient.isAvailable()).thenReturn(true);
OntologyProperty term =
new OntologyProperty()
.withId(UUID.randomUUID())
.withName("code")
.withFullyQualifiedName("shop.code")
.withDescription("An order code")
.withDeleted(false);

vectorService.updateEntityEmbeddings(term, "entityIndex");

verify(mockGenericClient, never()).execute(any());
verify(mockEmbeddingClient, never()).embed(any(String.class));
}

/**
* A non-term entity passed to the 2-arg overload is unaffected: it still writes its chunks and
* entity-doc embedding. Guards against an over-broad fix that would skip every entity.
*/
@Test
void twoArgOverloadStillWritesNonTermEntities() throws Exception {
when(mockEmbeddingClient.isAvailable()).thenReturn(true);
when(mockEmbeddingClient.embed(any(String.class))).thenReturn(new float[] {0.1f, 0.2f, 0.3f});
setField("chunkIndexEnsured", true);
mockOpenSearchResponse("{\"found\":false,\"hits\":{\"hits\":[]},\"errors\":false}");

vectorService.updateEntityEmbeddings(
new Table()
.withId(UUID.randomUUID())
.withName("orders")
.withFullyQualifiedName("svc.db.sch.orders")
.withDescription("orders"),
"entityIndex");

assertFalse(capturedBulkTargets().isEmpty(), "a non-term entity must still write its chunks");
}

/** A recreate in flight would otherwise promote the chunks it copied before this update. */
@Test
void liveUpdateDuringARecreateAlsoRewritesTheStagedGeneration() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.openmetadata.service.util;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.openmetadata.service.Entity;

/**
* Pins the {@code reembed} CLI's term-type exclusion. Ontology term embeddings are rebuilt only via
* the release-aware reindex path; the {@code reembed} CLI must skip them. The 2-arg {@code
* updateEntityEmbeddings} overload refuses terms defensively as well, so this predicate and the
* vector-service guard are belt-and-braces.
*/
class OpenMetadataOperationsReembedEligibilityTest {

@Test
void ontologyConceptsAndPropertiesAreNotReembeddable() {
assertFalse(
OpenMetadataOperations.isReembedableEntityType(Entity.ONTOLOGY_CONCEPT),
"ontologyConcept must be rebuilt via the release-aware reindex path, not reembed");
assertFalse(
OpenMetadataOperations.isReembedableEntityType(Entity.ONTOLOGY_PROPERTY),
"ontologyProperty must be rebuilt via the release-aware reindex path, not reembed");
}

@Test
void dataAssetEntitiesRemainReembeddable() {
for (String type :
new String[] {"table", "glossaryTerm", "chart", "dashboard", "topic", "contextMemory"}) {
assertTrue(
OpenMetadataOperations.isReembedableEntityType(type),
type + " must still be re-embeddable; only ontology terms are excluded");
}
}

@Test
void isReembedableEntityTypeIsCaseInsensitiveForTerms() {
// OntologyTermSearch.isTerm uses equalsIgnoreCase; the CLI relies on the same casing
// AvailableEntityTypes.LIST declares, but guard against a caller passing a variant.
assertFalse(OpenMetadataOperations.isReembedableEntityType("OntologyConcept"));
assertFalse(OpenMetadataOperations.isReembedableEntityType("ONTOLOGYPROPERTY"));
}
}
Loading