Skip to content
Open
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
@@ -0,0 +1,62 @@
# Metric semantic fields extend bounded generic JSON without changing concept context

- **Status:** Proposed
- **Revisions:** v1 2026-11-16 (initial)
- **Guard:** `AIContextBuilderTest`, `AIContextMarkdownTest`, `MetricContextBudgetTest`, `ConceptContextIT`, `McpMetricRelationVisibilityIT`, `MetricExpressionMappingIT`
- **Related:** #33455, ADR:2026-11-10-a-metric-concept-context-carries-what-changes-its-number

## Context

The generic metric block carries expression code and source assets but omits semantic dimensions,
measure aggregations, conditions and related FQNs. Structured-context callers need these to inspect
the metric. Concept context has a separate accepted contract that deliberately excludes dimensions,
measures and the variant hierarchy from its computation prompt.

## Decision

Add optional `dimensions`, `measures`, `filters` and related metric FQNs to
`assetContext.generic` in structured JSON. Reuse the metric schemas and the concept builder's
non-blank filter conditions. Related FQNs are distinct references already admitted to the existing
visible, Approved-or-unset, bounded concept metric knowledge list. After checking the first 50
knowledge candidates, structured metric JSON checks omitted related references in batches of 50.
It stops at the first visible, Approved-or-unset omission and sets the truncation marker.
A relation the caller cannot view does not set the marker.
Comment on lines +20 to +23

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Performance: Omitted related-metric scan is unbounded and runs a DB read per batch

In this commit, hasVisibleOmittedRelation replaced the previous single 50-reference lookahead with a loop over every omitted related reference, 50 at a time. It only stops early when it finds a visible, Approved-or-unset metric. Each batch calls containsEligibleRelatedMetric, which does a bulk repository.get(...) (find + setFieldsInBulk) and then a ViewPermissionFilter policy evaluation. Take a metric with N related metrics where the ones past the first 50 are hidden, unapproved or deleted: every structured get_asset_context call then makes about (N-50)/50 extra repository and authorization round trips. Nothing caps this. It also contradicts the PR's stated constraint of "no additional related-entity reads", and the ADR edit drops the former "up to 50 additional" bound without recording a new limit. Fix: put a hard cap on the lookahead batches (for example one or two), and once the cap is hit set semanticFieldsTruncated conservatively or leave it unasserted, as the earlier ADR wording did. Record that cap in the ADR.

Bound the number of lookahead batches:

private static final int MAX_OMITTED_RELATION_BATCHES = 1;
...
int checked = 0;
boolean eligible = false;
while (!eligible && batches.hasNext() && checked < MAX_OMITTED_RELATION_BATCHES) {
  eligible = containsEligibleMetric.test(batches.next());
  checked++;
}
return eligible;
  • Apply fix

Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for updating #33455, @pmbrull. I checked the scan cost. In your regression, 50 visible metrics are followed by 50 hidden ones and then one more visible metric. A one-batch lookahead misses that last metric. Setting semanticFieldsTruncated whenever we hit a cap would also signal an omission when every remaining metric is hidden.

I kept the visibility rule you requested. Structured JSON checks 50 references at a time and stops at the first visible, approved-or-unset omission. If none qualifies, it can read every remaining batch. Markdown skips this lookup. I updated the PR description to make that cost explicit.

Could you rerun Validate PR Metadata? Its last run predates your update, and I don’t have permission to rerun it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Gitar can change code and merge on your behalf, so it only acts on requests from people who can push. This needs Write access to this repository.


Keep `conceptContext` JSON and default concept Markdown unchanged, including its granularity,
units and parenthesized AND conjunction of all filters. The earlier accepted decision remains
in force. The existing JSON format explicitly opts into the new generic fields; legacy builder
callers and Markdown requests retain their full previous knowledge budget. The new generic JSON
fields do not opt dimensions or measures into that prompt.

Charge the serialized new semantic fields, including their JSON envelope and truncation marker,
to the existing knowledge-character budget before attached knowledge. Reuse the existing
50-item knowledge limit for each projected array. The stable knowledge-item TypeScript `Type` export is pinned by a schema title, so adding the
dimension enum does not rename an existing export. Spend space on complete filters first, then
related FQNs, dimensions and measures. Retain complete entries in source order; never clip SQL,
names or FQNs. A filter group is kept entirely or omitted entirely, because a partial conjunction
would change the definition. Set `semanticFieldsTruncated=true` when the projection drops entries
or a filter group. Clients must fetch the metric entity for the complete declarations in that case.
The original expression and source assets retain their existing shape and budget behavior.

