Repository navigation
feat: AI Context Platform — asset context MCP tools + multi-chunk embeddings - #29678
Conversation
…s, multi-chunk embeddings Fixes open-metadata/openmetadata-collate#4789: vector embedding discarded all body chunks except chunk 0, so long Knowledge Articles were never semantically retrievable past their opening. - AIContext spec type (generic envelope + typed assetContext) and AIContextBuilder: schema + PK/FK/frequent-joins/partitions + attached glossary terms (table+column), Context Center articles, knowledge pills, applied metrics, depth-1 lineage, and observability (latest profile shape + data-quality standing). - OKF-style markdown renderer for LLM consumption; JSON alternative. - New MCP tools: get_asset_context (Mode A: one call returns the full context for a chosen asset) and find_context (Mode B: semantic search over glossary/metrics/articles routed to candidate assets). - First-class metric→asset APPLIED_TO edge (metric.appliedToAssets on entity + create API + repository wiring). - AIContextIndex mixin materializes structural context onto table search docs (aiContext blob + queryable aiContextForeignKeyTargets). - /contextCenter/memories gains primaryEntityId filter; fixed pill resolution edge direction. - #4789 fix: VectorDocBuilder emits one doc per chunk; dedicated data_asset_embeddings_chunks index (delete-stale + bulk index, keyed parentId_chunkIndex); dual-write keeps hybrid search intact; read path dedupes (parentId, chunkIndex); chunk cleanup on delete/soft delete. Verified: 40+ new unit tests; VectorEmbeddingIntegrationIT 9/9 (real OpenSearch + DJL embeddings, incl. multi-chunk + legacy regression); AIContextMcpIT 3/3 end-to-end against the full application harness. Co-Authored-By: Claude Fable 5 <[email protected]>
✅ PR checks passedThe linked issue has a description and all required Shipping project fields set. Thanks! |
✅ TypeScript Types Auto-UpdatedThe generated TypeScript types have been automatically updated based on JSON schema changes in this PR. |
There was a problem hiding this comment.
Pull request overview
Introduces an “AI Context Platform” for retrieving per-asset, LLM-ready context via MCP tools, and fixes vector embedding indexing to support multi-chunk documents so long knowledge bodies remain semantically retrievable.
Changes:
- Adds server-side AIContext assembly/rendering (markdown + JSON) and exposes it via new MCP tools
get_asset_contextandfind_context. - Fixes collate#4789 by indexing one vector document per chunk into a dedicated chunk index (with dual-write to legacy entity-doc embedding).
- Adds metric→asset routing (
appliedToAssets) and materializes lightweight structuralaiContextfields into table search documents.
Reviewed changes
Copilot reviewed 32 out of 35 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| openmetadata-spec/src/main/resources/json/schema/type/aiContext.json | Adds AIContext schema used for server-side context projection. |
| openmetadata-spec/src/main/resources/json/schema/entity/data/metric.json | Adds appliedToAssets to metric entity schema. |
| openmetadata-spec/src/main/resources/json/schema/api/data/createMetric.json | Adds appliedToAssets to metric creation API payload. |
| openmetadata-spec/src/main/resources/elasticsearch/en/table_index_mapping.json | Adds aiContext and aiContextForeignKeyTargets fields to table mapping. |
| openmetadata-spec/src/main/resources/elasticsearch/jp/table_index_mapping.json | Adds aiContext and aiContextForeignKeyTargets fields to table mapping. |
| openmetadata-spec/src/main/resources/elasticsearch/ru/table_index_mapping.json | Adds aiContext and aiContextForeignKeyTargets fields to table mapping. |
| openmetadata-spec/src/main/resources/elasticsearch/zh/table_index_mapping.json | Adds aiContext and aiContextForeignKeyTargets fields to table mapping. |
| openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorIndexService.java | Extends vector index interface for chunk update/delete operations. |
| openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorEmbeddingHandler.java | Cleans up chunk docs on delete/soft-delete and dual-writes chunk embeddings. |
| openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorDocBuilder.java | Emits one embedding doc per chunk and materializes filter fields for chunk docs. |
| openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java | Creates/writes chunk index, bulk indexes chunk docs, and dedupes migration duplicates. |
| openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/SearchIndex.java | Auto-applies AIContextIndex mixin during search doc building. |
| openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/TableIndex.java | Enables AIContextIndex on table search documents. |
| openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/AIContextIndex.java | New mixin to materialize lightweight structural AI context into search docs. |
| openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java | Builds per-asset AIContext (structural + attached knowledge + lineage + observability). |
| openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextMarkdown.java | Renders AIContext (and “found context”) into LLM-friendly markdown. |
| openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java | Implements question-anchored routing from knowledge hits to candidate assets. |
| openmetadata-service/src/main/java/org/openmetadata/service/resources/metrics/MetricMapper.java | Maps CreateMetric appliedToAssets into Metric entity. |
| openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java | Persists/loads metric↔asset APPLIED_TO relationships and strips from storage JSON. |
| openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryResource.java | Adds primaryEntityId list filter param for pills applied to an asset. |
| openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java | Adds SQL condition for primaryEntityId via APPLIED_TO edge. |
| openmetadata-mcp/src/main/resources/json/data/mcp/tools.json | Registers new MCP tools get_asset_context and find_context. |
| openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetAssetContextTool.java | New MCP tool to fetch asset-anchored AIContext (markdown/json). |
| openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindContextTool.java | New MCP tool to find knowledge and route it to candidate assets. |
| openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java | Wires new MCP tool names to their implementations. |
| openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorDocBuilderChunkTest.java | Unit test ensuring fromEntity emits one doc per chunk. |
| openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/ListFilterTest.java | Unit test validating primaryEntityId generates APPLIED_TO filter SQL. |
| openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextBuilderTest.java | Unit tests for structural extraction and search field materialization. |
| openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextMarkdownTest.java | Unit tests for markdown rendering structure and observability sections. |
| openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextFinderTest.java | Unit tests for knowledge mapping and Mode-B markdown output. |
| openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/VectorEmbeddingIntegrationIT.java | Integration test for multi-chunk indexing and stale chunk deletion. |
| openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/AIContextMcpIT.java | End-to-end MCP IT for get_asset_context and metric appliedToAssets round-trip. |
…d_context PBAC - Reindex now populates the dedicated chunk index (issue #4789 backfill): the bulk sink writes all chunk docs when re-embedding, and backfills missing chunks (fingerprint-guarded, no-op once present) for entities whose cached embedding was reused — so one full reindex migrates an existing catalog to multi-chunk semantics. - Combined updateEntityEmbeddings embeds each chunk once and reuses chunk 0 for the legacy entity-doc partial update (N embedding calls instead of N+1); wired into the lifecycle handler, the reembed CLI, and the reindex sink. legacyEmbeddingFields extracts only the embedding payload so chunk filter fields can never clobber entity-doc tags/domains. Equivalence unit test proves chunk-0 payload matches the legacy builder output. - find_context now enforces PBAC (review feedback): VIEW_ALL on glossaryTerm/metric/page upfront, the caller's SubjectContext is threaded into the candidate-asset search so glossary-routed candidates are RBAC-filtered, and relationship-routed candidates (metric APPLIED_TO, page HAS) are permission-checked per asset. Verified: vector unit suite 194/194; VectorEmbeddingIntegrationIT 9/9 against real OpenSearch + DJL embeddings. Co-Authored-By: Claude Fable 5 <[email protected]>
…ge relevance The truncated-article excerpt was the positional first-N chars — often an intro, giving the LLM no signal about whether the substantive rule is buried further down, so it can't decide whether to fetch the full body. - Query-aware excerpts (Fix A): AIContextBuilder.withQuery(q) — threaded through get_asset_context (tool + tools.json) and the REST `?query=` on both /context endpoints. When a query is set and vectors are enabled, a truncated item's excerpt is the top query-relevant chunk (searchChunksByParent, #4789), so the snippet IS the relevant passage. - Structural preview (Fix B): with no query, the excerpt is the lead paragraph plus a `Sections:` outline of the body's markdown headings — a compact map of what the document covers. Bumped EXCERPT_CHARS 500→800. - Cap surfacing: capWithLog logs "dropped N of M articles/pills at the cap (unranked overflow)" instead of silently hard-dropping; relevance/recency ranking before the cap is the tracked follow-up. Verified: AIContextBuilderTest 16/16 (structuralPreview outline + short passthrough); AIContextMcpIT 6/6 (long article surfaces the Sections outline in its excerpt); AIContextRestIT 6/6 (?query accepted, degrades gracefully without vectors). Co-Authored-By: Claude Fable 5 <[email protected]>
…d query lookups
- BaseEntityIT.get_entityAiContext_200_OK now exercises the SDK
(getEntityService().getContext(id) / getContextByName(fqn)) instead of
an inline java.net.http.HttpClient — no per-call thread-pool leak
across the ~49 concurrent entity ITs, and it now covers the new SDK
code path (both overloads). Asserts the body starts with the YAML
frontmatter delimiter (---), not a loose contains("type:"). Guarded by
assumeTrue on getEntityService() (9 entity ITs wire it: Table, User,
Team, GlossaryTerm, TestCase, Database, DatabaseSchema, Glossary).
- structuralPreview reserves room for the Sections outline so lead +
outline stay within the excerpt limit — previously the appended
outline overran limit, debiting the knowledge budget past zero and
cascading later items to dropped content.
- buildExcerpt caps query-relevant vector lookups at 5 per bundle
(counted on attempt), falling back to the structural preview beyond
it, so a query'd context build can't fan out into dozens of sequential
ref+KNN round-trips.
Verified: AIContextBuilderTest 16/16; SDK context path green for Table,
User, GlossaryTerm, TestCase; AIContextMcpIT 6/6.
Co-Authored-By: Claude Fable 5 <[email protected]>
…estion SDK
- Java fluent SDK: getContext(id) / getContextByName(fqn) on all 47
entity fluent facades (Tables, GlossaryTerms, Dashboards, Metrics,
Domains, ...) delegating to the entity service's getContext — e.g.
Tables.getContext(id) returns the OKF-style markdown Context Profile.
- Python ingestion SDK (ometa): OpenMetadata.get_context(entity, fqn,
query=None) returns the AIContext markdown for any entity type, with
the optional query threaded to the query-relevant excerpt path.
Verified: openmetadata-sdk test suite green; Python get_context path
building covered by a unit test (asserts the /name/{fqn}/context path +
query encoding). The context endpoint itself is IT-covered via
BaseEntityIT.get_entityAiContext_200_OK (SDK service layer).
Co-Authored-By: Claude Fable 5 <[email protected]>
|
The Python checkstyle failed. Please run You can install the pre-commit hooks with |
…eturn, format - get_context used the urllib-style quote(fqn, safe=''), but ometa's quote helper takes only the FQN (it applies model_str + safe='' internally), so this dropped the safe kwarg to match get_by_name. - Narrow the return to str | None (getattr + isinstance) instead of the raw Any | str | Response the checker rejected. - ruff-format the endpoint test. Fixes the py-checkstyle (ruff format) and Static Checks (basedpyright) CI jobs. Co-Authored-By: Claude Fable 5 <[email protected]>
…tests - Rename the metric->asset field appliedToAssets to assets across metric.json, createMetric.json, MetricMapper, and MetricRepository (matching the assets naming on Domain/DataProduct). The underlying APPLIED_TO relationship is unchanged; assets stays relationship-backed and stripped from storage JSON, so no migration. - New MetricAssetsIT covers the full edge lifecycle end-to-end (7/7): create with assets, add / replace / remove-one / clear via PATCH, and referential cleanup when an asset table is hard-deleted. - AIContextMcpIT updated to the assets field/name. Verified: MetricAssetsIT 7/7, AIContextMcpIT 12/12 against the full harness. Co-Authored-By: Claude Fable 5 <[email protected]>
✅ TypeScript Types Auto-UpdatedThe generated TypeScript types have been automatically updated based on JSON schema changes in this PR. |
… import clearEntitySpecificRelationshipsForMany (the batch import path reached via updateManyEntitiesForImport → storeRelationshipsInternal) re-adds a metric's APPLIED_TO asset edges but only cleared RELATED_TO, leaving clear/re-add asymmetric. Any batch update that carried a shrunk asset list would union with stale edges instead of replacing them, and AIContextBuilder would keep routing the metric to removed assets. Clear APPLIED_TO too (null toEntity, since assets are heterogeneous) so the batch path replaces the list. Guard on assets != null: the metric CSV has no assets column, so a CSV import carries a null asset list meaning "unchanged" — an unconditional clear would silently wipe the existing edges on every import. A null list preserves; an empty list explicitly clears. Single PATCH/PUT and /bulk are unaffected — both diff assets via MetricUpdater.updateAssets (compareAndUpdate FIELD_ASSETS). Add a CSV export→import round-trip IT proving a metric's assets survive an import that omits the assets column (MetricAssetsIT, 8/8 green). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
|
Code Review ✅ Approved 21 resolved / 21 findingsIntroduces the AI Context Platform with MCP tools and REST endpoints for asset-anchored context, while resolving critical issues in metric relationship syncing, multi-chunk vector indexing, and authorization checks. All identified findings from previous review rounds have been addressed and validated through new integration tests. ✅ 21 resolved✅ Security: find_context MCP tool performs no authorization / bypasses PBAC
✅ Bug: Metric appliedToAssets changes are dropped on update/patch
✅ Security: get_asset_context returns knowledge content without per-item PBAC
✅ Quality: capList returns a backing-list view (subList) instead of a copy
✅ Edge Case: Stale entity-doc embedding not refreshed when entity has no chunks
...and 16 more resolved from earlier reviews OptionsDisplay: compact → Showing less information. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Gitar |



Describe your changes:
Fixes open-metadata/openmetadata-collate#4789
Closes #29826
I built an AI Context Platform so agents get strong, deterministic signals for SQL generation from a single call: a per-asset AIContext (schema, primary/foreign keys, frequently-joined columns, attached glossary terms, Context Center articles, knowledge pills, applied metrics, lineage, and observability), exposed via two new MCP tools —
get_asset_context(asset-anchored) andfind_context(question-anchored, routing knowledge to candidate assets). It also fixes collate#4789: the vector pipeline embedded only chunk 0 of an entity's body, so long Knowledge Articles were never semantically retrievable past their opening — the write path now indexes one document per chunk into a dedicated chunk index. Metrics gain a first-classappliedToAssetsedge so they route to assets as strongly as glossary terms, and table search docs materialize the structural context (aiContext+ queryableaiContextForeignKeyTargets).Type of change:
High-level design:
One context graph, two entry modes.
AIContextBuilder(openmetadata-service/aicontext) assembles the per-asset context server-side — structural signals from the entity (tableConstraints → FK graph, joins → empirical join hints), attached knowledge via existing relationships (glossarytags.tagFQN, articleHAS, pillAPPLIED_TO, metricAPPLIED_TO), depth-1 lineage, and observability (latest profile shape, permission-masked, + data-quality standing).AIContextMarkdownrenders it as an OKF-style markdown document for LLM consumption (JSON alternative).AIContextFinderis the reverse mode: semantic search over the knowledge layer {glossaryTerm, metric, page}, routing each hit to the candidate assets it points to. Both are thin MCP tools (get_asset_context,find_context) with per-tool PBAC, alongside the existing 19 tools.Three retrieval surfaces over one builder — MCP, REST, SDK. The same
AIContextBuilder/AIContextMarkdownbacks every consumer, so there is no divergent assembly logic. (1) MCP toolsget_asset_context/find_context/get_knowledge_content. (2) REST, on every entity — added to theEntityResourcebase class so all ~40 entity types inherit it:GET /v1/{entities}/{id}/contextandGET /v1/{entities}/name/{fqn}/contextreturn an OKF-styletext/markdowndocument by default (spec-valid Open Knowledge Format v0.1 — frontmattertype+title+description+resource+tags+timestamp, structural body with# Schema) or the structuredAIContextJSON via?format=json, under per-entityVIEW_ALLauthorization with the same per-item knowledge PBAC. (3) 2.0 Java SDK —EntityServiceBase.getContext(id)/getContextByName(fqn), inherited by every entity client. Coverage:BaseEntityIT.get_entityAiContext_200_OKexercises the endpoint across all 49 entity ITs, plus a dedicatedAIContextRestIT.collate#4789 multi-chunk fix.
dataAssetEmbeddingsis an alias over the entity search indices, and embeddings were partial-updated onto each entity's single doc — physically one vector per entity.VectorDocBuilder.fromEntitynow emits one document per chunk (contiguouschunkIndex, sharedparentId/fingerprint, KNN filter fields materialized per chunk);OpenSearchVectorServicewrites them to a dedicateddata_asset_embeddings_chunksindex (fingerprint skip → delete-stale-by-parentId → bulk index, ids{parentId}_{chunkIndex}), created idempotently with thedataAssetEmbeddingsalias attached. Dual-write keeps the legacy chunk-0 entity-doc embedding so hybrid search is untouched, and reads spanning both dedupe per(parentId, chunkIndex)— no migration cliff: pre-existing entities keep serving their entity-doc embedding until touched. Chunk docs are cleaned on hard/soft delete and re-embedded on restore.Alternatives rejected: client-side assembly in the agent (ai-platform PR #834's approach — per-consumer stitching, N round-trips, no PBAC reuse); nested chunk vectors on the entity doc (OpenSearch 2.x KNN can't query nested vectors); repointing the alias exclusively to the chunk index (would empty semantic search for existing catalogs until reindex).
Migration/compat: JSON schema changes need no data migration —
aiContextis a derived type (never stored),metric.appliedToAssetsis relationship-backed and stripped from storage JSON,createMetric.appliedToAssetsis API-only. The newaiContext/aiContextForeignKeyTargetssearch-mapping fields apply to new indexes and on the next reindex. The chunk index is created on first write.Tests:
Use cases covered
get_asset_contextfor a table and receives schema, FK graph (referred columns + cardinality), Approved glossary definitions (table+column level), linked Context Center article bodies, knowledge pills, applied metric expressions, and lineage in one markdown/JSON payloadfind_contextwith a business question and receives matching glossary/metric/article definitions plus the candidate assets each routes toappliedToAssetsround-trips through the API and surfaces in the table's contextUnit tests
AIContextBuilderTest(11),AIContextMarkdownTest(5),AIContextFinderTest(4),VectorDocBuilderChunkTest(2),ListFilterTest(+1); full vector suite (193 tests) and search-index suite pass unchangedBackend integration tests
openmetadata-integration-tests/for new/changed API endpoints.mcp/AIContextMcpIT(3/3 green vs full harness: metric-edge round-trip,get_asset_contextmarkdown + JSON end-to-end);VectorEmbeddingIntegrationIT(+multi-chunk test; 9/9 green vs real OpenSearch 3.4 + local DJL embeddings, including legacy-path regression)Ingestion integration tests
Playwright (UI) tests
Manual testing performed
mvn -pl openmetadata-integration-tests verify -Dit.test=AIContextMcpIT— 3/3 against the full MySQL+Elasticsearch harness with the/mcpservletmvn -pl openmetadata-integration-tests verify -Dit.test=VectorEmbeddingIntegrationIT— 9/9 against a real OpenSearch container with DJL MiniLM embeddingsmvn spotless:check-clean across all touched modulesUI screen recording / screenshots:
Not applicable.
Checklist:
Fixesabove (cross-repo: openmetadata-collate#4789).aiContextis a derived (never stored) type,metric.appliedToAssetsis relationship-backed and stripped from storage JSON.🤖 Generated with Claude Code
Summary by Gitar
updateAppliedToAssetstoMetricRepositoryto properly syncAPPLIED_TOedges during PATCH and PUT operations.aiContextandaiContextForeignKeyTargetsfields totable_index_mapping.jsonto store structural context for search.tools.jsonto enforce required parameters forget_asset_context,find_context, andget_knowledge_contentMCP tools.ContextMemoryResourceto supportprimaryEntityIdfiltering and fixed pagination metadata loss.AIContextRestITfor testing the new AI context API endpoints and RESTful accessibility.This will update automatically on new commits.
Greptile Summary
This PR introduces the AI Context Platform — server-side
AIContextBuilder/AIContextFinder/AIContextMarkdowncomponents that assemble a rich per-asset context payload (schema, FK graph, glossary, articles, metrics, lineage, observability) exposed via two new MCP tools (get_asset_context,find_context) and a REST endpoint on every entity type. It also fixes a long-standing vector pipeline bug (collate#4789) where only chunk 0 of a Knowledge Article's body was indexed, blocking semantic retrieval of long articles.VectorDocBuilder.fromEntitynow emits one document per body chunk;OpenSearchVectorServicewrites them to a dedicateddata_asset_embeddings_chunksindex via fingerprint-guarded bulk upsert, while dual-writing chunk 0's embedding fields to the legacy entity-doc so hybrid search is untouched. Chunk lifecycle (delete on hard/soft delete, re-embed on restore) is wired throughVectorEmbeddingHandler.AIContextBuilder/AIContextFindercontext graph: Per-asset context assembles structural signals (tableConstraints→FK graph, joins→join hints), attached knowledge (glossary terms, articles, pills, metrics viaAPPLIED_TOedge), and depth-1 lineage;AIContextFinder(Mode B) does the reverse — semantic search over knowledge entities routing back to candidate assets.MetricRepositoryassetsrelationship: Adds a first-classAPPLIED_TOedge from metric→asset, with correct per-entity PATCH/PUT sync viacompareAndUpdate(FIELD_ASSETS, ...)and bulk-path cleanup (deleteFromManyfor non-null asset lists) so stale edges don't persist across reindex or CSV import.Confidence Score: 4/5
The PR is safe to merge; all previously flagged relationship-sync and authorization issues have been addressed. The dual-write chunk pipeline is well-reasoned with fingerprint-based staleness guards and no forced refreshes on the hot path.
All the meaningful issues from earlier review rounds — APPLIED_TO edge sync on PATCH/PUT, bulk-path cleanup, entity-doc vs chunk-0 deduplication, resolveKnowledgeId fallback for chunk docs, and per-asset authorization in GetAssetContextTool — are now correctly handled. The remaining open item is a minor gap in OpenSearchBulkSink: stale chunk docs are not cleaned when an entity's body becomes entirely empty during reindex (the live-write path handles this correctly). The code is large and the dual-write pipeline has many moving parts, so a second pass from a reviewer familiar with the vector indexing layer would be valuable before merge.
OpenSearchBulkSink.java (stale chunk cleanup when chunkDocs is empty during reindex) and OpenSearchVectorService.java (dual-write, chunk fingerprint logic, and orphan healing path) warrant the closest attention.
Important Files Changed
Sequence Diagram
%%{init: {'theme': 'neutral'}}%% sequenceDiagram participant Agent participant MCP as MCP Tool Layer participant ACB as AIContextBuilder participant ACF as AIContextFinder participant Repo as EntityRepository participant OS as OpenSearchVectorService participant ChunkIdx as data_asset_embeddings_chunks Note over Agent,ChunkIdx: Mode A: get_asset_context (asset-anchored) Agent->>MCP: get_asset_context(entityType, fqn, query) MCP->>MCP: authorize(VIEW_ALL, ResourceContext(entityType, fqn)) MCP->>ACB: build() ACB->>Repo: getEntityByName(fqn) ACB->>Repo: findGlossaryTerms / findArticles / findMetrics (APPLIED_TO) ACB->>OS: searchChunksByParent(itemId, query, k) OS->>ChunkIdx: KNN query (filtered by parentId) ChunkIdx-->>OS: top-k passages OS-->>ACB: relevant excerpt ACB-->>MCP: AIContext (markdown/json) MCP-->>Agent: context payload Note over Agent,ChunkIdx: Mode B: find_context (question-anchored) Agent->>MCP: find_context(query, size) MCP->>ACF: find(query, size) ACF->>OS: search(query, CONTEXT_FILTER) OS->>ChunkIdx: KNN over glossaryTerm+metric+page ChunkIdx-->>OS: hits (id/parentId fallback) ACF->>Repo: findTo / findFrom / searchByTag (route to assets) ACF-->>MCP: FoundContext(items, candidateAssets) MCP->>MCP: filterCandidates(VIEW_BASIC per asset) MCP-->>Agent: knowledge items + candidate FQNs Note over OS,ChunkIdx: Write path (dual-target) OS->>OS: buildChunkDocs (one per body chunk) OS->>ChunkIdx: bulk upsert chunk docs (fingerprint-guarded) OS->>OS: partialUpdateEntity (chunk-0 embedding to entity doc)%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%% sequenceDiagram participant Agent participant MCP as MCP Tool Layer participant ACB as AIContextBuilder participant ACF as AIContextFinder participant Repo as EntityRepository participant OS as OpenSearchVectorService participant ChunkIdx as data_asset_embeddings_chunks Note over Agent,ChunkIdx: Mode A: get_asset_context (asset-anchored) Agent->>MCP: get_asset_context(entityType, fqn, query) MCP->>MCP: authorize(VIEW_ALL, ResourceContext(entityType, fqn)) MCP->>ACB: build() ACB->>Repo: getEntityByName(fqn) ACB->>Repo: findGlossaryTerms / findArticles / findMetrics (APPLIED_TO) ACB->>OS: searchChunksByParent(itemId, query, k) OS->>ChunkIdx: KNN query (filtered by parentId) ChunkIdx-->>OS: top-k passages OS-->>ACB: relevant excerpt ACB-->>MCP: AIContext (markdown/json) MCP-->>Agent: context payload Note over Agent,ChunkIdx: Mode B: find_context (question-anchored) Agent->>MCP: find_context(query, size) MCP->>ACF: find(query, size) ACF->>OS: search(query, CONTEXT_FILTER) OS->>ChunkIdx: KNN over glossaryTerm+metric+page ChunkIdx-->>OS: hits (id/parentId fallback) ACF->>Repo: findTo / findFrom / searchByTag (route to assets) ACF-->>MCP: FoundContext(items, candidateAssets) MCP->>MCP: filterCandidates(VIEW_BASIC per asset) MCP-->>Agent: knowledge items + candidate FQNs Note over OS,ChunkIdx: Write path (dual-target) OS->>OS: buildChunkDocs (one per body chunk) OS->>ChunkIdx: bulk upsert chunk docs (fingerprint-guarded) OS->>OS: partialUpdateEntity (chunk-0 embedding to entity doc)Comments Outside Diff (10)
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 473-506 (link)appliedToAssetsrelationship changes are silently dropped on PATCH and PUTentitySpecificUpdatehas an explicitcompareAndUpdate("relatedMetrics", () -> updateRelatedMetrics(…))that callsupdateToRelationships(a diff-and-sync), but there is no analogous call forappliedToAssets. As a result:appliedToAssetsin the patch body is ignored because the framework's PATCH path only applies whatentitySpecificUpdateexplicitly handles.storeRelationshipsadds newAPPLIED_TOedges but never removes the old ones, so removing an asset from the list leaves a stale edge inentity_relationship.A metric created with
appliedToAssets=[tableA, tableB]and then patched to[tableA]will still surface for both tables viafindFrom/AIContextBuilder.findAttachedMetrics, producing incorrect AI context fortableB.openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 505-506 (link)compareAndUpdateforappliedToAssetsto keep the relationship table in sync on both PATCH and PUT operations. Without this theappliedToAssetsrelationship table diverges from the stored entity after any update.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 505-506 (link)appliedToAssetsrelationship never synced on PATCH or PUTentitySpecificUpdatecallscompareAndUpdate("relatedMetrics", …)to diff and sync therelatedMetricsrelationship table, but there is no equivalent call forappliedToAssets. The result is: PATCH silently drops any change toappliedToAssets; PUT adds newAPPLIED_TOedges viastoreRelationshipsbut never removes old ones. A metric created with[tableA, tableB]then PATCHed to[tableA]will still surface for both tables viafindAttachedMetrics→findFrom(…, APPLIED_TO, METRIC), producing incorrect AI context fortableBindefinitely.openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetAssetContextTool.java, line 201-204 (link)new ResourceContext<>(entityType)checks only whether the caller hasVIEW_ALLon the entity type globally — it does not load or evaluate resource-level policies for the specificfqnbeing requested. Any user holding a type-wideVIEW_ALLontable(or whichever entity type they pass) can retrieve the full AI context — including the permission-masked observability profile, data quality metrics, lineage, and all attached knowledge — for any asset of that type, even if per-resource policies would otherwise deny access.Compare with
FindContextTool.canView, which correctly usesnew ResourceContext<>(asset.entityType(), null, asset.fullyQualifiedName())to verify per-resource visibility before returning each candidate. The same pattern should be applied here:new ResourceContext<>(entityType, null, fqn).openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java, line 835-845 (link)idmissing from chunk docs breaks routing for METRIC and PAGE hitsChunk documents written to the dedicated chunk index (
buildChunkDoc) carryparentIdbut noidfield. The entity search-index documents carry bothid(native field) andparentId(added by the legacy partial-update). After deduplication keeps only the first (higher-scoring) occurrence per(parentId, chunkIndex), either representation can survive — and when the chunk doc wins,hit.get("id")returnsnull. Downstream,parseId(null)returnsnull, andfindRelated(null, …)returns an empty list, so no candidate assets are produced for that METRIC or PAGE item. GLOSSARY_TERM routing is unaffected (it uses the FQN). For same-score ties between the entity-doc and chunk-0 the outcome depends on OpenSearch's internal iteration order, so the bug is non-deterministic.openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java, line 780-791 (link)isDuplicateChunkdoes not suppress the entity-doc + chunk-0 pairThe comment says "keep the first (higher-scoring) occurrence per
chunkIndex," but the guard short-circuits fornullwithout checking whether the group already contains an entity-doc representing the same chunk. The result: for every entity that has both a legacy entity-doc embedding (from the entity index,chunkIndexabsent) and a chunk-0 doc (from the chunk index,chunkIndex = 0), both survive and are added to the samebyParentgroup.The downstream effect in
AIContextFinder.find()is concrete: every hit inresponse.getHits()is turned into aKnowledgeItemindependently, so the same metric, page, or glossary term produces twoKnowledgeItementries in the response — one from the entity-doc hit, one from chunk-0 — consuming two slots of the caller-controlledsizebudget per entity. For a defaultsize=10query against a catalog where every entity has been dual-indexed, the agent receives only ~5 distinct entities instead of 10.The fix is to treat a missing
chunkIndex(entity-doc) as logically equivalent tochunkIndex = 0inside the duplicate check, comparing each member's effective chunk index the same way.openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 194-199 (link)clearEntitySpecificRelationshipsForManydoesn't cleanappliedToAssetsedgesThis method is invoked by
storeMany(the bulk-import / reindex path) to clear old entity-specific relationships before storing new ones. It clearsRELATED_TO(relatedMetrics) on both sides, but has no corresponding cleanup for the newAPPLIED_TO(appliedToAssets) edges. During a CSV import or batch reindex where a metric'sappliedToAssetslist shrinks, the removed asset references are never deleted fromentity_relationship. SubsequentstoreRelationshipscalls add the new edges on top of the stale ones, sofindAttachedMetricsinAIContextBuilderkeeps returning metrics for assets they no longer apply to.Individual PATCH/PUT is correctly handled via
compareAndUpdate(FIELD_APPLIED_TO_ASSETS, ...), but the bulk path needs the same cleanup added here — e.g.,deleteFromMany(ids, Entity.METRIC, Relationship.APPLIED_TO, null).openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 194-199 (link)clearEntitySpecificRelationshipsForMany(called bystoreManyon CSV import and batch reindex) clearsRELATED_TOedges forrelatedMetricsbut has no corresponding cleanup for the newAPPLIED_TOedges introduced by this PR. When a batch import shrinks a metric'sappliedToAssetslist (e.g., from[tableA, tableB]to[tableA]), the stale edge totableBis never deleted beforestoreRelationshipsadds the new edges on top of it.findAttachedMetricsinAIContextBuilderthen keeps returning the metric fortableBindefinitely, surfacing incorrect AI context for that asset.The fix mirrors what
updateRelatedMetricsdoes for the single-entity path — adddeleteFromMany(ids, Entity.METRIC, Relationship.APPLIED_TO, null)here.openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 194-199 (link)APPLIED_TOedges never cleaned upclearEntitySpecificRelationshipsForMany(called bystoreManyon CSV import and batch reindex) clears both sides of theRELATED_TO(relatedMetrics) relationship but has no equivalent cleanup for the newAPPLIED_TO(appliedToAssets) edges. When a bulk import shrinks a metric'sappliedToAssetsfrom[tableA, tableB]to[tableA], the stale edge totableBis never deleted beforestoreRelationshipsadds the new edges on top.findAttachedMetricsinAIContextBuilderthen keeps returning the metric fortableBindefinitely, surfacing incorrect AI context for that asset.The fix mirrors what
updateAppliedToAssetsdoes on the single-entity path: adddeleteFromMany(ids, Entity.METRIC, Relationship.APPLIED_TO, null)(null target type covers the heterogeneous asset types) here alongside the existingRELATED_TOcleanup.openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 190-195 (link)clearEntitySpecificRelationshipsForManymissingAPPLIED_TOcleanupstoreRelationshipsnow writesAPPLIED_TOedges forassets, butclearEntitySpecificRelationshipsForManyonly removesRELATED_TOedges. On the bulk-import/reindex path (storeMany→clearEntitySpecificRelationshipsForMany→storeRelationships), if a metric'sassetslist shrinks (e.g. CSV re-import dropstableB), the oldAPPLIED_TOedge totableBis never deleted before new edges are added.AIContextBuilder.findAttachedMetricsthen keeps returning the metric fortableBindefinitely, surfacing incorrect AI context for that asset. Fix mirrorsupdateRelatedMetricson the single-entity path: adddeleteFromMany(ids, Entity.METRIC, Relationship.APPLIED_TO, null)here.Reviews (29): Last reviewed commit: "Merge branch 'main' into harshach/knowle..." | Re-trigger Greptile