Skip to content

feat: AI Context Platform — asset context MCP tools + multi-chunk embeddings - #29678

Merged
harshach merged 36 commits into
mainfrom
harshach/knowledge-articles-rag-signals
Jul 8, 2026
Merged

harshach merged 36 commits into
mainfrom
harshach/knowledge-articles-rag-signals

Conversation

@harshach

@harshach harshach commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator

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) and find_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-class appliedToAssets edge so they route to assets as strongly as glossary terms, and table search docs materialize the structural context (aiContext + queryable aiContextForeignKeyTargets).

Type of change:

  • Bug fix
  • New feature

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 (glossary tags.tagFQN, article HAS, pill APPLIED_TO, metric APPLIED_TO), depth-1 lineage, and observability (latest profile shape, permission-masked, + data-quality standing). AIContextMarkdown renders it as an OKF-style markdown document for LLM consumption (JSON alternative). AIContextFinder is 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/AIContextMarkdown backs every consumer, so there is no divergent assembly logic. (1) MCP tools get_asset_context / find_context / get_knowledge_content. (2) REST, on every entity — added to the EntityResource base class so all ~40 entity types inherit it: GET /v1/{entities}/{id}/context and GET /v1/{entities}/name/{fqn}/context return an OKF-style text/markdown document by default (spec-valid Open Knowledge Format v0.1 — frontmatter type+title+description+resource+tags+timestamp, structural body with # Schema) or the structured AIContext JSON via ?format=json, under per-entity VIEW_ALL authorization 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_OK exercises the endpoint across all 49 entity ITs, plus a dedicated AIContextRestIT.

collate#4789 multi-chunk fix. dataAssetEmbeddings is an alias over the entity search indices, and embeddings were partial-updated onto each entity's single doc — physically one vector per entity. VectorDocBuilder.fromEntity now emits one document per chunk (contiguous chunkIndex, shared parentId/fingerprint, KNN filter fields materialized per chunk); OpenSearchVectorService writes them to a dedicated data_asset_embeddings_chunks index (fingerprint skip → delete-stale-by-parentId → bulk index, ids {parentId}_{chunkIndex}), created idempotently with the dataAssetEmbeddings alias 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 — aiContext is a derived type (never stored), metric.appliedToAssets is relationship-backed and stripped from storage JSON, createMetric.appliedToAssets is API-only. The new aiContext/aiContextForeignKeyTargets search-mapping fields apply to new indexes and on the next reindex. The chunk index is created on first write.

Tests:

Use cases covered

  • Agent calls get_asset_context for 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 payload
  • Agent calls find_context with a business question and receives matching glossary/metric/article definitions plus the candidate assets each routes to
  • Metric created with appliedToAssets round-trips through the API and surfaces in the table's context
  • A Knowledge Article longer than one chunk is indexed as one embedding document per chunk; shrinking the body deletes orphan chunks; deleted entities stop matching KNN

Unit tests

  • Files added/updated: AIContextBuilderTest (11), AIContextMarkdownTest (5), AIContextFinderTest (4), VectorDocBuilderChunkTest (2), ListFilterTest (+1); full vector suite (193 tests) and search-index suite pass unchanged

Backend integration tests

  • I added integration tests in openmetadata-integration-tests/ for new/changed API endpoints.
  • Files added/updated: mcp/AIContextMcpIT (3/3 green vs full harness: metric-edge round-trip, get_asset_context markdown + 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

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

  1. mvn -pl openmetadata-integration-tests verify -Dit.test=AIContextMcpIT — 3/3 against the full MySQL+Elasticsearch harness with the /mcp servlet
  2. mvn -pl openmetadata-integration-tests verify -Dit.test=VectorEmbeddingIntegrationIT — 9/9 against a real OpenSearch container with DJL MiniLM embeddings
  3. mvn spotless:check-clean across all touched modules

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR is linked to a GitHub issue via Fixes above (cross-repo: openmetadata-collate#4789).
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: no migration needed — aiContext is a derived (never stored) type, metric.appliedToAssets is relationship-backed and stripped from storage JSON.
  • I have added tests (unit / integration as applicable) and listed them above.

🤖 Generated with Claude Code


Summary by Gitar

  • Metric relationship sync:
    • Added updateAppliedToAssets to MetricRepository to properly sync APPLIED_TO edges during PATCH and PUT operations.
  • Search index mapping:
    • Added aiContext and aiContextForeignKeyTargets fields to table_index_mapping.json to store structural context for search.
  • MCP tool constraints:
    • Updated tools.json to enforce required parameters for get_asset_context, find_context, and get_knowledge_content MCP tools.
  • Context memory filtering:
    • Refactored ContextMemoryResource to support primaryEntityId filtering and fixed pagination metadata loss.
  • Integration testing:
    • Added AIContextRestIT for 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/AIContextMarkdown components 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.

  • Multi-chunk embedding pipeline: VectorDocBuilder.fromEntity now emits one document per body chunk; OpenSearchVectorService writes them to a dedicated data_asset_embeddings_chunks index 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 through VectorEmbeddingHandler.
  • AIContextBuilder/AIContextFinder context graph: Per-asset context assembles structural signals (tableConstraints→FK graph, joins→join hints), attached knowledge (glossary terms, articles, pills, metrics via APPLIED_TO edge), and depth-1 lineage; AIContextFinder (Mode B) does the reverse — semantic search over knowledge entities routing back to candidate assets.
  • MetricRepository assets relationship: Adds a first-class APPLIED_TO edge from metric→asset, with correct per-entity PATCH/PUT sync via compareAndUpdate(FIELD_ASSETS, ...) and bulk-path cleanup (deleteFromMany for 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

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java New 929-line core context assembler. Structural transforms are pure functions; relationship resolvers include PBAC-checked knowledge items and knowledge budget with query-relevant excerpts. Minor: excerpt() can emit "…" when limit=0 (degenerate but harmless edge case).
openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java New Mode-B finder. resolveKnowledgeId correctly falls back to parentId for chunk docs; routeToAssets uses correct relationship directions (findTo for METRIC APPLIED_TO, findFrom for PAGE HAS). Looks correct.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java Adds first-class assets (APPLIED_TO) relationship with per-entity PATCH/PUT sync via compareAndUpdate and bulk-path cleanup for non-null asset lists. The null=unchanged semantics for storeMany (CSV path) are correctly documented and implemented.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java Major chunk-indexing implementation. normalizeChunkIndex correctly deduplicates entity-doc and chunk-0 hits during migration. getChunkHeader uses real-time GET for fingerprint staleness check (no forced refresh). cleanOrphanChunks fallback handles missing chunk-0 headers.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorDocBuilder.java Refactored to emit one doc per body chunk. buildChunkDoc materializes all KNN filter fields (entityType, deleted, tags, domains, tier). relatedTerms duplicated per chunk (intentional; field is enabled:false). Null guard added for entityType in semantic enrichers.
openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java Dual-target write wired into reindex pipeline. writeEntityChunks is only called when chunkDocs is non-empty, so stale chunks would not be cleaned during reindex if entity body text is entirely removed (live writes do handle this).
openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetAssetContextTool.java Required-param validation added; authorization uses ResourceContext(entityType, null, fqn) for per-asset PBAC. Correct.
openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindContextTool.java Vector-enabled guard added upfront; candidate assets filtered per-asset with VIEW_BASIC. Glossary-routed candidates use subject-scoped search for RBAC; relationship-routed candidates are filtered before returning.
openmetadata-service/src/main/java/org/openmetadata/service/resources/EntityResource.java Adds /context endpoints to base class (id and fqn variants), both using getResourceContextById/ByName for per-entity VIEW_ALL authorization. Correct pattern.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorEmbeddingHandler.java onEntityDeleted and onEntitySoftDeletedOrRestored now correctly handle chunk lifecycle: deleteChunks on hard/soft delete, updateEmbedding (dual-write) on restore.
openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryResource.java Adds primaryEntityId filter, resolved via parameterized SQL (no injection risk). Correctly rejects primaryEntityId with search-backed params. resolveAuthorByName now throws BadRequestException on unknown author instead of propagating EntityNotFoundException.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java getPrimaryEntityCondition uses JDBI parameterized query (:primaryEntityIdParam) so no SQL injection. Relationship ordinal is a compile-time constant. Correct.

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)
Loading
%%{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)
Loading

Comments Outside Diff (10)

  1. openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 473-506 (link)

    P1 appliedToAssets relationship changes are silently dropped on PATCH and PUT

    entitySpecificUpdate has an explicit compareAndUpdate("relatedMetrics", () -> updateRelatedMetrics(…)) that calls updateToRelationships (a diff-and-sync), but there is no analogous call for appliedToAssets. As a result:

    • PATCH: any change to appliedToAssets in the patch body is ignored because the framework's PATCH path only applies what entitySpecificUpdate explicitly handles.
    • PUT (createOrUpdate): storeRelationships adds new APPLIED_TO edges but never removes the old ones, so removing an asset from the list leaves a stale edge in entity_relationship.

    A metric created with appliedToAssets=[tableA, tableB] and then patched to [tableA] will still surface for both tables via findFrom/AIContextBuilder.findAttachedMetrics, producing incorrect AI context for tableB.

  2. openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 505-506 (link)

    P1 Add a compareAndUpdate for appliedToAssets to keep the relationship table in sync on both PATCH and PUT operations. Without this the appliedToAssets relationship 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!

  3. openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 505-506 (link)

    P1 appliedToAssets relationship never synced on PATCH or PUT

    entitySpecificUpdate calls compareAndUpdate("relatedMetrics", …) to diff and sync the relatedMetrics relationship table, but there is no equivalent call for appliedToAssets. The result is: PATCH silently drops any change to appliedToAssets; PUT adds new APPLIED_TO edges via storeRelationships but never removes old ones. A metric created with [tableA, tableB] then PATCHed to [tableA] will still surface for both tables via findAttachedMetrics → findFrom(…, APPLIED_TO, METRIC), producing incorrect AI context for tableB indefinitely.

  4. openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetAssetContextTool.java, line 201-204 (link)

    P1 security Resource-level authorization not enforced for the requested asset

    new ResourceContext<>(entityType) checks only whether the caller has VIEW_ALL on the entity type globally — it does not load or evaluate resource-level policies for the specific fqn being requested. Any user holding a type-wide VIEW_ALL on table (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 uses new 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).

  5. openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java, line 835-845 (link)

    P1 id missing from chunk docs breaks routing for METRIC and PAGE hits

    Chunk documents written to the dedicated chunk index (buildChunkDoc) carry parentId but no id field. The entity search-index documents carry both id (native field) and parentId (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") returns null. Downstream, parseId(null) returns null, and findRelated(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.

  6. openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java, line 780-791 (link)

    P1 isDuplicateChunk does not suppress the entity-doc + chunk-0 pair

    The comment says "keep the first (higher-scoring) occurrence per chunkIndex," but the guard short-circuits for null without 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, chunkIndex absent) and a chunk-0 doc (from the chunk index, chunkIndex = 0), both survive and are added to the same byParent group.

    The downstream effect in AIContextFinder.find() is concrete: every hit in response.getHits() is turned into a KnowledgeItem independently, so the same metric, page, or glossary term produces two KnowledgeItem entries in the response — one from the entity-doc hit, one from chunk-0 — consuming two slots of the caller-controlled size budget per entity. For a default size=10 query 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 to chunkIndex = 0 inside the duplicate check, comparing each member's effective chunk index the same way.

  7. openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 194-199 (link)

    P1 clearEntitySpecificRelationshipsForMany doesn't clean appliedToAssets edges

    This method is invoked by storeMany (the bulk-import / reindex path) to clear old entity-specific relationships before storing new ones. It clears RELATED_TO (relatedMetrics) on both sides, but has no corresponding cleanup for the new APPLIED_TO (appliedToAssets) edges. During a CSV import or batch reindex where a metric's appliedToAssets list shrinks, the removed asset references are never deleted from entity_relationship. Subsequent storeRelationships calls add the new edges on top of the stale ones, so findAttachedMetrics in AIContextBuilder keeps 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).

  8. openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 194-199 (link)

    P1 Bulk-path APPLIED_TO cleanup missing

    clearEntitySpecificRelationshipsForMany (called by storeMany on CSV import and batch reindex) clears RELATED_TO edges for relatedMetrics but has no corresponding cleanup for the new APPLIED_TO edges introduced by this PR. When a batch import shrinks a metric's appliedToAssets list (e.g., from [tableA, tableB] to [tableA]), the stale edge to tableB is never deleted before storeRelationships adds the new edges on top of it. findAttachedMetrics in AIContextBuilder then keeps returning the metric for tableB indefinitely, surfacing incorrect AI context for that asset.

    The fix mirrors what updateRelatedMetrics does for the single-entity path — add deleteFromMany(ids, Entity.METRIC, Relationship.APPLIED_TO, null) here.

  9. openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 194-199 (link)

    P1 Bulk-path APPLIED_TO edges never cleaned up

    clearEntitySpecificRelationshipsForMany (called by storeMany on CSV import and batch reindex) clears both sides of the RELATED_TO (relatedMetrics) relationship but has no equivalent cleanup for the new APPLIED_TO (appliedToAssets) edges. When a bulk import shrinks a metric's appliedToAssets from [tableA, tableB] to [tableA], the stale edge to tableB is never deleted before storeRelationships adds the new edges on top. findAttachedMetrics in AIContextBuilder then keeps returning the metric for tableB indefinitely, surfacing incorrect AI context for that asset.

    The fix mirrors what updateAppliedToAssets does on the single-entity path: add deleteFromMany(ids, Entity.METRIC, Relationship.APPLIED_TO, null) (null target type covers the heterogeneous asset types) here alongside the existing RELATED_TO cleanup.

  10. openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java, line 190-195 (link)

    P1 clearEntitySpecificRelationshipsForMany missing APPLIED_TO cleanup

    storeRelationships now writes APPLIED_TO edges for assets, but clearEntitySpecificRelationshipsForMany only removes RELATED_TO edges. On the bulk-import/reindex path (storeMany → clearEntitySpecificRelationshipsForMany → storeRelationships), if a metric's assets list shrinks (e.g. CSV re-import drops tableB), the old APPLIED_TO edge to tableB is never deleted before new edges are added. AIContextBuilder.findAttachedMetrics then keeps returning the metric for tableB indefinitely, surfacing incorrect AI context for that asset. Fix mirrors updateRelatedMetrics on the single-entity path: add deleteFromMany(ids, Entity.METRIC, Relationship.APPLIED_TO, null) here.

Reviews (29): Last reviewed commit: "Merge branch 'main' into harshach/knowle..." | Re-trigger Greptile

…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]>
Copilot AI review requested due to automatic review settings July 1, 2026 20:50
@github-actions

github-actions Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Jul 1, 2026
@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

✅ TypeScript Types Auto-Updated

The generated TypeScript types have been automatically updated based on JSON schema changes in this PR.

@github-actions
github-actions Bot requested a review from a team as a code owner July 1, 2026 20:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_context and find_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 structural aiContext fields 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.

Copilot AI review requested due to automatic review settings July 1, 2026 20:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 32 out of 35 changed files in this pull request and generated 4 comments.

…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]>
@github-actions

github-actions Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 63%
63.78% (72768/114087) 46.92% (42357/90264) 48.22% (13031/27023)

…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]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

