Skip to content

Fixes 33455: Include bounded metric semantics in JSON AI context - #37992

Open
iamkiayun wants to merge 7 commits into
open-metadata:mainfrom
iamkiayun:fix/33455-metric-json-context
Open

iamkiayun wants to merge 7 commits into
open-metadata:mainfrom
iamkiayun:fix/33455-metric-json-context

Conversation

@iamkiayun

@iamkiayun iamkiayun commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Describe your changes:

Fixes #33455

Structured JSON context for a metric now includes its declared dimensions, measures, filter conditions, and visible related metric FQNs in assetContext.generic. This lets callers inspect how to slice the metric without fetching its complete entity. The existing expression and source assets retain their behavior.

Current validation

On c2667e96c, 197 focused unit tests and 34 PostgreSQL/OpenSearch integration tests passed. The earlier database and search combinations are recorded below.

Type of change:

  • Improvement

High-level design:

  • Reuse the metric dimension/measure schemas and the existing extraction of nonblank filter conditions. REST JSON context and both MCP JSON context routes opt into the new generic fields.

  • Preserve the separate concept-context contract from merged AI context: a metric concept carries its filters, granularity and unit #37419 and its accepted ADR: definition, bindings, filters, granularity and unit. Dimensions, measures, metric type and variant hierarchy remain excluded from concept context. Default Markdown and its knowledge budget remain unchanged; filters still render as one conjunction with each condition parenthesized and joined by AND.

  • Charge the new serialized semantic projection to the existing 8,000-character knowledge-content budget before attached knowledge. Reuse the existing 50-item cap for each array. Keep complete values; retain a filter conjunction entirely or omit it entirely. Mark omitted declarations with semanticFieldsTruncated=true. This is not a size cap on the complete response.

  • Related metrics

    Structured JSON returns up to 50 related metric names from the existing visible, Approved-or-unset knowledge list. To decide whether another eligible metric was omitted, the server checks the remaining references in batches of 50. Each batch can require a database read and permission checks. The scan stops at the first eligible omission or after the last batch. When every remaining metric is hidden or ineligible, the server checks them all and leaves the relationship truncation flag unset. Markdown requests skip this scan.

  • Add explicit metricExpression mappings in all five locales while retaining the old expression mapping. Preserve the dynamic text fields' .keyword subfields and ignore_above: 256 on fresh indexes and mapping updates. Java/Python models and both affected committed TypeScript outputs were regenerated; existing TypeScript exports and enum definitions are preserved.

  • No relational migration is needed for optional response fields. Normal index creation/mapping update consumes the additive search resources. The new structural-context ADR is proposed and does not supersede the accepted concept ADR.

Design question for review: the implementation shares the existing character budget with attached knowledge, prioritizing complete filters, related FQNs, dimensions and measures before knowledge bodies. This can shorten attached knowledge in structured JSON responses. Is that allocation the desired policy, or should structural declarations receive a separate bounded allocation? The current choice honors the issue's existing-budget constraint; it is a proposal, and no maintainer agreement is claimed. The ADR remains Proposed. This is a character budget, not a measured token limit.

Tests:

Use cases covered

Null/empty declarations, semantics without an expression, distinct visible related FQNs, complete-entry and item-count bounds, atomic filter conjunctions, unchanged default Markdown knowledge, restricted-viewer REST/MCP responses, old dynamic mappings, legacy documents, and fresh-index exact searches.

Earlier unit test results

  • Added/updated regression tests for the changed logic.
  • 179 distinct focused cases passed, with zero failures, errors or skips: AIContextBuilderTest (59), AIContextMarkdownTest (32), ConceptContextBuilderTest (23), ConceptContextMarkdownTest (5), MetricContextBudgetTest (6), MetricIndexTest (9), GetConceptContextToolTest (3), and GetEntityToolTest (42).
  • The final evidence combines 170 unchanged cases from the complete focused run with the nine strengthened mapping cases rerun after the last mapping-resource refinement. It does not claim another all-179 run after that refinement.
  • Changed-class coverage percentage was not measured; no 90% coverage claim is made.

