Skip to content

Fixes #27990: stop malformed search input failing as a server error - #33655

Merged
mohityadav766 merged 4 commits into
mainfrom
fix/27990-search-query-parse-errors
Sep 22, 2026
Merged

mohityadav766 merged 4 commits into
mainfrom
fix/27990-search-query-parse-errors

Conversation

@harshach

@harshach harshach commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes #27990

/v1/search/query reported malformed caller input as a server fault. Two distinct failures are recorded on that Sentry group, and this PR fixes both plus the shared amplifier that turned them into 500s.

1. A malformed Lucene expression in q failed the whole search.
containsQuerySyntax() routes anything containing * ? ( ) ~ ^ " + - : into query_string with the raw text. Lucene then rejects an unparseable expression, which comes back as all shards failed and the caller gets nothing — this is the parse_exception ... Encountered " ":" ": "" at line 1, column 0 in the issue body.

Routing now also requires the expression to be parseable (LuceneQuerySyntax). Well-formed Lucene keeps its Lucene meaning exactly as before; text that Lucene cannot parse is searched as literal words, which is what a partially typed query means anyway.

2. A queryFilter that is valid JSON but not query DSL failed the search.
This is the newer failure on the same group: x_content_parse_exception: [1:220] [bool] failed to parse field [must]. applyQueryFilter's try/catch only covered client-side JSON parsing, so a filter that parsed as JSON but was not a query sailed through into a wrapper query and was rejected by the engine.

QueryFilterShape now checks the one invariant the DSL actually guarantees — must/should/filter/must_not hold a query object or an array of query objects — and rejects anything else as a 400 naming queryFilter.

3. Engine 400s are no longer reported as 500s.
buildSearchException special-cased only 404, so every other engine status became SearchException(String), which hardcodes INTERNAL_SERVER_ERROR. SearchEngineErrors now maps an engine 400 to a 400. Everything else, including the 429 a tripped circuit breaker returns, stays a 500 — those are not the caller's doing. This also covers any malformed form the syntax check above does not model: it is an honest 400 instead of a 500.

Type of change:

  • Bug fix

High-level design:

The routing guard is a structural check, not a Lucene parser — Lucene's queryparser is not on the service classpath. It is deliberately conservative: it only reports text that Lucene definitely cannot parse, so it can never downgrade a valid expression. Every rule was derived from a live engine rather than from the grammar, which mattered — foo~ parses (default edit distance) while foo^ does not, a + b parses while a lone + does not, and colons inside a quoted phrase are literal.

Alternatives considered:

  • Escape or sanitize q — silently changes the meaning of valid Lucene expressions. Rejected.
  • Catch the engine's parse failure and retry as free text — correct, but costs a round trip and threads retry state through executeRankedSearch. The pre-check gets the same user-visible result with no extra round trip, and change 3 catches whatever it misses.
  • Silently ignore a malformed queryFilter (the previous behaviour for malformed JSON) — a dropped filter widens the result set past what the caller asked for, which is worse than an error. Rejected.

Behaviour change worth calling out: a malformed queryFilter was previously logged and ignored, returning 200 with unfiltered results. It is now a 400. This is intentional for the reason above, but it is a visible change for any caller that has been sending a filter that never applied.

Tests:

Use cases covered

  • A user typing revenue (draft) in Explore gets results at every intermediate keystroke instead of a failed search
  • Searching :foo*, "unclosed, foo AND, name:(foo returns results instead of all shards failed
  • A valid Lucene expression (name:orders AND service:snowflake, foo~^2, "a:b:c") keeps its Lucene meaning
  • A caller sending a malformed queryFilter gets a 400 naming the parameter, not a 500
  • A tripped circuit breaker (429) is still reported as a server error

Unit tests

  • Added for all new logic.
  • Files added: LuceneQuerySyntaxTest, QueryFilterShapeTest, SearchEngineErrorsTest
  • Files updated: SearchSourceBuilderFactoryTest (routing: unparseable syntax must not reach query_string; well-formed syntax still must)

Backend integration tests

  • Added in openmetadata-integration-tests/.
  • Files updated: SearchResourceIT — unparseable q returns 200; malformed queryFilter returns 400; valid queryFilter still applies

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