The localized index templates add the emitted `metricExpression` field while retaining
`expression` with its old mapping. The new explicit text fields preserve the previous dynamic
`keyword` subfields (including `ignore_above: 256`), so exact-match searches remain available
on fresh indexes and existing indexes where the dynamic field is already text.

If the first expression looked like a date, the search engine may have mapped
`metricExpression.code` as `date`. An in-place mapping update then returns HTTP 400 because
the field type cannot change. After upgrading, run the Search Indexing application for the
`metric` entity with **Recreate Index** enabled. The equivalent admin request is
`POST /api/v1/apps/trigger/SearchIndexingApplication` with
`{"entities":["metric"],"recreateIndex":true}`. This rebuilds the metric documents from the
catalog into a fresh backing index with the explicit text mapping, then promotes that index.
Verify that the job succeeds and that an exact search on `metricExpression.code.keyword`
finds the original expression.

## Consequences

Structured clients can inspect semantic declarations while consumers of concept JSON and default
Markdown retain their accepted prompt contract. Consumers reading only concept context do not
automatically gain dimensions or measures. Large declarations consume the shared budget and
produce explicit partial-projection metadata; attached knowledge may become shorter or reference
only. Existing concept conditions remain complete even when their generic duplicate cannot fit.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import static org.awaitility.Awaitility.await;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
Expand All @@ -41,7 +42,10 @@
import org.openmetadata.schema.api.data.CreateTable;
import org.openmetadata.schema.api.data.CreateTableProfile;
import org.openmetadata.schema.api.data.CreateTopic;
import org.openmetadata.schema.api.data.MetricDimension;
import org.openmetadata.schema.api.data.MetricExpression;
import org.openmetadata.schema.api.data.MetricFilter;
import org.openmetadata.schema.api.data.MetricMeasure;
import org.openmetadata.schema.api.policies.CreatePolicy;
import org.openmetadata.schema.api.services.CreateDashboardService;
import org.openmetadata.schema.api.services.CreateMessagingService;
Expand Down Expand Up @@ -256,6 +260,155 @@ void metricContextReturnsExpressionAppliedTablesAndResolvedColumns() throws Exce
.isEqualTo(orders.getFullyQualifiedName() + "." + COLUMN);
}

@Test
void metricSemanticContextReachesJsonWithoutChangingConceptMarkdown() throws Exception {
final Metric related =
post("metrics", new CreateMetric().withName("related_" + suffix), Metric.class);
final Metric semantic =
post(
"metrics",
new CreateMetric()
.withName("semantic_" + suffix)
.withMetricExpression(new MetricExpression().withCode(EXPRESSION))
.withDimensions(
List.of(new MetricDimension().withName("region").withExpression("region_code")))
.withMeasures(
List.of(new MetricMeasure().withName("amount_cents").withAggregation("sum")))
.withFilters(
List.of(
new MetricFilter().withWhere("status = 'paid'"),
new MetricFilter().withWhere("amount_cents > 0"),
new MetricFilter().withWhere(" ")))
.withRelatedMetrics(List.of(related.getFullyQualifiedName())),
Metric.class);
final JsonNode context = metricContext(semantic);
final JsonNode generic = context.at("/assetContext/generic");
assertThat(generic.path("definition").asText()).isEqualTo(EXPRESSION);
assertThat(generic.at("/dimensions/0/name").asText()).isEqualTo("region");
assertThat(generic.at("/dimensions/0/expression").asText()).isEqualTo("region_code");
assertThat(generic.at("/measures/0/aggregation").asText()).isEqualTo("sum");
assertThat(generic.path("filters"))
.isEqualTo(OBJECT_MAPPER.valueToTree(List.of("status = 'paid'", "amount_cents > 0")));
assertThat(generic.path("relatedMetrics"))
.isEqualTo(OBJECT_MAPPER.valueToTree(List.of(related.getFullyQualifiedName())));

final JsonNode response =
executeMcpRequest(
McpTestUtils.createToolCallRequest(
"get_concept_context",
Map.of(
"entityType",
"metric",
"fqn",
semantic.getFullyQualifiedName(),
"format",
"json")));
final JsonNode mcpContext =
OBJECT_MAPPER.readTree(response.at("/result/content/0/text").asText());
assertThat(mcpContext.at("/assetContext/generic")).isEqualTo(generic);
final String markdown =
getResponse("metrics/name/" + semantic.getFullyQualifiedName() + "/context", authToken)
.body();
assertThat(markdown)
.doesNotContain("Dimensions", "Measures", "region_code")
.contains("(status = 'paid')\nAND (amount_cents > 0)");
}