harshach and others added 2 commits July 6, 2026 11:30
…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]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

The Python checkstyle failed.

Please run make py_format and py_format_check in the root of your repository and commit the changes to this PR.
You can also use pre-commit to automate the Python code formatting.

You can install the pre-commit hooks with make install_test precommit_install.

harshach and others added 2 commits July 6, 2026 11:59
…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]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

✅ TypeScript Types Auto-Updated

The generated TypeScript types have been automatically updated based on JSON schema changes in this PR.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

tomasmontielp
tomasmontielp previously approved these changes Jul 7, 2026
harshach and others added 2 commits July 7, 2026 07:14
… 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]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@sonarqubecloud

sonarqubecloud Bot commented Jul 7, 2026

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Jul 7, 2026

Copy link
Copy Markdown

@gitar-bot

gitar-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 21 resolved / 21 findings

Introduces 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

📄 openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindContextTool.java:28-42 📄 openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java:179-193 📄 openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java:88-93
The MCP framework does not centralize authorization — each tool must call authorizer.authorize() itself (e.g. GetAssetContextTool and SearchCompanyContextTool both do). FindContextTool.execute performs no authorization check at all, contradicting the PR's stated "per-tool PBAC". It returns glossary term definitions, metric definitions and Context Center article bodies, plus candidate asset FQNs. The candidate-asset routing amplifies the exposure: AIContextFinder.searchAssetsByTag calls Entity.getSearchRepository().search(request, null) with a null subject context (no RBAC filtering), and findRelated reads relationships directly from repositories with no permission check. Any authenticated MCP caller can therefore enumerate asset FQNs and knowledge content regardless of their data-access policies. Add an authorize() call and/or pass the caller's subject context into the search so results are RBAC-filtered.

