Repository navigation
Fixes 30715: reject bodiless clauses in persona AI context rule filters - #30716
Conversation
A persona AI-context rule whose Explore query-builder row has a field and an
operator but no value serialized to `{"term":{}}`. Both OpenSearch and
Elasticsearch reject a bodiless field-keyed clause outright, so the rule
evaluation failed with
Failed to parse query filter: Unexpected JSON event 'END_OBJECT' instead of 'KEY_NAME'
The editor auto-previews on a 300 ms debounce, so simply pausing mid-edit fired
it; once saved, the rule also broke the whole persona context document and the
MCP persona-context tool, not just the preview.
That failure was then masked. `ServiceUnavailableException(String)` routes
through `WebApplicationException(message, null, response)`, which sets the cause
to null rather than leaving it unset, so the following `initCause()` always threw
`IllegalStateException: Can't overwrite cause with ...` — turning a 503 with a
usable cause chain into a 500 with the original stack trace dropped.
- PersonaContextBuilder.search now passes the cause through the constructor.
- PersonaContextBuilder.activeEntityFilter prunes bodiless clauses, treating an
incomplete row as "no constraint" the way the query builder renders it.
bool/match_all/match_none are kept, since they are valid without a body and
dropping them would invert a surrounding must_not.
- buildEsRule stops emitting a rule whose values are all undefined, and the
multiselect path filters out the resulting holes instead of serializing nulls.
✅ PR checks passedThe linked issue has a description and all required Shipping project fields set. Thanks! |
✅ Playwright Results — workflow succeededValidated commit ✅ 587 passed · ❌ 0 failed · 🟡 2 flaky · ⏭️ 0 skipped · 🧰 0 lifecycle flaky PerformanceBlocking targets: ✅ met · Optimization targets: 🟡 in progress Shard-job maxima below are not the full workflow wall time; the linked run includes build, fixture, planning, and reporting. 🕒 Full workflow signal wall (to summary) 1h 31m 41s ⏱️ Max setup 3m 17s · max shard execution 19m 31s · max shard-job elapsed before upload 22m 50s · reporting 6s 🌐 201.71 requests/attempt · 2.78 app boots/UI scenario · 6.92% common-shard skew Optimization targets still in progress:
🟡 2 flaky test(s) (passed on retry)
How to debug locally# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip # view trace |
The emitted queryFilter drops a condition that has a field but no value, because
`{"term":{}}` is rejected outright by both search engines. Dropping it silently
on save is its own bug: a rule the user built as "tier is ___" persists as no
filter at all, so it matches everything and pulls the entity cap instead of the
handful of assets they selected.
The rule editor now refuses the save while a condition is unfinished and says so
inline, rather than quietly widening the rule.
hasUnfinishedRule answers the question by asking elasticSearchFormat what a row
actually produces, so the guard and buildEsRule's drop decision cannot drift
apart. It walks the same tree with the same config the emitted filter is built
from, which also keeps it a pure function — testable in jest, unlike anything
that reaches into react-awesome-query-builder's own config or validation (every
jest suite here mocks RAQB wholesale).
A group with no conditions stays valid: "empty selects every entity of the
configured type" is documented behaviour.
QueryBuilderWidgetV1 reports this through a new optional onValidityChange prop.
Only the persona rule editor opts in, so Explore and the other query-builder
consumers are untouched. The message appears on the save attempt rather than the
moment a row is added, so adding a condition is not immediately flagged.
Relates to #30715.
|
The rule drawer opens with no condition rows at all — the Filter section shows only the group's own field select and an "Add condition" button — so the .rule locator matched nothing and selectOption timed out looking for its selector. Click "Add condition" first, and anchor on the widget's own query-builder-form-field testid rather than the surrounding dialog. Confirmed against the CI failure screenshot and the widget markup rather than inferred: .rule and .rule--field are what query-builder-widget-v1.less styles and what the custom-property advanced-search suites already drive.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 28 out of 28 changed files in this pull request and generated no new comments.
Suppressed comments (1)
openmetadata-ui/src/main/resources/ui/src/components/common/QueryBuilderWidgetV1/QueryBuilderWidgetV1.tsx:227
handleChangereceives the up-to-datenConfigfrom RAQB, but the new validity check (and the emitted ES filter) uses the component stateconfiginstead. SincesetConfig(nConfig)is async, this can compute validity / serialize with a stale config (contradicting the comment that it uses the same tree+config as the emitted filter), especially during config changes (e.g., entity type/fields updates). UsenConfigfor bothhasUnfinishedRuleandelasticSearchFormathere.
if (outputType === SearchOutputType.ElasticSearch) {
// Same tree and config the emitted filter is built from, so the caller can block a save that
// would otherwise drop an unfinished condition and silently widen the filter.
props.onValidityChange?.(!hasUnfinishedRule(nTree, config));
const data = elasticSearchFormat(nTree, config) ?? '';
"Add condition" adds a row that already carries a field and an operator — Owners / Is — with its value left empty, so it is the unfinished condition under test as soon as it appears. Selecting a field on top of that was both unnecessary and wrong: the Filter section also holds a hidden .rule, so .first() resolved to that and toBeVisible never settled. Drop the field selection, assert on the row's delete button instead of reaching into RAQB markup, and remove the added row with .last() the way the entity-type test already does. Confirmed against the CI failure screenshot.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 28 out of 28 changed files in this pull request and generated no new comments.
Suppressed comments (1)
openmetadata-ui/src/main/resources/ui/src/components/common/QueryBuilderWidgetV1/QueryBuilderWidgetV1.tsx:228
handleChangeupdates internal state viaonTreeUpdate(nTree, nConfig), but then computes validity and the emitted ES filter using the (potentially stale)configstate. SincesetConfig(nConfig)is async, this can causehasUnfinishedRule/elasticSearchFormatto run against the previous config. Use thenConfigargument for both so the validity signal and emitted filter are always computed from the same config that RAQB provided for this change event.
// Same tree and config the emitted filter is built from, so the caller can block a save that
// would otherwise drop an unfinished condition and silently widen the filter.
props.onValidityChange?.(!hasUnfinishedRule(nTree, config));
const data = elasticSearchFormat(nTree, config) ?? '';
const qFilter = {
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 28 out of 28 changed files in this pull request and generated no new comments.
Suppressed comments (4)
openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextBuilder.java:326
- prunedClauseList() currently keeps null elements because
NullNodeis not an object, so it passes the!pruned.isObject()check and is added to the clause list. This leaves historically persisted multiselect holes (serialized asnull) unpruned, which can still make ES/OS reject the query and break persona context materialization.
private static JsonNode prunedClauseList(JsonNode clauses) {
ArrayNode kept = JsonNodeFactory.instance.arrayNode();
for (JsonNode clause : clauses) {
JsonNode pruned = prunedFilter(clause);
if (!pruned.isObject() || !pruned.isEmpty()) {
openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextBuilder.java:342
- JsonNode iteration in this codebase consistently uses
node.fields()(e.g., JsonPatchUtils.java:122) rather thanJsonNode.properties(). Usingfields()here avoids relying on a less-common API and keeps style consistent.
private static JsonNode prunedClause(JsonNode clause) {
ObjectNode kept = JsonNodeFactory.instance.objectNode();
for (Map.Entry<String, JsonNode> property : clause.properties()) {
JsonNode pruned = prunedFilter(property.getValue());
openmetadata-ui/src/main/resources/ui/src/components/common/QueryBuilderWidgetV1/QueryBuilderWidgetV1.tsx:228
- handleChange() uses the component state
configwhen computing validity and emitting the Elasticsearch filter, but the current config for this change is provided asnConfig. Because state updates are async, this can evaluate validity/formatting with a stale config when the builder updates config and tree together.
if (outputType === SearchOutputType.ElasticSearch) {
// Same tree and config the emitted filter is built from, so the caller can block a save that
// would otherwise drop an unfinished condition and silently widen the filter.
props.onValidityChange?.(!hasUnfinishedRule(nTree, config));
const data = elasticSearchFormat(nTree, config) ?? '';
const qFilter = {
openmetadata-ui/src/main/resources/ui/playwright/e2e/Features/PersonaAIContext.spec.ts:1153
- This test adds a persistent
adminPage.on('request', ...)listener but never removes it. In serial suites that reuse the same page, accumulating listeners can cause noisy cross-test coupling and harder-to-debug failures. Prefer registering a named handler and detaching it at the end of the test.
// Observe rather than intercept, so the debounced preview call is left alone.
let saveRequested = false;
adminPage.on('request', (request) => {
if (
request.method() === 'POST' &&
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 28 out of 28 changed files in this pull request and generated no new comments.
Suppressed comments (1)
openmetadata-ui/src/main/resources/ui/src/components/common/QueryBuilderWidgetV1/QueryBuilderWidgetV1.tsx:228
- handleChange receives the authoritative updated config as
nConfig, but the newonValidityChangecall (and the emitted ES filter) uses the component stateconfiginstead. BecausesetConfig(nConfig)is async, this can validate/serialize against stale config and incorrectly block (or allow) saving depending on timing and config changes. UsenConfigconsistently for bothhasUnfinishedRuleandelasticSearchFormatin this handler.
const handleChange = (nTree: ImmutableTree, nConfig: Config) => {
onTreeUpdate(nTree, nConfig);
if (outputType === SearchOutputType.ElasticSearch) {
// Same tree and config the emitted filter is built from, so the caller can block a save that
// would otherwise drop an unfinished condition and silently widen the filter.
props.onValidityChange?.(!hasUnfinishedRule(nTree, config));
const data = elasticSearchFormat(nTree, config) ?? '';
const qFilter = {
…nitization Per PR review: the recursive JSON pruning (prunedFilter/prunedClause/ prunedClauseList/carriesConstraint) duplicated validation ES/OS already do. UI guards stop empty filters at the source; if one still reaches the backend, ES/OS reject it and the 503 carries the real cause (that fix is retained). Removes the pruning helpers, the BODILESS_QUERY_CLAUSES set, the pruning call in activeEntityFilter, and the 3 pruning unit tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 28 out of 28 changed files in this pull request and generated no new comments.
Suppressed comments (2)
openmetadata-ui/src/main/resources/ui/src/components/common/QueryBuilderWidgetV1/QueryBuilderWidgetV1.tsx:228
handleChangereceives the updated RAQB config asnConfig, but the new validity check and the emitted Elasticsearch query both use the (possibly stale) React stateconfig. SincesetConfig(nConfig)is async, this can compute validity/DSL using the previous config and cause incorrect save-blocking or query serialization. UsenConfigfor bothhasUnfinishedRuleandelasticSearchFormathere (and keep usingnConfigconsistently in this callback).
if (outputType === SearchOutputType.ElasticSearch) {
// Same tree and config the emitted filter is built from, so the caller can block a save that
// would otherwise drop an unfinished condition and silently widen the filter.
props.onValidityChange?.(!hasUnfinishedRule(nTree, config));
const data = elasticSearchFormat(nTree, config) ?? '';
const qFilter = {
openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextBuilder.java:272
- This change correctly preserves the underlying search exception as the 503 cause, but
activeEntityFilter()still unconditionally includes the user-providedquerysubtree when it’s non-empty. If a persisted rule contains a bodiless clause (e.g.{"term":{}}nested under abool.must), the search filter will still be handed to the engine deserializer and fail, so the persona context document will continue to break for already-saved poisoned rules (the PR description says these clauses are pruned). The backend safety-net pruning logic looks missing here.
// ServiceUnavailableException(String) already fixes the cause to null, so initCause() on it
// always throws IllegalStateException and swallows the real failure.
throw new ServiceUnavailableException(
"Failed to evaluate persona context rule '"
+ rule.getName()
|
Code Review ✅ Approved 1 resolved / 1 findingsPrevents saving incomplete persona AI-context rules with bodiless filter conditions and fixes search failure handling by preserving underlying exception causes. No issues found. ✅ 1 resolved✅ Edge Case: Save-block skipped when editing a pre-existing incomplete rule
OptionsDisplay: compact → Showing less information. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Gitar | Powered by Gitar — free for open source |
|
picked to 2.0 |



Describe your changes:
Fixes #30715
A persona AI-context rule whose Explore query-builder row has a field and an operator but no value serialized to
{"term":{}}. Both OpenSearch and Elasticsearch reject a bodiless field-keyed clause outright, so evaluating the rule failed withFailed to parse query filter: Unexpected JSON event 'END_OBJECT' instead of 'KEY_NAME'. The editor auto-previews on a 300 ms debounce, so pausing mid-edit was enough to trigger it, and once the rule was saved the same filter broke the whole persona context document and theget_persona_contextMCP tool —selectRulesevaluates every rule, so one bad rule fails the entire build.Approach: fix it on the UI, don't sanitize on the backend. The empty filter must never be emitted or saved in the first place — that is a UI concern. The backend does not try to clean up query filters: ES/OS already validate queries, so re-implementing that as recursive JSON pruning in the service is duplicated work. If a malformed filter ever does reach the backend, ES/OS reject it and the failure now surfaces with its real cause instead of being masked.
UI — don't let an empty filter through
buildEsRulestops emitting a rule whose values are allundefined(this also covers the nested custom-property path, which builds its clause separately), and the multiselect branch filters out the resulting holes instead of serializing them asnull.hasUnfinishedRuleanswers that by askingelasticSearchFormatwhat a row actually produces, so the guard andbuildEsRule's drop decision cannot drift apart. A group with no conditions stays valid — "empty selects every entity of the configured type" is documented behaviour.QueryBuilderWidgetV1exposes this through a new optionalonValidityChangeprop. Only the persona rule editor opts in, so Explore and the other query-builder consumers are untouched. The message appears on the save attempt rather than the moment a row is added.Backend — stop masking a real search failure
PersonaContextBuilder.searchpasses the cause through the(String, Response, Throwable)constructor instead of callinginitCause(), so the 503 keeps its real cause.ServiceUnavailableException(String)routes throughWebApplicationException(message, null, response)→super(message, cause)withcause == null, which sets the cause instead of leaving it unset, so the followinginitCause()always threwIllegalStateException: Can't overwrite cause with ...— every search failure surfaced as a 500 with the original stack trace dropped.Type of change:
High-level design:
The UI guard is deliberately a pure function over the same tree and config the emitted filter is built from, rather than a call into react-awesome-query-builder's own validation (
QbUtils.isValidTree).Two reasons. It cannot disagree with
buildEsRuleabout what counts as unfinished, since it askselasticSearchFormatrather than reimplementing the rule. And it is unit-testable: every jest suite in this repo mocks RAQB wholesale (jest.mock('@react-awesome-query-builder/antd')inQueryBuilderWidgetV1.test.tsx), so anything reaching into RAQB's config or validation can only be verified in a browser. Building RAQB's extended config standalone does not work either — OM'sgetTreeConfigoutput is not complete until<Query>extends it, soConfigUtils.extendConfigthrows on it.Tests:
Use cases covered
POST /aiContext/rulesis fired.Unit tests
Backend —
openmetadata-service/.../aicontext/PersonaContextBuilderTest.java.searchSurfacesTheUnderlyingSearchFailureWithItsCausefails onmainwith the exact productionIllegalStateException.UI —
src/utils/QueryBuilderElasticsearchFormatUtils.test.js, 12 tests: 4 covering the emitted filter (unentered rule, bodiless clause, multiselect null hole, entered-value regression guard) and 8 coveringhasUnfinishedRule(unentered value, no field picked, multiselect with no option, fully entered, group with no conditions, undefined tree, unfinished nested in a group, all-entered group).Backend integration tests
Ingestion integration tests
Playwright (UI) tests
playwright/e2e/Features/PersonaAIContext.spec.ts:blocks saving a rule whose condition has no value enteredsaves a rule that has no filter conditions at allclears the filter error once the unfinished condition is removedThese drive the real query builder end-to-end, which jest cannot (see High-level design). The middle one is the important guard: if the check ever starts rejecting an empty filter, saving a "match everything" rule breaks, and that is a worse regression than the bug being fixed.
Manual testing performed
The UI behaviour is covered by the Playwright cases above.
i18n
message.persona-context-rule-filter-incompleteadded and synced withyarn i18n. All 19 non-English locales carry a real translation rather than the English placeholderyarn i18ninserts. Notepr-pris Persian, not Portuguese.UI screen recording / screenshots:
Not attached — no local stack available to record against. The three Playwright cases document the behaviour end-to-end instead.
Follow-up (not in this PR)
PersonaContextBuilder.selectRulesstill evaluates rules unguarded, so any future rule-level failure takes down the entire persona context document and the MCP tool rather than degrading that one rule. Isolating per rule is a behaviour change worth its own discussion — happy to open a separate issue.Checklist:
Fixes <issue-number>: <short explanation>Fixes #<issue-number>above.🤖 Generated with Claude Code