Skip to content

Fixes #32600: render table sample rows in the AI context markdown - #33126

Merged
pmbrull merged 1 commit into
mainfrom
pmbrull/markdown-sample-rows-gap
Sep 10, 2026
Merged

pmbrull merged 1 commit into
mainfrom
pmbrull/markdown-sample-rows-gap

Conversation

@pmbrull

@pmbrull pmbrull commented Sep 10, 2026

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #32600

I reopened #32600 because the change that closed it (#32608) only surfaced the samples in the
structured representation. Markdown is what both consumers return by default —
GET /v1/tables/{id}/context with no format param, and the MCP get_entity tool with
include: ["context"] — so assetContext.table.sampleData was populated but never rendered, and
the stored rows stayed unreachable for exactly the SQL-agent path the issue was filed for. That PR's
own description states it: "The default Markdown rendering is unchanged."

This renders a # Sample Data section into the markdown document from the payload the builder
already authorized against ViewSampleData and PII-masked, so no new data reaches a caller who
could not already read it via ?format=json.

Type of change:

  • Bug fix

High-level design:

  • AIContextMarkdown.appendTableContext gains appendSampleData, placed under the existing
    SCHEMA section gate after the schema table and data model — definitions first, then values.
  • Rendering is defensive because the payload is user/ingestion-supplied JSON, not a typed row set:
    values are flattened to one line (\R+ → space), pipes escaped, null rendered as an empty
    cell, rows padded or truncated to the declared column width, and each cell capped at 120 chars.
    The width normalization matters for correctness, not just looks — one ragged row otherwise shifts
    every value under the wrong column name, which is worse than no samples at all for an agent.
  • A caveat line (_Representative stored sample rows — not the full table; never count or aggregate over them._) precedes the table, so an agent does not read 10 rows as the table's cardinality.
  • No new ContextSection enum value was added, deliberately.
    AIContextBuilder.applySearchFields indexes buildTableContext(table) without sample data, and
    PersonaContextBuilder.assetContext(document) deserializes TableContext from that search
    document. So the persona path has no samples to render, and a sampleData persona toggle would
    advertise a section that path can never fill. Materializing samples there would also be a real
    leak: the persona context document is cached and shared across users, so it cannot carry a
    per-caller ViewSampleData/PII decision. Gating on SCHEMA keeps the section on the one path
    that does the per-request authorization.
  • No migration and no schema change: sampleData already exists on assetContext.table from
    Fixes #32600: include samples in AI context #32608. This PR is presentation-only.

Tests:

Use cases covered

  • An authorized caller requesting the markdown default (no ?format=json) receives a
    # Sample Data table with the header row and the first 10 of 12 stored rows.
  • A caller with explicit deny ViewSampleData receives the markdown context with # Schema and
    no # Sample Data section and no sample values anywhere in the body.
  • A payload whose rows are shorter or longer than its declared columns renders an aligned table:
    short rows padded, overflowing values dropped rather than appended as phantom cells.
  • A value containing a pipe, an embedded newline, or null does not break the table delimiters.
  • A 500-char blob value is capped so it cannot crowd the rest of the context out of the window.
  • Sample data absent, or present with columns but zero rows, emits no section at all.

Unit tests

  • I added unit tests for the new/changed logic.
  • File updated: openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextMarkdownTest.java
    (5 new tests: render_emitsSampleDataRowsUnderSchema, render_omitsSampleDataWhenAbsentOrEmpty,
    render_sanitizesAndPadsDelimiterSensitiveSampleValues,
    render_padsRaggedSampleRowsToTheColumnWidth, render_capsLongSampleValues)
  • Coverage on the changed class (mvn -Pstatic-code-analysis ... jacoco:report):
    AIContextMarkdown.java — 90.8% lines (376/414), 79.7% branches. Meets the 90% target.
AIContextMarkdownTest      29/29 pass
AIContextBuilderTest       47/47 pass
PersonaContextMarkdownTest 12/12 pass
PersonaContextBuilderTest  21/21 pass

Backend integration tests

  • I added integration tests for the changed response representation.
  • File updated: openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/AIContextRestIT.java
    • tableContext_returnsOkfMarkdownByFqn now asserts the # Sample Data heading, the header row,
      row 9, and the absence of name-10 (the 10-row cap holds in markdown too).
    • tableContext_omitsSamplesFromMarkdownWithoutViewSampleDataPermission (new) — the denied
      caller's markdown has # Schema but no # Sample Data and no sample values.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes; this is a server-rendered markdown response).

Manual testing performed

  1. Rendered the document from a fixture with a pipe-bearing value, an embedded newline, a null,
    a 200-char blob, and a 3-column header against 1- and 4-value rows; confirmed the table stays
    aligned, a|b renders as a\|b, the newline flattens, the blob elides with …, and the caveat
    line precedes the table:
# Sample Data

_Representative stored sample rows — not the full table; never count or aggregate over them._

| id | note | amount |
|---|---|---|
| 1 | a\|b c |  |
| 2 | zzzz…(capped at 120) | 9.5 |
  1. mvn -o -pl openmetadata-service test -Dtest=AIContextMarkdownTest,AIContextBuilderTest — pass.
  2. mvn -o -pl openmetadata-service test -Dtest=PersonaContextMarkdownTest,PersonaContextBuilderTest
    — pass, confirming the persona rendering path is unchanged.
  3. mvn -o -pl openmetadata-integration-tests test-compile — clean.
  4. mvn -pl openmetadata-service,openmetadata-integration-tests spotless:apply — no diff.