Earlier backend integration test results

  • Added/updated integration tests for the affected responses and search mapping.
Runtime Selected classes Result
MySQL 8.3.0 / OpenSearch 3.4.0 ConceptContextIT (24), McpMetricRelationVisibilityIT (7), MetricExpressionMappingIT (2) 33 passed; 0 failures/errors/skips
PostgreSQL 15 / OpenSearch 3.4.0 Same three classes 33 passed; 0 failures/errors/skips
MySQL 8.3.0 / Elasticsearch 9.3.0 Same three classes 33 passed; 0 failures/errors/skips

The earlier cloud attempt was blocked before tests by missing /proc/self/coredump_filter. That runtime-specific blocker was resolved by running the focused tests on the local Mac with OrbStack/Docker on 2026-11-17. Elasticsearch 9.3.0 and MySQL 8.3.0 startup/version evidence was captured. Fresh Failsafe XML contains exactly 33 testcase elements (24 + 7 + 2), with zero failures, errors or skips; the successful serial run completed in 154.621 seconds. Host Java 21.0.9 and Maven 3.9.11 were used with search-it, a 384 MiB Maven heap, a verified 1 GiB test heap, two CPUs and disk-backed MySQL test data. No source, Docker settings, native/security checks or runtime permissions were changed. All task containers were cleaned up, preserving existing workloads.

These are focused results, not full repository suites. The three selected classes now cover the tested Elasticsearch response, authorization and mapping scenarios. The full impacted integration/unit plan, broader Elasticsearch client/mapping behavior, UI/Playwright, nightly/scale, downstream builds, and coverage measurement remain unrun. Ordinary PRs skip the MySQL/Elasticsearch jobs; the focused Elasticsearch evidence above comes from the local run, not a green or skipped CI check.

The earlier unit and OpenSearch tests ran on base 930926a86ca8622cd30356706f5b5c7e9cd93afa plus the local patch. The successful local Elasticsearch run used a clean checkout of exact PR commit bcaab65b53c605a9ee1903bbb3cb12ee92dc4afc. At 2026-11-17 14:06 UTC, the patch applied cleanly to upstream main b605048058082fef7a857c4803d93df3a18e2297, with no upstream changes in its 21 paths. This is an applicability check, not a rebase or test run on that newer main. The recorded source hashes match commit bcaab65b53c605a9ee1903bbb3cb12ee92dc4afc; the commit preserves the exact tested patch.

Ingestion integration tests

Not applicable to connector behavior. Shared Python model generation, freshness, normal imports and a JSON round-trip passed. No ingestion integration suite was run.

Playwright (UI) tests

Not applicable to rendered UI behavior; the two UI changes are regenerated shared TypeScript types. Strict type checks of those files passed. No full UI build or Playwright suite was run.

No Playwright execution claimed.

Visual regression baselines

Not applicable: no rendering behavior changed.

Manual testing performed

The response and authorization checks used the real embedded server, database and OpenSearch through automated integration tests. Spotless checks passed across the service, MCP and integration modules. Schema fixtures (7 valid and 7 invalid), five-locale additive mapping checks, generated-model freshness, ADR lint, impact-map ownership, whitespace and patch checks passed. No additional manual UI testing is claimed.

UI screen recording:

Not applicable: backend context/search behavior with generated client types only.