✅ Bug: Metric appliedToAssets changes are dropped on update/patch

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java:76-77 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java:200-208 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java:472-486 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java:581-595
appliedToAssets is added to UPDATE_FIELDS/PATCH_FIELDS and is relationship-backed (stripped from storage JSON via getFieldsStrippedFromStorageJson). storeRelationships writes the APPLIED_TO edges only on create. On update/patch, relationship diffs are applied in MetricUpdater.entitySpecificUpdate, which handles relatedMetrics (via updateToRelationships) but has no equivalent for appliedToAssets; postUpdate also does not re-store them. Consequently, adding or removing assets from a metric via PUT/PATCH is silently ignored — the APPLIED_TO relationships are never updated and no change/version is recorded. Since find_context (metric → assets routing) and get_asset_context (assets → metrics) both depend on these edges, a metric's applied assets become effectively immutable after creation. The integration test only covers the create round-trip, so this gap is untested. Add relationship diffing for appliedToAssets in entitySpecificUpdate.

✅ Security: get_asset_context returns knowledge content without per-item PBAC

📄 openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetAssetContextTool.java:33-46 📄 openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java:346-360 📄 openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java:452-466
GetAssetContextTool authorizes only a single VIEW_ALL check on the requested asset (new OperationContext(entityType, VIEW_ALL)), then AIContextBuilder resolves and returns the full content of attached glossary terms, Context Center articles, applied metrics, and knowledge pills (ContextMemory) fetched directly via repositories with no per-item authorization. AIContextFinder's own Javadoc states knowledge pills "carry per-user visibility rules and are surfaced through the PBAC-checked Mode-A path" — but Mode A (get_asset_context) only gates on asset visibility, not on the pills/articles themselves. A user permitted to view a table but not its attached pills/articles will receive that content in the markdown/JSON payload. Consider applying per-entity authorization (or resolving each knowledge item through the PBAC-checked read path) before including its content, and only pass through items the caller may view.