Verified against a real OpenSearch 3.4.0 node with OpenMetadata's own table_index_mapping.json and 8,000 indexed tables, driving the real OpenSearchSourceBuilderFactory with the shipped searchSettings.json so the query bodies under test are the ones the service actually sends.

  1. Before the fix: 23 of 38 malformed inputs returned query_shard_exception / all shards failed. q=":foo*" reproduced the issue's parse_exception byte-for-byte, including the Was expecting one of: token list.
  2. Before the fix: of the 42 keystroke prefixes of revenue (draft), "quoted phrase" and sales (2024), 25 failed — every state from the opening ( or " until it was closed.
  3. After the fix: 0 failures across all three corpora — 38 malformed, 42 keystroke prefixes, 20 realistic.
  4. Mode 2 reproduced and fixed: a queryFilter with a nested array inside bool.must produced x_content_parse_exception: [1:200] [bool] failed to parse field [must] before, and is a 400 naming queryFilter after.

Cross-check of the syntax guard against live Lucene — a 1,001-query corpus, restricted to the 913 that actually reach the Lucene path (containsQuerySyntax == true), comparing the guard's verdict against whether the engine really parses the text:

corpus 1001; reaching the Lucene path: 913
agree:                                                778
FALSE POSITIVES (guard downgrades text Lucene accepts):  0
residual (still unparseable -> now a 400, not a 500):   135

Zero false positives is the property that matters: no valid Lucene expression loses its meaning. The 135 residuals are exotic forms the guard does not model (orders[~1, orders!^2); they are genuinely malformed, and change 3 makes them an honest 400.

Across the three input corpora (38 malformed, 42 keystroke prefixes, 20 realistic), server-side failures go from 48 to 0.

UI screen recording / screenshots:

Not applicable.

Checklist:

🤖 Generated with Claude Code


Open workspace in Conductor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; the previous findings are resolved and no new actionable defects were identified.

Summary

This PR prevents malformed search input from being reported as a server failure.

  • Routes structurally malformed Lucene expressions through literal-text search while preserving valid Lucene syntax, including ranges and regular expressions.
  • Validates boolean query-filter clause shapes and returns a named 400 response instead of silently dropping invalid filters.
  • Maps search-engine 400 responses to client errors while retaining server-error treatment for statuses such as 429.
  • Adds unit and integration coverage for malformed queries, query filters, status translation, and the valid forms raised in the previous review.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Request["Search request"] --> Q{"Malformed q?"}
  Q -->|Yes| Literal["Literal/simple query path"]
  Q -->|No| Lucene["Lucene query path"]
  Request --> Filter{"queryFilter valid?"}
  Filter -->|No| BadRequest["HTTP 400"]
  Filter -->|Yes| Engine["Search engine"]
  Literal --> Engine
  Lucene --> Engine
  Engine --> Status{"Engine status"}
  Status -->|400| BadRequest
  Status -->|Other failure| ServerError["HTTP 500"]
  Status -->|Success| Results["Search results"]
Loading

Reviews (4) · Last reviewed commit: "Update two SearchResourceIT assertions t..."

/v1/search/query reported malformed caller input as a 500. Two distinct
failures are recorded on that Sentry group; this fixes both, plus the
shared mapping that turned them into server errors.

A malformed Lucene expression in `q` failed the whole search.
containsQuerySyntax routes anything carrying Lucene syntax into
query_string with the raw text, so an unparseable expression came back as
`all shards failed` and the caller got nothing. Routing now also requires
the expression to be parseable. Well-formed Lucene keeps its meaning
exactly as before; text Lucene cannot parse is searched as literal words,
which is what a partially typed query means anyway.

A queryFilter that is valid JSON but not query DSL failed the search with
`[bool] failed to parse field [must]`. applyQueryFilter only guarded
client-side JSON parsing, so such a filter reached the engine inside a
wrapper query. It is now rejected as a 400 naming the parameter rather
than dropped, since a missing filter widens the result set past what the
caller asked for.

buildSearchException special-cased only 404, so every other engine status
became SearchException(String), which hardcodes INTERNAL_SERVER_ERROR.
Engine 400s now map to 400; 429 and 5xx stay 500s. This also covers any
malformed form the syntax check does not model.

The syntax check is structural, not a Lucene parser, and deliberately
conservative: every rule was derived from a live engine, since `foo~`
parses while `foo^` does not and `a + b` parses while a lone `+` does not.
Cross-checked over a 1,001-query corpus (913 reaching the Lucene path)
against whether the engine really parses the text: zero false positives.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@harshach
harshach requested a review from a team as a code owner September 20, 2026 06:11
@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

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

Both encode behaviour this PR deliberately changes, and both failed on
every integration lane.

testSearchWithMalformedQueryFilter asserted that a malformed queryFilter
is accepted: it was logged, dropped, and the search returned 200 carrying
every row the filter was meant to exclude. Silently widening a result set
is worse than failing, so it is now a 400 and the test says so.

testSearchWithNegativeOffset asserted ApiException. A negative offset is
the caller's error and the engine answers 400, which the SDK maps to
InvalidRequestException -- a sibling of ApiException, not a subclass, so
the old assertion no longer matches. The test now pins the 400.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

Copy link
Copy Markdown
Collaborator Author

Integration lane failures — fixed in d352ea9

All three lanes (mysql-elasticsearch, postgres-opensearch, postgres-elasticsearch-redis) failed on the same two tests, and both are pre-existing tests encoding behaviour this PR deliberately changes — not the new ones. My three added tests passed on every lane.

testSearchWithMalformedQueryFilter — asserted assertDoesNotThrow, i.e. that a malformed queryFilter is accepted. That was the old behaviour: logged, dropped, search returns 200 carrying every row the filter was meant to exclude. Silently widening a result set is worse than failing, so it is now a 400 and the test asserts that (this is the behaviour change already called out in the PR description).

testSearchWithNegativeOffset — asserted ApiException. A negative offset is the caller's error and the engine answers 400, which the SDK maps to InvalidRequestException. That is a sibling of ApiException (both extend OpenMetadataException), not a subclass, so the old assertion stopped matching once the status stopped being flattened to 500. The test now pins the 400, which is the more correct contract.

Neither change weakens a test — both now assert a stricter, more specific contract than before.

Checks I ran before pushing, to avoid another round trip:

  • Swept every other queryFilter usage and ApiException assertion in the IT suite: the only other one (LineageBrokenReferenceIT, a plain term filter) is unaffected, and the ApiException uses in ActivityResourceIT/ConversationResourceIT are entity 404s, unrelated to search.
  • Ran 14 real OM-generated filter shapes — nested bool/should, must_not holding a bare object, empty clause arrays, nested customPropertiesTyped, the UI's Explore filter shape — through QueryFilterShape: all accepted.
  • openmetadata-integration-tests test-compile: BUILD SUCCESS.

@gitar-bot

gitar-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved 1 closed / 1 findings

🟡 Medium risk

Prevents malformed search input from surfacing as server errors by routing unparseable Lucene expressions through free-text search, validating query-filter shapes before forwarding to the engine, and mapping engine 400s to caller-facing bad requests. Comprehensive unit and integration test coverage added. No issues found.

✅ 1 closed
✅ Edge Case: QueryFilterShape validates bool keys anywhere, not only in bool

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/QueryFilterShape.java:67-81 📄 openmetadata-service/src/main/java/org/openmetadata/service/search/QueryFilterShape.java:94-107
hasWellFormedClauses recurses into every JSON object and enforces the query-object/array-of-query-objects shape on any property whose key is must/should/filter/must_not, regardless of context. A legitimate leaf clause that targets a field literally named one of these keys — e.g. {"term":{"filter":"x"}} or {"match":{"must":"y"}} — has a scalar value, so isClauseValue returns false and the whole queryFilter is rejected as a 400. Previously such a filter parsed as JSON and was forwarded successfully, so this is a behavior regression for that (admittedly uncommon) field-name case. Consider only applying the clause-shape check to keys that are direct children of a bool object.

Review coverage

📋 Rules No rules evaluated

🧪 Functional validation Not enabled · Set up

🤖 Auto-approval Not enabled · Set up

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

@sonarqubecloud

Copy link
Copy Markdown

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

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

Projects

None yet

2 participants