@Test
void boundedJsonDoesNotSpendTheMarkdownKnowledgeBudget() throws Exception {
final String tail = "END_RELATED_DEFINITION";
final Metric bounded = createMetricWithOversizedSemantics(tail);
assertMetricSemanticBudget(bounded);
assertRestMarkdownKeepsRelatedDefinition(bounded, tail);
assertMcpMarkdownKeepsRelatedDefinition(bounded, tail);
}

private static Metric createMetricWithOversizedSemantics(final String tail) throws Exception {
final Metric related = createRelatedMetricWithDefinitionTail(tail);
return post(
"metrics",
new CreateMetric()
.withName("bounded_" + suffix)
.withMetricExpression(new MetricExpression().withCode(EXPRESSION))
.withDimensions(oversizedMetricDimensions())
.withRelatedMetrics(List.of(related.getFullyQualifiedName())),
Metric.class);
}

private static Metric createRelatedMetricWithDefinitionTail(final String tail) throws Exception {
return post(
"metrics",
new CreateMetric()
.withName("bounded_related_" + suffix)
.withDescription("Related metric grounding. ".repeat(40) + tail),
Metric.class);
}

private static List<MetricDimension> oversizedMetricDimensions() {
return IntStream.range(0, 60)
.mapToObj(
(final var index) ->
new MetricDimension()
.withName("region_" + index + "_" + "x".repeat(90))
.withExpression("COALESCE(region_code, 'unknown')")
.withDescription("Dimension explanation. ".repeat(5)))
.toList();
}

private static void assertMetricSemanticBudget(final Metric bounded) throws Exception {
final JsonNode generic = metricContext(bounded).at("/assetContext/generic");
assertThat(generic.path("semanticFieldsTruncated").asBoolean()).isTrue();
assertThat(generic.path("dimensions").size()).isBetween(1, 50);
final ObjectNode semanticFields = generic.deepCopy();
semanticFields.remove(List.of("fields", "definition", "sourceAssets"));
assertThat(semanticFields.toString().length()).isLessThanOrEqualTo(8000);
}

private static void assertRestMarkdownKeepsRelatedDefinition(
final Metric bounded, final String tail) throws Exception {
final HttpResponse<String> rest =
getResponse("metrics/name/" + bounded.getFullyQualifiedName() + "/context", authToken);
assertThat(rest.statusCode()).isEqualTo(200);
assertThat(rest.body()).contains(tail).doesNotContain("Dimensions");
}

private void assertMcpMarkdownKeepsRelatedDefinition(final Metric bounded, final String tail)
throws Exception {
for (final Map<String, Object> request :
List.of(conceptMarkdownRequest(bounded), entityDetailsMarkdownRequest(bounded))) {
assertMcpMarkdownContainsDefinition(request, tail);
}
}

private static Map<String, Object> conceptMarkdownRequest(final Metric bounded) {
return McpTestUtils.createToolCallRequest(
"get_concept_context",
Map.of("entityType", "metric", "fqn", bounded.getFullyQualifiedName()));
}

private static Map<String, Object> entityDetailsMarkdownRequest(final Metric bounded) {
return McpTestUtils.createToolCallRequest(
"get_entity_details",
Map.of(
"entityType",
"metric",
"fqn",
bounded.getFullyQualifiedName(),
"include",
List.of("context")));
}

private void assertMcpMarkdownContainsDefinition(
final Map<String, Object> request, final String tail) throws Exception {
final JsonNode response = executeMcpRequest(request);
assertThat(response.at("/result/isError").asBoolean(false)).isFalse();
final JsonNode body = OBJECT_MAPPER.readTree(response.at("/result/content/0/text").asText());
final JsonNode markdown =
body.has("context") ? body.at("/context/content") : body.path("content");
assertThat(markdown.isTextual()).isTrue();
assertThat(markdown.asText()).contains(tail).doesNotContain("Dimensions");
}

@Test
void mcpExposesSameConceptBundleAndChecksAssetPermissions() throws Exception {
Map<String, Object> call =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.databind.JsonNode;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
Expand Down Expand Up @@ -34,6 +36,7 @@
class McpMetricRelationVisibilityIT extends McpTestBase {

private static final String RESTRICTED_TAG = "PII.Sensitive";
private static final String GET_ENTITY_DETAILS = "get_entity_details";

private static Metric hiddenParent;
private static Metric hiddenRelated;
Expand All @@ -45,6 +48,7 @@ class McpMetricRelationVisibilityIT extends McpTestBase {
private static MetricGroup hiddenGroup;
private static MetricGroup visibleGroup;
private static String restrictedToken;
private static String viewBasicOnlyDeniedToken;
private static String suffix;

@BeforeAll
Expand Down Expand Up @@ -88,6 +92,8 @@ static void setup() throws Exception {
visibleMember.getFullyQualifiedName())),
MetricGroup.class);
restrictedToken = bearerFor(createRestrictedUser(suffix));
viewBasicOnlyDeniedToken =
bearerFor(createRestrictedUser("basic_" + suffix, List.of(MetadataOperation.VIEW_BASIC)));
}