Checklist:

  • Read the repository contribution guidance and official contribution guide.

  • Title follows Fixes <issue-number>: <short explanation> and the body links the existing issue.

  • Documented the response contract, ordering and truncation policy in the proposed ADR.

  • UI recording is not applicable to this backend change with generated client types only.

  • Added and listed the relevant unit and backend integration tests.

  • Explained why no relational migration is needed for the schema change.

  • Added a proposed decision record for the generic JSON contract and preserved the accepted concept-context policy.

  • Completed the focused MySQL 8.3.0 / Elasticsearch 9.3.0 run on the local Mac: 33 fresh cases passed, zero failures/errors/skips, on exact PR commit bcaab65b53c605a9ee1903bbb3cb12ee92dc4afc.

  • Complete the full impacted plan required for merge readiness.

  • Measure changed-class coverage against the repository target (not run).

  • Completed fresh self-review of commit bcaab65b53c605a9ee1903bbb3cb12ee92dc4afc against REVIEW.md: no blocking findings or nits; changed-source test map and saved XML evidence checked. This does not claim the unrun validation above.

RetriggerView in GreptileConfidence Score: 5/5

The reviewed changes appear safe to merge; no blocking issues were found.

Summary

Adds bounded metric declarations to structured JSON context while preserving concept context and default Markdown behavior.

  • Metric JSON context shows its dimensions, measures, filters, and visible related metrics.
  • Metric expression fields keep text and exact-match search across locales.
  • Ontology graph fixture helpers are removed.

No new actionable issues found. The earlier Java style findings are addressed.

Reviews (7) · Last reviewed commit: "Remove orphaned ontology graph mock" · Reviewed by Greptile

@iamkiayun
iamkiayun marked this pull request as ready for review November 17, 2026 14:40
@iamkiayun
iamkiayun requested a review from a team as a code owner November 17, 2026 14:40
@iamkiayun
iamkiayun requested a review from harshach November 17, 2026 14:40
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

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

@iamkiayun
iamkiayun requested a review from a team as a code owner November 18, 2026 15:05
@greptile-apps

greptile-apps Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@iamkiayun

Copy link
Copy Markdown
Contributor Author

Hi @harshach — gentle ping for review when you have a moment. All code, test, and Collate compatibility checks are passing.

Two quick items whenever convenient:

  1. Your thoughts on the open design question in the PR description (sharing the existing 8,000-char knowledge budget vs. giving structural metric fields a separate allocation).
  2. Setting the Shipping project fields on Metric AI context returns only the SQL expression #33455 (or adding skip-pr-checks) so Validate PR Metadata can pass, plus safe to test if you'd like CI integration tests run. Thanks!

@harshach harshach left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please carry the upstream related-metric limit into semanticFieldsTruncated and cover a metric with 51 visible relations. Today the JSON makes the first 50 look complete. Please also gate the mapping integration tests on embedded search, since the external test client rejects both index creation and cleanup.

.withDimensions(nullOrEmpty(metric.getDimensions()) ? null : metric.getDimensions())
.withMeasures(nullOrEmpty(metric.getMeasures()) ? null : metric.getMeasures())
.withFilters(nullOrEmpty(concept.getFilters()) ? null : concept.getFilters())
.withRelatedMetrics(relatedMetricFqns(metric, concept))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Carry the upstream 50-reference cutoff into semanticFieldsTruncated. With 51 distinct approved, visible related metrics and enough character budget, JSON returns 50 FQNs with no marker, so a client has no reason to fetch the complete list. I traced resolveMetrics at lines 1080–1089 through ConceptContextBuilder.build and relatedMetricFqns: the budget only sees the already-capped list. Track whether the candidate scan hit its limit, keeping permission-denied references out of the response, and test the 51-visible case.

Suggested change
.withRelatedMetrics(relatedMetricFqns(metric, concept))

private boolean truncated;

