← Back to Pull requests

Close gaps left by the regex breaker charging #166954

Open
alighahramani-alig opened this pull request with 222 lines diff across 11 files
View on GitHub
alighahramani-alig alighahramani-alig commented on Nov 20, 2026 20:13 UTC
Author

Follow-up to #158570, from the review comments left on its last commit.

  • constant_keyword. A regexp or wildcard query compiled its pattern into a CharacterRunAutomaton to test the field's one value. That is a table with an entry for every state and every character class of the pattern, built after the charged build had released its reservation. The value is now stepped through the DFA, so no table is built.

  • version. Its regexp query charged the NFA and DFA builds and then constructed an AutomatonQuery, which compiles the DFA into its UTF-8 run form with nothing reserved. The estimate the keyword field reserves for that step is now held while the query is constructed, and what the finished query keeps is charged as it is built, not when the query tree is walked.

  • Include/exclude. An exclude that is deterministic as built, and an include that an exclude matching nothing leaves unchanged, were held on the breaker twice during the build. Each is now held once.

  • Changelog and docs. The entry of #158570 said a rejected include/exclude pattern fails the search. The length, complexity and breaker checks all run on the shard, so when only some shards reject the pattern the search returns the others' results and lists the rejections under _shards.failures, unless partial results are disallowed. The entry now says so, and 30_limits.yml pins it for the length check across two indices with different limits. The entry and the Prometheus compatibility page also state the 1,000-character limit on the pattern of a PromQL =~ or !~ label matcher.
  • Each new unit test fails without its fix. No changelog entry of its own: #158570 is in no stack release yet, so its entry is the one edited here. The backports of #158570 that carry the breaker charging should carry these commits too.

    Left for later, from the same review: the include/exclude work limit does not count the ranges it scans, and a multi-value exact label matcher builds its literals before the first budget check.

    Assisted by Claude.

    Diff: 222 lines (+200 / -22) across 11 files Reviewer: kosabogi Review duration: 19845m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.50) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.50 · 222 lines diff across 11 files
    0.50
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.96 · 5 substantive comment(s)
    0.96
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    93%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.323
    Real PR Conversation Timeline
    17 items
    github-actions[bot] github-actions[bot] commented on Nov 20, 2026 20:16 UTC
    Bot

    🔍 Preview links for changed docs

    This PR only changes snippets or data files. No direct page links are available.
    Browse the full preview

    github-actions[bot] github-actions[bot] commented on Nov 20, 2026 20:16 UTC
    Bot

    ✅ Elastic Docs Style Checker (Vale)

    No issues found on modified lines!

    ---

    The Vale linter checks documentation changes against the Elastic Docs style guide. To use Vale locally or report issues, refer to Elastic style guide for Vale.

    <!-- Sticky Pull Request Commentelastic-vale-results -->

    github-actions[bot] github-actions[bot] commented on Nov 20, 2026 20:18 UTC
    Bot

    ℹ️ Important: Docs version tagging

    👋 Thanks for updating the docs! Elastic docs cover multiple versions and deployment types on the same page. applies_to tags help readers understand which information applies to them.

    ⚠️ Don't remove or replace information that applies to an older version.

    Need help with applies_to?

  • Tagging skill: Identify, generate, update, and validate tags.

  • Placement guide: Where to put applies_to metadata, with syntax examples.
  • The automated docs review also checks for tagging issues on your PR, where enabled.

    elasticsearchmachine elasticsearchmachine commented on Nov 30, 2026 15:54 UTC
    Contributor

    Pinging @elastic/es-analytical-engine (Team:Analytics)

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Nov 30, 2026 15:59 UTC
    Code Review
    docs/changelog/158570.yaml:1
    @@ -9,17 +9,22 @@ breaking:
         circuit breaker. The patterns are now compiled on the shard,
         with every step charged to the request circuit breaker and bounded by a fixed amount of work, so a pattern that is too
         complex to build is rejected instead of occupying a search thread. The `regexp` query and PromQL label matchers are
    -    built the same way and are bounded by the same amount of work. Both constructors of the pattern now compile it with
    +    built the same way and are bounded by the same amount of work, and the pattern of a PromQL label matcher is limited
    +    to `1000` characters. Both constructors of the pattern now compile it with
         the same flags, so `~` is the complement operator on every shard; before, a shard that received the request from
         another node treated `~` as a literal character.
       impact: >-
         A search whose aggregation uses an `include` or `exclude` pattern longer than `index.max_regex_length` now fails with an
    -    HTTP 400 error naming the setting. Raise `index.max_regex_length` on the index to keep using such a pattern. On
    +    HTTP 400 error naming the setting. The limit is checked on each shard: when only some shards reject the pattern,
    +    because the indices have different limits or the cluster is partway through a rolling upgrade, the search returns the
    +    other shards' results and reports the rejections under `_shards.failures`, unless `allow_partial_search_results` is
    +    `false`. Raise `index.max_regex_length` on the index to keep using such a pattern. On
         Elastic Cloud Serverless the setting cannot be changed; pass a long list of alternatives as an array of exact values
         in `include` or `exclude` instead, which is not a regular expression and is not bounded by the setting. A pattern
         whose automaton is too complex to build also fails with an HTTP 400 error, and one whose build would exceed the request
    -    circuit breaker fails with an HTTP 429 error, as the `regexp` query does. A pattern that uses `~` as a literal character
    -    must escape it as `\~`.
    +    circuit breaker fails with an HTTP 429 error, as the `regexp` query does. A PromQL query whose `=~` or `!~` pattern is

    Severity: P3 (Low)

    The partial-results caveat also applies to aggregation regex complexity errors and request-breaker trips during compilation. Those errors are reported as shard failures too, so a search can return HTTP 200 with _shards.failures rather than the HTTP 400 or 429 promised here. Scope those status codes to searches that fail outright.

    <sub>Generated by Libra. React with 👍 or 👎 to give feedback on this comment.</sub>

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Nov 30, 2026 15:59 UTC
    Code Review
    docs/reference/query-languages/promql/_snippets/compatibility/basics.md:1
    @@ -75,6 +75,8 @@ Time durations, such as `1h30m`, and duration arithmetic, such as `x[5m + 1m]`.
     
     A metric name with the label matchers `=`, `!=`, `=~`, and `!~`, such as `http_requests_total{job="api", code=~"5.."}`.
     
    +{applies_to}`stack: ga 9.7+` {applies_to}`serverless: ga` The pattern of a `=~` or `!~` matcher takes at most 1000 characters.

    Severity: P3 (Low)

    The limit is 1,000 UTF-16 code units, not 1,000 Unicode characters. Supplementary characters count twice, so a matcher can be rejected even when its pattern is under the documented character limit. Clarify the unit here and in the changelog.

    <sub>Generated by Libra. React with 👍 or 👎 to give feedback on this comment.</sub>

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Nov 30, 2026 15:59 UTC
    Code Review
    rest-api-spec/src/yamlRestTest/resources/rest-api-spec/test/search/30_limits.yml:1
    @@ -313,3 +313,38 @@ setup:
                     field: foo
                     include: "b.*"
       - match: { aggregations.terms_agg.buckets.0.key: bar }
    +
    +  # The limit is each index's own and is checked on the shard, so across indices with different limits the shards that
    +  # reject the pattern fail and the others answer.
    +  - do:
    +      indices.create:
    +        index: test_default_regex
    +        body:
    +          mappings:
    +            properties:
    +              foo:
    +                type: keyword
    +
    +  - do:
    +      index:
    +        index: test_default_regex
    +        id: "1"
    +        refresh: true
    +        body: { foo: bar }
    +
    +  - do:
    +      search:
    +        rest_total_hits_as_int: true
    +        index: test_default_regex,test_short_regex
    +        body:
    +          size: 0
    +          aggs:
    +            terms_agg:
    +              terms:
    +                field: foo
    +                include: "aaaaaaaaaaaaaaaaaaaaa"
    +  - gte: { _shards.successful: 1 }
    +  - gte: { _shards.failed: 1 }
    +  - match:
    +      _shards.failures.0.index: /(.*:)?test_short_regex/
    +  - length: { aggregations.terms_agg.buckets: 0 }

    Severity: P3 (Low)

    This test would still pass if the successful shard's buckets were discarded: the only value in test_default_regex is bar, which the include pattern does not match. Index a matching value there and assert its bucket and count so the test verifies that the successful shard's aggregation data survives the other shard's rejection.

    <sub>Generated by Libra. React with 👍 or 👎 to give feedback on this comment.</sub>

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Nov 30, 2026 15:59 UTC
    Code Review
    x-pack/plugin/mapper-version/src/main/java/org/elasticsearch/xpack/versionfield/VersionStringFieldMapper.java:1
    @@ -205,13 +207,18 @@ public Query regexpQuery(
                     );
                 }
                 Term term = new Term(name(), new BytesRef(value));
    -            Automaton automaton = AutomatonQueries.toRegexpAutomaton(
    -                term,
    -                syntaxFlags,
    -                matchFlags,
    -                maxDeterminizedStates,
    -                context.getCircuitBreaker()
    +            CircuitBreaker breaker = context.getCircuitBreaker();
    +            Automaton automaton = AutomatonQueries.toRegexpAutomaton(term, syntaxFlags, matchFlags, maxDeterminizedStates, breaker);
    +            // An AutomatonQuery compiles the DFA into its UTF-8 run form as it is constructed, which peaks well above the DFA.
    +            return AutomatonQueries.reservingCompile(
    +                automaton,
    +                breaker,
    +                ChildMemoryCircuitBreaker.CATEGORY_REGEXP,
    +                () -> decodingRegexpQuery(term, automaton, method)
                 );

    Severity: P2 (Medium)

    Keep the compiled version automaton charged after construction. reservingCompile drops the entire reservation, but a compound query keeps the returned automaton alive while it builds subsequent clauses. The query visitor's running estimate is not on the breaker yet, so a later compile can pass its breaker check even when its reservation plus the earlier live automata exceeds the limit. Swap the build reservation for the query's retained size and mark it precharged, as the regexp builder does.

    <sub>Generated by Libra. React with 👍 or 👎 to give feedback on this comment.</sub>

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Nov 30, 2026 17:10 UTC
    Code Review
    rest-api-spec/src/yamlRestTest/resources/rest-api-spec/test/search/30_limits.yml:1
    @@ -313,3 +313,40 @@ setup:
                     field: foo
                     include: "b.*"
       - match: { aggregations.terms_agg.buckets.0.key: bar }
    +
    +  # The limit is each index's own and is checked on the shard, so across indices with different limits the shards that
    +  # reject the pattern fail and the others answer.
    +  - do:
    +      indices.create:
    +        index: test_default_regex
    +        body:
    +          mappings:
    +            properties:
    +              foo:
    +                type: keyword
    +
    +  - do:
    +      index:
    +        index: test_default_regex
    +        id: "1"
    +        refresh: true
    +        body: { foo: aaaaaaaaaaaaaaaaaaaaa }

    Severity: P3 (Low)

    Keep a nonmatching value in test_default_regex alongside the new matching one. With only a matching value on the successful side, the mixed-index assertions also pass if the short-limit shard rejects the pattern correctly but the successful shard ignores include and returns unfiltered buckets.

    <sub>Generated by Libra. React with 👍 or 👎 to give feedback on this comment.</sub>

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Nov 30, 2026 17:10 UTC
    Code Review
    rest-api-spec/src/yamlRestTest/resources/rest-api-spec/test/search/30_limits.yml:1
    @@ -313,3 +313,38 @@ setup:
                     field: foo
                     include: "b.*"
       - match: { aggregations.terms_agg.buckets.0.key: bar }
    +
    +  # The limit is each index's own and is checked on the shard, so across indices with different limits the shards that
    +  # reject the pattern fail and the others answer.
    +  - do:
    +      indices.create:
    +        index: test_default_regex
    +        body:
    +          mappings:
    +            properties:
    +              foo:
    +                type: keyword
    +
    +  - do:
    +      index:
    +        index: test_default_regex
    +        id: "1"
    +        refresh: true
    +        body: { foo: bar }
    +
    +  - do:
    +      search:
    +        rest_total_hits_as_int: true
    +        index: test_default_regex,test_short_regex
    +        body:
    +          size: 0
    +          aggs:
    +            terms_agg:
    +              terms:
    +                field: foo
    +                include: "aaaaaaaaaaaaaaaaaaaaa"
    +  - gte: { _shards.successful: 1 }
    +  - gte: { _shards.failed: 1 }
    +  - match:
    +      _shards.failures.0.index: /(.*:)?test_short_regex/
    +  - length: { aggregations.terms_agg.buckets: 0 }
    kosabogi kosabogi commented on code on Dec 01, 2026 10:50 UTC
    Code Review
    docs/reference/query-languages/promql/_snippets/compatibility/basics.md:1
    @@ -75,6 +75,8 @@ Time durations, such as `1h30m`, and duration arithmetic, such as `x[5m + 1m]`.
     
     A metric name with the label matchers `=`, `!=`, `=~`, and `!~`, such as `http_requests_total{job="api", code=~"5.."}`.
     
    +{applies_to}`stack: ga 9.7+` {applies_to}`serverless: ga` The pattern of a `=~` or `!~` matcher takes at most 1000 characters.

    nit: let's thousands separator, as in the other PromQL pages:

    {applies_to}`stack: ga 9.7+` {applies_to}`serverless: ga` The pattern of a `=~` or `!~` matcher can be at most 1,000 characters long.
    

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Dec 01, 2026 19:58 UTC
    Code Review
    docs/changelog/158570.yaml:1
    @@ -9,17 +9,22 @@ breaking:
         circuit breaker. The patterns are now compiled on the shard,
         with every step charged to the request circuit breaker and bounded by a fixed amount of work, so a pattern that is too
         complex to build is rejected instead of occupying a search thread. The `regexp` query and PromQL label matchers are
    -    built the same way and are bounded by the same amount of work. Both constructors of the pattern now compile it with
    +    built the same way and are bounded by the same amount of work, and the pattern of a PromQL label matcher is limited
    +    to `1000` characters. Both constructors of the pattern now compile it with
         the same flags, so `~` is the complement operator on every shard; before, a shard that received the request from
         another node treated `~` as a literal character.
       impact: >-
         A search whose aggregation uses an `include` or `exclude` pattern longer than `index.max_regex_length` now fails with an
    -    HTTP 400 error naming the setting. Raise `index.max_regex_length` on the index to keep using such a pattern. On
    +    HTTP 400 error naming the setting. The limit is checked on each shard: when only some shards reject the pattern,
    +    because the indices have different limits or the cluster is partway through a rolling upgrade, the search returns the
    +    other shards' results and reports the rejections under `_shards.failures`, unless `allow_partial_search_results` is
    +    `false`. Raise `index.max_regex_length` on the index to keep using such a pattern. On
         Elastic Cloud Serverless the setting cannot be changed; pass a long list of alternatives as an array of exact values
         in `include` or `exclude` instead, which is not a regular expression and is not bounded by the setting. A pattern
         whose automaton is too complex to build also fails with an HTTP 400 error, and one whose build would exceed the request
    -    circuit breaker fails with an HTTP 429 error, as the `regexp` query does. A pattern that uses `~` as a literal character
    -    must escape it as `\~`.
    +    circuit breaker fails with an HTTP 429 error, as the `regexp` query does. A PromQL query whose `=~` or `!~` pattern is
    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Dec 01, 2026 19:58 UTC
    Code Review
    x-pack/plugin/mapper-version/src/main/java/org/elasticsearch/xpack/versionfield/VersionStringFieldMapper.java:1
    @@ -205,13 +207,18 @@ public Query regexpQuery(
                     );
                 }
                 Term term = new Term(name(), new BytesRef(value));
    -            Automaton automaton = AutomatonQueries.toRegexpAutomaton(
    -                term,
    -                syntaxFlags,
    -                matchFlags,
    -                maxDeterminizedStates,
    -                context.getCircuitBreaker()
    +            CircuitBreaker breaker = context.getCircuitBreaker();
    +            Automaton automaton = AutomatonQueries.toRegexpAutomaton(term, syntaxFlags, matchFlags, maxDeterminizedStates, breaker);
    +            // An AutomatonQuery compiles the DFA into its UTF-8 run form as it is constructed, which peaks well above the DFA.
    +            return AutomatonQueries.reservingCompile(
    +                automaton,
    +                breaker,
    +                ChildMemoryCircuitBreaker.CATEGORY_REGEXP,
    +                () -> decodingRegexpQuery(term, automaton, method)
                 );
    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Dec 01, 2026 19:58 UTC
    Code Review
    rest-api-spec/src/yamlRestTest/resources/rest-api-spec/test/search/30_limits.yml:1
    @@ -313,3 +313,40 @@ setup:
                     field: foo
                     include: "b.*"
       - match: { aggregations.terms_agg.buckets.0.key: bar }
    +
    +  # The limit is each index's own and is checked on the shard, so across indices with different limits the shards that
    +  # reject the pattern fail and the others answer.
    +  - do:
    +      indices.create:
    +        index: test_default_regex
    +        body:
    +          mappings:
    +            properties:
    +              foo:
    +                type: keyword
    +
    +  - do:
    +      index:
    +        index: test_default_regex
    +        id: "1"
    +        refresh: true
    +        body: { foo: aaaaaaaaaaaaaaaaaaaaa }
    alighahramani-alig alighahramani-alig commented on code on Dec 01, 2026 20:16 UTC
    Code Review
    docs/reference/query-languages/promql/_snippets/compatibility/basics.md:1
    @@ -75,6 +75,8 @@ Time durations, such as `1h30m`, and duration arithmetic, such as `x[5m + 1m]`.
     
     A metric name with the label matchers `=`, `!=`, `=~`, and `!~`, such as `http_requests_total{job="api", code=~"5.."}`.
     
    +{applies_to}`stack: ga 9.7+` {applies_to}`serverless: ga` The pattern of a `=~` or `!~` matcher takes at most 1000 characters.

    ⚒️ Zug zug. _(Claude, the author's peon)_

    Not changing this one. It is true for a pattern with supplementary characters: the check is String.length(), as it is for index.max_regex_length. The regexp query page states that limit in characters too, so this line keeps the same word.

    <!-- zugzug:reply-to=4741794779 -->

    infra-vault-gh-plugin-prod[bot] infra-vault-gh-plugin-prod[bot] commented on code on Dec 01, 2026 20:17 UTC
    Code Review
    docs/reference/query-languages/promql/_snippets/compatibility/basics.md:1
    @@ -75,6 +75,8 @@ Time durations, such as `1h30m`, and duration arithmetic, such as `x[5m + 1m]`.
     
     A metric name with the label matchers `=`, `!=`, `=~`, and `!~`, such as `http_requests_total{job="api", code=~"5.."}`.
     
    +{applies_to}`stack: ga 9.7+` {applies_to}`serverless: ga` The pattern of a `=~` or `!~` matcher takes at most 1000 characters.

    The implementation confirms the distinction rather than resolving it: it rejects when regex.length() > maxRegexLength and reports that same length (LabelMatcher.java lines 213–223). In Java, String.length() counts UTF-16 code units, so a supplementary character contributes two; a pattern with fewer than 1,000 Unicode code points can therefore exceed this limit. The regexp page uses the same “characters” wording (lines 43–47), but matching that wording does not make the unit clearer. I’d describe the limit as 1,000 UTF-16 code units here (and in the changelog), or explicitly qualify what “characters” means.

    <sub>Generated by Libra. React with 👍 or 👎 to give feedback on this comment.</sub>

    Reviewers
    Assignees
    alighahramani-alig alighahramani-alig
    Labels
    risk: low confidence: 93.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 50% (MEDIUM) · Higher = larger blast radius
    50%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 93.3% · Lower = rushed or shallow review
    93.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 3.3% · Safe to merge
    3.3%