AIContextRestIT compiles but was not executed locally (needs the live stack); the two new HTTP
cases run in CI.

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: not applicable — no schema change; sampleData already exists on assetContext.table from Fixes #32600: include samples in AI context #32608.
  • For UI changes: not applicable.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.

Bug fix

  • I have added a test that covers the exact scenario we are fixing. Verified RED: checking out
    origin/main's AIContextMarkdown.java against the new test file gives
    Tests run: 29, Failures: 4 — the 4 assertion tests fail without the fix. The 5th
    (render_omitsSampleDataWhenAbsentOrEmpty) asserts absence and so passes on main by
    construction; it guards against a future regression that renders an empty section, not
    against today's bug.

#32608 added `assetContext.table.sampleData` to the AI context but only
the structured representation surfaced it. Markdown is the default for
both `GET /{entity}/{id}/context` and the MCP `get_entity` tool, so the
stored samples were reachable only via `?format=json` — the gap this
closes.

Renders a `# Sample Data` table under the SCHEMA section, immediately
reusing the payload the builder already authorized against
`ViewSampleData` and PII-masked. Values are flattened to one line, pipe
escaped, padded/truncated to the declared column width, and capped at
120 chars so a blob column cannot crowd out the rest of the context. A
caveat line marks the rows as a sample so an agent does not count or
aggregate over them.

The persona context path is unaffected: `AIContextBuilder.applySearchFields`
indexes `buildTableContext(table)` without sample data, so the cached,
cross-user persona document has nothing to render.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@pmbrull
pmbrull requested a review from a team as a code owner September 10, 2026 09:32
Copilot AI lite review requested due to automatic review settings September 10, 2026 09:32

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 added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Sep 10, 2026
Comment on lines +488 to +493
private static String sampleCell(Object value) {
String text = value == null ? "" : cell(Objects.toString(value).replaceAll("\\R+", " "));
return text.length() > MAX_SAMPLE_CELL_CHARS
? text.substring(0, MAX_SAMPLE_CELL_CHARS) + "…"
: text;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Edge Case: Sample cell truncation can split a char or escape sequence

In sampleCell, text.substring(0, MAX_SAMPLE_CELL_CHARS) cuts the already-escaped string at a UTF-16 code-unit boundary. This can split a surrogate pair (leaving a lone surrogate) or split an inserted \| escape, leaving a trailing backslash before the appended … (rendered as a visible \…). The impact is cosmetic — it does not break table alignment since no new | is introduced — but truncating on code points and trimming a dangling backslash would be cleaner. Consider capping on codePointCount/offsetByCodePoints and stripping a trailing lone \ before appending the ellipsis.

Was this helpful? React with 👍 / 👎

@gitar-bot

gitar-bot Bot commented Sep 10, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 0 resolved / 1 findings

Adds # Sample Data markdown rendering to the AI context, fixing the gap where sample rows were available in JSON but not in the default markdown response. The implementation includes defensive rendering with proper escaping, alignment, and a caveat note for agents.

Consider refining sample cell truncation to avoid splitting UTF-16 surrogates or escape sequences—currently substring(0, MAX_SAMPLE_CELL_CHARS) can split a \| escape or surrogate pair, leaving a trailing backslash before the ellipsis. Truncating on code points and trimming a dangling \ would be cleaner.

💡 Edge Case: Sample cell truncation can split a char or escape sequence

📄 openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextMarkdown.java:488-493

In sampleCell, text.substring(0, MAX_SAMPLE_CELL_CHARS) cuts the already-escaped string at a UTF-16 code-unit boundary. This can split a surrogate pair (leaving a lone surrogate) or split an inserted \| escape, leaving a trailing backslash before the appended … (rendered as a visible \…). The impact is cosmetic — it does not break table alignment since no new | is introduced — but truncating on code points and trimming a dangling backslash would be cleaner. Consider capping on codePointCount/offsetByCodePoints and stripping a trailing lone \ before appending the ellipsis.

🤖 Prompt for agents
Code Review: Adds `# Sample Data` markdown rendering to the AI context, fixing the gap where sample rows were available in JSON but not in the default markdown response. The implementation includes defensive rendering with proper escaping, alignment, and a caveat note for agents.
  
  Consider refining sample cell truncation to avoid splitting UTF-16 surrogates or escape sequences—currently `substring(0, MAX_SAMPLE_CELL_CHARS)` can split a `\|` escape or surrogate pair, leaving a trailing backslash before the ellipsis. Truncating on code points and trimming a dangling `\` would be cleaner.

1. 💡 Edge Case: Sample cell truncation can split a char or escape sequence
   Files: openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextMarkdown.java:488-493

   In `sampleCell`, `text.substring(0, MAX_SAMPLE_CELL_CHARS)` cuts the already-escaped string at a UTF-16 code-unit boundary. This can split a surrogate pair (leaving a lone surrogate) or split an inserted `\|` escape, leaving a trailing backslash before the appended `…` (rendered as a visible `\…`). The impact is cosmetic — it does not break table alignment since no new `|` is introduced — but truncating on code points and trimming a dangling backslash would be cleaner. Consider capping on `codePointCount`/`offsetByCodePoints` and stripping a trailing lone `\` before appending the ellipsis.

Options

Display: compact → Counting what did not apply, without listing it.

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

@pmbrull
pmbrull added this pull request to the merge queue Sep 10, 2026
Merged via the queue into main with commit 4b05f84 Sep 10, 2026
152 checks passed
@pmbrull
pmbrull deleted the pmbrull/markdown-sample-rows-gap branch September 10, 2026 18:10

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ingestion 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.

Include permission-filtered table samples in AI context

3 participants