MetricContextBudget(final int budgetChars, final int maxItems) {
budget = new BudgetTracker(Math.max(0, budgetChars) - ENVELOPE_CHARS);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Charge the fields actually emitted before dropping a complete filter. I checked BudgetTracker and the serialized projection: with an 800-character budget, one 750-character ASCII condition serializes as a 766-character filters object. The fixed 95-character reservation leaves 705, so takeAll drops the only filter and sets the truncation flag. Add that exact-fit boundary to the tests and reserve space for the marker only when needed.

Suggested change
budget = new BudgetTracker(Math.max(0, budgetChars) - ENVELOPE_CHARS);

return 0;
}
if (!includeMetricSemantics) {
generic

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Gate construction of the new projection on includeMetricSemantics. I followed buildAssetContext into buildMetricContext: every default Markdown call scans the related references and builds the visibility set, only to clear all five fields here. The format is already known before buildMetricContext runs, so the legacy path can skip this work. Preserve the current omitted-field JSON behavior for legacy callers.

Suggested change
generic

void explicitMappingAcceptsExistingDynamicAndLegacyExpressionDocuments(
final TestNamespace namespace) throws Exception {
final ObjectNode mapping = readMetricMapping();
final SearchClient search = new SearchClient(OssTestServer.defaultHandle());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Gate this class on embedded search before entering either test. In external mode OssTestServer.defaultHandle() returns the remote handle, and SearchClient.put and delete both call requireEmbedded. Both tests therefore fail before checking a mapping, and the finally delete can mask the first error. StagedIndexUnrefreshedCountIT.setup() already shows the class-level JUnit assumption for this case.

Suggested change
final SearchClient search = new SearchClient(OssTestServer.defaultHandle());

assertTrue(generic.getDimensions().size() < dimensions.size());
assertEquals(dimensions.getFirst(), generic.getDimensions().getFirst());
final int contentChars = attached.getContent() == null ? 0 : attached.getContent().length();
assertTrue(AIContextBuilder.metricSemanticChars(generic) + contentChars <= 800);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Measure the serialized semantic fields independently in this assertion. applyKnowledgeBudget subtracts the same metricSemanticChars result at line 256. If that helper returned zero, the attached body could take all 800 characters and this test would still pass with dimensions on top. Serialize the returned generic fields (excluding pre-existing fields) and add the actual attached content length before comparing with 800.

@harshach

Copy link
Copy Markdown
Collaborator

@iamkiayun thanks for the PR. Please check the comments

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

UI browser tests

Ran: none (no browser test executes the changed code)

Changed files no browser test loads
  • src/generated/type/aiContext.ts
  • src/generated/type/personaContext.ts

@pmbrull pmbrull left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Java unit test failure

IngestionPipelineRepositoryTest.postDeleteTearsDownTheDeployedPipelineOnHardDelete was the only failure in 17,953 tests. It picked up a secrets manager left by an earlier test, and secret cleanup threw a NullPointerException before the test reached the runner. #38220 fixed this on main, where all 83 cases in that class passed. All 110 tests in the four changed service test classes passed on this PR head. Please rebase onto main to pick up the fix. PR unit-test log · Passing main run

.filter(Objects::nonNull)
.collect(Collectors.toCollection(ArrayList::new));
// Report the scan bound without performing extra lookups or exposing omitted references.
return new ResolvedMetrics(items, distinct.size() > MAX_KNOWLEDGE_ITEMS);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

scanCapped counts candidates before the visibility and approval checks, so 51 hidden related metrics still produce semanticFieldsTruncated=true for a caller who can see none. Please keep the lookup bounded, derive the flag from eligible related metrics, and update cutoffIsReportedWithoutExposingFilteredReferences to assert that the flag is absent when all relations are filtered out.

}
}
},
"code": {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

An existing index can have metricExpression.code mapped as date if the first expression was date-shaped. I verified on OpenSearch 3.4.0 that applying this mapping to that index returns HTTP 400 (mapper [metricExpression.code] cannot be changed from type [date] to [text]). Please cover the incompatible legacy field in the upgrade test and provide a reindex path for affected indexes.

@openbotgit
openbotgit Bot force-pushed the fix/33455-metric-json-context branch from fd457a5 to 0fd0812 Compare November 25, 2026 07:00
@pmbrull

pmbrull commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

semanticFieldsTruncated is missing when 50 visible relations are followed by 50 hidden ones and then one more visible relation. Check omitted relations in batches until you find a metric the caller can view that is approved or has no status. Add a regression for that ordering.

Rebase onto main and rerun CI. Fill in the Shipping fields on #33455 so Validate PR Metadata can pass.

iamkiayun and others added 5 commits November 26, 2026 01:00
Add final to unchanged bindings, extract focused mapping and budget-test helpers,
and centralize repeated mapping field names without changing behavior.
Propagate bounded related-metric scans without exposing filtered references, charge only emitted semantics, preserve legacy context omissions, and guard mapping tests in external mode.

Signed-off-by: Kee Kia Yun <kiayun.0218@outlook.com>
@openbotgit
openbotgit Bot force-pushed the fix/33455-metric-json-context branch from 0fd0812 to c2667e9 Compare November 25, 2026 17:24

Copy link
Copy Markdown
Contributor Author

Thanks for the regression. I rebased the five commits onto main and pushed c2667e96c, preserving your fix and authorship. The test now covers 50 visible relationships, 50 hidden ones, and one more visible relationship. All 197 focused unit tests and 34 PostgreSQL/OpenSearch integration tests passed locally.

I don’t have access to the Shipping project fields on #33455. Could a maintainer set Status, Source, Priority, Domain, and Release, and approve any fork CI runs that need it?

Comment on lines +20 to +23
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.

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.

@pmbrull

pmbrull commented Nov 26, 2026

Copy link
Copy Markdown
Member

hi @iamkiayun handled the issue metadata. Please check bot comments

@iamkiayun

Copy link
Copy Markdown
Contributor Author

@pmbrull Thanks for rerunning the metadata check. The latest run now lists just one missing field: Shipping → Status on #33455. I can’t edit the Shipping project. Could someone with project access set the status and rerun Validate PR Metadata?

@pmbrull

pmbrull commented Nov 27, 2026

Copy link
Copy Markdown
Member

@iamkiayun PR metadata is green. We also made some changes on CI structure, please bump your PR with latest main to get the final shape of the code. Thanks

@iamkiayun

Copy link
Copy Markdown
Contributor Author

Thanks, @pmbrull. I updated this branch from main, including #38701. The focused unit tests passed on the updated commit. I also reran the metric context and visibility tests on both PostgreSQL/OpenSearch and MySQL/Elasticsearch, and the metric expression mapping tests on PostgreSQL/OpenSearch. All passed.

@gitar-bot

gitar-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown
Code Review ⚠️ Changes requested 🔴 High risk 0 closed / 1 findings

Adding related metric FQNs to REST/MCP JSON changes the authorization-sensitive disclosure boundary; a permission-filtering error could expose restricted metric names.

Adds bounded metric declarations (dimensions, measures, filters, and visible related metric FQNs) to structured JSON context while leaving concept context and default Markdown unchanged. Changes are requested before merge because the omitted related-metric lookahead is unbounded: it loops over every omitted related reference in batches of 50, each batch doing a repository read and authorization check, which adds repeated round trips and contradicts the PR's no-additional-related-entity-reads constraint. A hard cap on lookahead batches should be added and recorded in the ADR.

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

📄 docs/decisions/2026-11-16-metric-structural-context-carries-semantic-fields.md:20-23

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;
🤖 Prompt for agents
Code Review: Adds bounded metric declarations (dimensions, measures, filters, and visible related metric FQNs) to structured JSON context while leaving concept context and default Markdown unchanged. Changes are requested before merge because the omitted related-metric lookahead is unbounded: it loops over every omitted related reference in batches of 50, each batch doing a repository read and authorization check, which adds repeated round trips and contradicts the PR's no-additional-related-entity-reads constraint. A hard cap on lookahead batches should be added and recorded in the ADR.

1. ⚠️ Performance: Omitted related-metric scan is unbounded and runs a DB read per batch
   Files: docs/decisions/2026-11-16-metric-structural-context-carries-semantic-fields.md:20-23

   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.

   Fix (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;

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

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

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Metric AI context returns only the SQL expression

3 participants