✅ Quality: capList returns a backing-list view (subList) instead of a copy

📄 openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextBuilder.java:611-613
capList returns values.subList(0, max) when the list exceeds max. List.subList returns a view backed by the original list; the returned List retains a reference to the full backing list and is not structurally independent. For the current call sites the backing lists are local and not mutated afterward, so behavior is correct, but returning a live view from a utility named like a truncation helper is fragile — a future mutation of the backing list (or of the returned view) would surprise callers, and it keeps the full original list reachable. Prefer returning new ArrayList<>(values.subList(0, max)) to hand back an independent, bounded list.

✅ Edge Case: Stale entity-doc embedding not refreshed when entity has no chunks

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java:227-236
In updateEntityEmbeddings, when entityDocStale is true but VectorDocBuilder.fromEntity returns an empty list (entity has no embeddable body/description), the legacy entity-doc embedding is never updated because of the !chunkDocs.isEmpty() guard, and the entity doc keeps whatever stale embedding it had. Symmetrically, chunksStale with empty chunkDocs deletes the old chunks (correct), but the entity doc's legacy embedding is left untouched and mismatched, so the fingerprint mismatch recurs on every subsequent update, repeating the (now no-op) work each time. This is a minor edge case: if content was removed such that there are no chunks, the previously-embedded entity-doc vector lingers. Consider explicitly clearing/removing the entity-doc embedding fields when chunkDocs is empty so the doc reflects the entity's current (empty) embeddable state.

...and 16 more resolved from earlier reviews

Options

Display: compact → Showing less information.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

This branch was previously deployed

1 inactive deployment
test — 3ba8a4e2 Deployed Jul 7, 2026 by harshach via playwright-ci-postgresql (4, 6) #55191
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: AI Context Platform for agent-ready asset retrieval

4 participants