@Test
Expand All @@ -113,6 +119,69 @@ void metricRead_omitsTheRelationsTheCallerCannotView() throws Exception {
.doesNotContain(hiddenParent.getName(), hiddenChild.getName(), hiddenRelated.getName());
}

@Test
void metricContextOnlyNamesRelatedMetricsTheCallerCanView() throws Exception {
final String path = "metrics/name/" + current.getFullyQualifiedName() + "/context?format=json";
final HttpResponse<String> unrestrictedResponse = getResponse(path, authToken);
assertThat(unrestrictedResponse.statusCode()).isEqualTo(200);
final JsonNode unrestricted = OBJECT_MAPPER.readTree(unrestrictedResponse.body());
assertThat(unrestricted.at("/assetContext/generic/relatedMetrics/0").asText())
.isEqualTo(hiddenRelated.getFullyQualifiedName());

final HttpResponse<String> restrictedResponse = getResponse(path, restrictedToken);
assertThat(restrictedResponse.statusCode()).isEqualTo(200);
final JsonNode restricted = OBJECT_MAPPER.readTree(restrictedResponse.body());
assertThat(restricted.at("/assetContext/generic/relatedMetrics").isMissingNode()).isTrue();
assertThat(restricted.toString()).doesNotContain(hiddenRelated.getFullyQualifiedName());
assertThat(
getResponse(
"metrics/name/"
+ hiddenRelated.getFullyQualifiedName()
+ "/context?format=json",
restrictedToken)
.statusCode())
.isEqualTo(403);
}

@Test
void metricContextChecksRelatedViewBasicOnBothMcpRoutes() throws Exception {
assertThat(
getResponse(
"metrics/name/"
+ hiddenRelated.getFullyQualifiedName()
+ "/context?format=json",
viewBasicOnlyDeniedToken)
.statusCode())
.as("the fixture permits ViewAll while denying ViewBasic on the related metric")
.isEqualTo(200);
for (final String tool : List.of("get_concept_context", GET_ENTITY_DETAILS)) {
final Map<String, Object> arguments =
new HashMap<>(
Map.of(
"entityType",
Entity.METRIC,
"fqn",
current.getFullyQualifiedName(),
"format",
"json"));
if (GET_ENTITY_DETAILS.equals(tool)) {
arguments.put("include", List.of("context"));
}
final Map<String, Object> request = McpTestUtils.createToolCallRequest(tool, arguments);
JsonNode unrestricted = callTool(request, authToken);
JsonNode restricted = callTool(request, viewBasicOnlyDeniedToken);
if (GET_ENTITY_DETAILS.equals(tool)) {
unrestricted = unrestricted.path("context");
restricted = restricted.path("context");
}
assertThat(unrestricted.at("/assetContext/generic/relatedMetrics/0").asText())
.isEqualTo(hiddenRelated.getFullyQualifiedName());
assertThat(restricted.path("assetContext").isObject()).isTrue();
assertThat(restricted.at("/assetContext/generic/relatedMetrics").isMissingNode()).isTrue();
assertThat(restricted.toString()).doesNotContain(hiddenRelated.getFullyQualifiedName());
}
}

@Test
void metricRead_omitsAGroupTheCallerCannotView() throws Exception {
JsonNode unrestricted =
Expand Down Expand Up @@ -244,8 +313,12 @@ private static Metric createMetric(CreateMetric create) throws Exception {
* metric groups tagged as restricted are hidden from it.
*/
private static User createRestrictedUser(String suffix) throws Exception {
List<MetadataOperation> viewOperations =
List.of(MetadataOperation.VIEW_BASIC, MetadataOperation.VIEW_ALL);
return createRestrictedUser(
suffix, List.of(MetadataOperation.VIEW_BASIC, MetadataOperation.VIEW_ALL));
}

private static User createRestrictedUser(
final String suffix, final List<MetadataOperation> viewOperations) throws Exception {
Rule allowCatalog =
new Rule()
.withName("AllowCatalog")
Expand Down
Loading