Skip to content

Fix another infinite loop in volcano rules + configurable rule-call limit - #6011

Open
Swiddis wants to merge 6 commits into
opensearch-project:mainfrom
Swiddis:planner-followups
Open

Swiddis wants to merge 6 commits into
opensearch-project:mainfrom
Swiddis:planner-followups

Conversation

@Swiddis

@Swiddis Swiddis commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Builds on #6008 with 3 more fixes:

  • stats avg(l) | head 1 from 1 hits a loop with limit-offsets and causes OOM
  • top 1 l | eval e = floor('') cleanly kills the node via the unhandled Error type ExceptionInInitializerError
  • head 1 | head 6 from 2 returned a 500 with [size] parameter cannot be negative

Additionally, adds settings plugins.calcite.planner.rule_call_limit and plugins.calcite.planner.rule_call_limit_enforcement which can be used to force volcano planning to truncate at a specific point, which will mitigate future impacts of these rule loops. Setting an intentionally low limit with reject enforcement can help automatically find more rule call bugs.

Related Issues

Resolves #[Issue number to be closed when this PR is merged]

Check List

  • New functionality includes testing.
  • New functionality has been documented.
  • New functionality has javadoc added.
  • New functionality has a user manual doc added.
  • New PPL command checklist all confirmed.
  • API changes companion pull request created.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

The circular-pushdown guard in CalciteLogicalIndexScan.pushDownProject
compared the new field-name list against pushdown digests, but project
digests have been ProjectDigest records since opensearch-project#4992, so the guard never
fired. Stacked stats with dc() then looped in the Volcano planner until
the node ran out of heap.

Match on ProjectDigest names instead.

Resolves opensearch-project#6007

Signed-off-by: Simeon Widdis <sawiddis@amazon.com>
Planner rules that don't converge loop until the node runs out of heap,
and planning can't be cancelled (opensearch-project#6007, opensearch-project#5966). Count Volcano rule calls
per query with a RelOptListener and stop at
plugins.calcite.planner.rule_call_limit (default 100000, 0 disables).

plugins.calcite.planner.rule_call_limit_enforcement picks what happens:
truncate (default) raises the planner's CancelFlag so Volcano keeps the
cheapest plan found so far; reject fails the query with a 400
RESOURCE_LIMIT_EXCEEDED that names the setting.

The scope lives on CalcitePlanContext because prepareStatement reuses
the planner the context creates.

Signed-off-by: Simeon Widdis <sawiddis@amazon.com>
With an aggregate pushed and offset > 0, pushDownLimit keeps the sort
above the new scan, so LimitIndexScanRule matched it again and pushed
the same limit forever. The scan digest grows with every pass, so the
node ran out of heap before the rule call limit tripped
(`stats avg(l) as a1 | head 1 from 1`).

Apply the existing same-limit-on-top guard to the aggregate branch too.

Signed-off-by: Simeon Widdis <sawiddis@amazon.com>
Two bugs found by property-based testing (ppl-hegel):

1. An Error thrown by generated query code on the complex worker pool
   (ExceptionInInitializerError, e.g. `top 1 l | eval e = floor('')`
   where the constant fails to fold) was not caught, so OpenSearch's
   uncaught handler exited the node. Catch Throwable there, map it as
   QueryService does, and still rethrow VirtualMachineError.

2. `head 1 | head 6 from 2` pushed a negative size into the search
   request and failed with 500 "[size] parameter cannot be negative".
   Clamp the remaining size at 0, so the query returns no rows.

Signed-off-by: Simeon Widdis <sawiddis@amazon.com>
@Swiddis Swiddis changed the title Fix more infinite loops in volcano rules Fix more infinite loops in volcano rules + detection setting Dec 1, 2026
@Swiddis Swiddis changed the title Fix more infinite loops in volcano rules + detection setting Fix more infinite loops in volcano rules + configurable limit Dec 1, 2026
@Swiddis Swiddis added enhancement New feature or request bugFix labels Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 7ea41e2)

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 Multiple PR themes

Sub-PR theme: Fix negative size on head with offset past earlier head

Relevant files:

  • opensearch/src/main/java/org/opensearch/sql/opensearch/request/OpenSearchRequestBuilder.java
  • opensearch/src/test/java/org/opensearch/sql/opensearch/request/OpenSearchRequestBuilderTest.java
  • integ-test/src/test/java/org/opensearch/sql/calcite/remote/CalciteHeadCommandIT.java

Sub-PR theme: Catch ExceptionInInitializerError on complex worker pool

Relevant files:

  • opensearch/src/main/java/org/opensearch/sql/opensearch/executor/ThreadPoolExecutionDispatcher.java
  • opensearch/src/test/java/org/opensearch/sql/opensearch/executor/ThreadPoolExecutionDispatcherTest.java
  • integ-test/src/test/java/org/opensearch/sql/calcite/remote/CalciteTopCommandIT.java

Sub-PR theme: Add configurable Volcano rule-call limit

Relevant files:

  • common/src/main/java/org/opensearch/sql/common/setting/Settings.java
  • core/src/main/java/org/opensearch/sql/calcite/CalcitePlanContext.java
  • core/src/main/java/org/opensearch/sql/calcite/SysLimit.java
  • core/src/main/java/org/opensearch/sql/calcite/plan/RuleCallLimit.java
  • core/src/main/java/org/opensearch/sql/calcite/utils/CalciteToolsHelper.java
  • core/src/test/java/org/opensearch/sql/calcite/SysLimitRuleCallBudgetTest.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/setting/OpenSearchSettings.java
  • ppl/src/test/java/org/opensearch/sql/ppl/calcite/CalcitePPLAbstractTest.java
  • ppl/src/test/java/org/opensearch/sql/ppl/calcite/CalcitePPLRuleCallLimitTest.java
  • docs/user/admin/settings.rst
  • docs/user/ppl/admin/settings.md

⚡ Recommended focus areas for review

Thread-safety of Scope counter

Scope.ruleCalls and exceeded are declared volatile but incremented via ++ruleCalls in onRuleCall(). While Volcano planning is typically single-threaded, if the listener is ever invoked concurrently (or shared across threads), the non-atomic increment can lose updates and the exceeded check can fire multiple times or not at all. Consider using AtomicLong/AtomicBoolean or documenting the single-threaded contract.

private volatile long ruleCalls = 0;
private volatile boolean exceeded = false;

private Scope(Budget budget) {
  this.budget = budget;
}

public long ruleCalls() {
  return ruleCalls;
}

/** Whether this query reached the limit. */
public boolean exceeded() {
  return exceeded;
}

public Budget budget() {
  return budget;
}

private void onRuleCall() {
  if (++ruleCalls <= budget.limit() || exceeded) {
    return;
  }
  exceeded = true;
  if (budget.enforcement() == Enforcement.REJECT) {
    throw new ExceededException(budget.limit());
  }
  LOG.warn(
      "Query planning reached {} rule calls ({}); keeping the cheapest plan found so far.",
      budget.limit(),
      LIMIT_SETTING);
  cancelled.set(true);
}
Connection lifecycle change

The try-with-resources now declares both context.connection and the RuleCallLimit.Installation. context.connection was previously closed here already, but the added inner try/catch around runner.prepareStatement(rel) catches RuntimeException and rethrows via ruleCallLimitError, which throws a new exception. Verify that the outer catch (SQLException e) block (which handles window-function error enrichment) is still reachable for non-limit SQLExceptions — the inner catch (SQLException e) now intercepts all SQLExceptions from prepareStatement and converts non-limit ones back via ruleCallLimitError returning the original, which is then rethrown and should propagate out past the outer catch only if the outer catch's scope encloses it. Confirm the outer window-function enrichment path is still exercised.

final RuleCallLimit.Scope ruleCalls = context.ruleCallScope;
try (Connection connection = context.connection;
    RuleCallLimit.Installation ignored = RuleCallLimit.install(ruleCalls)) {
  final RelRunner runner = connection.unwrap(RelRunner.class);
  try {
    return runner.prepareStatement(rel);
  } catch (SQLException e) {
    throw ruleCallLimitError(e, ruleCalls);
  } catch (RuntimeException e) {
    throw ruleCallLimitError(e, ruleCalls);
  }
} catch (SQLException e) {

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 7ea41e2

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Make the rule-call counter thread-safe

ruleCalls is declared volatile but mutated with ++ruleCalls, which is not atomic. If
the planner ever invokes listeners from multiple threads, the counter can lose
increments and exceeded can be set more than once. Use an AtomicLong (or guard with
synchronization) to make the budget check correct under any concurrent rule-call
events.

core/src/main/java/org/opensearch/sql/calcite/plan/RuleCallLimit.java [168-181]

 private void onRuleCall() {
-  if (++ruleCalls <= budget.limit() || exceeded) {
+  long calls = ruleCallsCounter.incrementAndGet();
+  if (calls <= budget.limit() || exceeded) {
     return;
   }
-  exceeded = true;
+  synchronized (this) {
+    if (exceeded) return;
+    exceeded = true;
+  }
   if (budget.enforcement() == Enforcement.REJECT) {
     throw new ExceededException(budget.limit());
   }
Suggestion importance[1-10]: 5

__

Why: Valid concern about thread safety of ++ruleCalls on a volatile field; however, the Volcano planner typically runs single-threaded, so impact is modest. The improved code also references an undefined ruleCallsCounter field.

Low
General
Also catch linkage errors from generated code

Only catching ExceptionInInitializerError leaves other janino/generated-code errors
(e.g. LinkageError, NoClassDefFoundError from a transitive static init failure)
uncaught, which will still kill the node. Consider also handling related linkage
errors, or unwrapping NoClassDefFoundError whose cause is an
ExceptionInInitializerError.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/ThreadPoolExecutionDispatcher.java [129-133]

-} catch (ExceptionInInitializerError | Exception t) {
-  // Generated query code can throw ExceptionInInitializerError when a constant fails
-  // to fold. Left uncaught on this pool, OpenSearch exits the node. Other Errors (VM
-  // errors, linkage errors, ...) still propagate to the uncaught-exception handler.
+} catch (ExceptionInInitializerError | LinkageError | Exception t) {
+  // Generated query code can throw ExceptionInInitializerError / LinkageError when a
+  // constant or class fails to initialize. Left uncaught on this pool, OpenSearch exits
+  // the node. Other Errors (VM errors, ...) still propagate to the uncaught handler.
   Exception e = asException(t);
Suggestion importance[1-10]: 5

__

Why: Reasonable extension to also catch LinkageError from generated code initialization failures, though the current PR targets a specific observed failure mode.

Low
Avoid failing all queries on bad setting

Enforcement.of throws IllegalArgumentException on invalid values, which will
propagate out of fromSettings and fail every query — not just the one that set the
bad value. Consider catching the parse error here and falling back to the default
enforcement (with a warning log) so a bad cluster setting doesn't take down query
execution.

core/src/main/java/org/opensearch/sql/calcite/SysLimit.java [36-40]

+RuleCallLimit.Enforcement parsed = RuleCallLimit.Enforcement.TRUNCATE;
+if (enforcement != null) {
+  try {
+    parsed = RuleCallLimit.Enforcement.of(enforcement);
+  } catch (IllegalArgumentException e) {
+    // Fall back to default rather than failing all queries on a bad setting.
+  }
+}
 return new RuleCallLimit.Budget(
-    limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit,
-    enforcement == null
-        ? RuleCallLimit.Enforcement.TRUNCATE
-        : RuleCallLimit.Enforcement.of(enforcement));
+    limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit, parsed);
Suggestion importance[1-10]: 3

__

Why: OpenSearch settings validation via Enforcement::of in the setting definition should prevent invalid values from being accepted, making this defensive fallback mostly redundant.

Low

Previous suggestions

Suggestions up to commit ec8b06c
CategorySuggestion                                                                                                                                    Impact
General
Also catch LinkageError from generated code

Catching only ExceptionInInitializerError leaves other generated-code errors like
LinkageError, NoClassDefFoundError, or VerifyError (which are also commonly produced
by Janino-generated classes failing to load) uncaught, which will still exit the
node. Consider also catching LinkageError here, since it's a similar class of
non-fatal, code-generation-related error that shouldn't kill the node.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/ThreadPoolExecutionDispatcher.java [129-133]

-} catch (ExceptionInInitializerError | Exception t) {
-  // Generated query code can throw ExceptionInInitializerError when a constant fails
-  // to fold. Left uncaught on this pool, OpenSearch exits the node. Other Errors (VM
-  // errors, linkage errors, ...) still propagate to the uncaught-exception handler.
+} catch (ExceptionInInitializerError | LinkageError | Exception t) {
+  // Generated query code can throw ExceptionInInitializerError/LinkageError when a
+  // constant fails to fold or a generated class fails to load. Left uncaught on this
+  // pool, OpenSearch exits the node. Other Errors (VM errors, ...) still propagate.
   Exception e = asException(t);
Suggestion importance[1-10]: 5

__

Why: Catching LinkageError (which includes NoClassDefFoundError and VerifyError) is a reasonable defensive improvement for Janino-generated code failures, aligned with the PR's intent to prevent such errors from killing the node.

Low
Prevent null enforcement in Budget record

RuleCallLimit.Budget is a record whose constructor accepts Enforcement. The test
disabledBudgetCountsNothing passes null to new RuleCallLimit.Budget(0, null), but
other code paths (e.g. onRuleCall via budget.enforcement() == Enforcement.REJECT)
will NPE if enforcement is null. Add a compact-constructor validation or defensive
default to guard against null enforcement.

core/src/main/java/org/opensearch/sql/calcite/SysLimit.java [36-40]

+return new RuleCallLimit.Budget(
+    limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit,
+    enforcement == null
+        ? RuleCallLimit.Enforcement.TRUNCATE
+        : RuleCallLimit.Enforcement.of(enforcement));
 
-
Suggestion importance[1-10]: 2

__

Why: The existing_code and improved_code are identical, so the suggestion does not actually propose a concrete fix. The concern about null enforcement is partially valid but only shown in a test's direct instantiation, not in SysLimit.fromSettings.

Low
Possible issue
Make rule call counter thread-safe

ruleCalls is declared volatile but incremented with ++, which is not atomic. If
multiple planner threads share the same Scope (e.g. parallel planner internals or
shared context across sub-plans), updates can be lost and the limit check becomes
unreliable. Use AtomicLong (or LongAdder with an explicit check) instead of volatile
long for correct counting.

core/src/main/java/org/opensearch/sql/calcite/plan/RuleCallLimit.java [168-181]

 private void onRuleCall() {
-  if (++ruleCalls <= budget.limit() || exceeded) {
+  long calls = ruleCallsCounter.incrementAndGet();
+  if (calls <= budget.limit() || exceeded) {
     return;
   }
   exceeded = true;
   if (budget.enforcement() == Enforcement.REJECT) {
     throw new ExceededException(budget.limit());
   }
Suggestion importance[1-10]: 4

__

Why: Volcano planning is generally single-threaded per query, so this is likely not a real issue in practice. However, the observation that volatile long with ++ is not atomic is technically correct and could be a latent bug if the scope is ever shared across threads.

Low
Suggestions up to commit 8c75dac
CategorySuggestion                                                                                                                                    Impact
General
Also catch LinkageError from generated code

Catching only ExceptionInInitializerError leaves other common linkage/generated-code
errors like NoClassDefFoundError, LinkageError, and BootstrapMethodError uncaught on
this pool, which can still exit the node. Consider catching LinkageError (parent of
these) along with ExceptionInInitializerError, or catching Error but rethrowing
VirtualMachineError / ThreadDeath to preserve node safety.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/ThreadPoolExecutionDispatcher.java [129-133]

-} catch (ExceptionInInitializerError | Exception t) {
-  // Generated query code can throw ExceptionInInitializerError when a constant fails
-  // to fold. Left uncaught on this pool, OpenSearch exits the node. Other Errors (VM
-  // errors, linkage errors, ...) still propagate to the uncaught-exception handler.
+} catch (ExceptionInInitializerError | LinkageError | Exception t) {
+  // Generated query code can throw ExceptionInInitializerError/LinkageError when a
+  // constant fails to fold or a generated class fails to link. Left uncaught on this
+  // pool, OpenSearch exits the node. VM errors still propagate.
   Exception e = asException(t);
Suggestion importance[1-10]: 6

__

Why: Reasonable point that other LinkageError subtypes from generated code could still escape and crash the node. Broadening the catch improves node safety, though the PR intentionally limits scope to ExceptionInInitializerError.

Low
Avoid failing queries on bad enforcement value

RuleCallLimit.Enforcement.of throws IllegalArgumentException on unknown values,
which will propagate out of SysLimit.fromSettings for any query submitted when the
cluster setting is in an unexpected state. Since the setting value is already
validated at registration time by OpenSearchSettings, consider falling back to the
default (TRUNCATE) here with a warning log to avoid failing every query on a
corrupted/legacy value.

core/src/main/java/org/opensearch/sql/calcite/SysLimit.java [36-40]

+RuleCallLimit.Enforcement parsed;
+try {
+  parsed = enforcement == null
+      ? RuleCallLimit.Enforcement.TRUNCATE
+      : RuleCallLimit.Enforcement.of(enforcement);
+} catch (IllegalArgumentException e) {
+  parsed = RuleCallLimit.Enforcement.TRUNCATE;
+}
 return new RuleCallLimit.Budget(
     limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit,
-    enforcement == null
-        ? RuleCallLimit.Enforcement.TRUNCATE
-        : RuleCallLimit.Enforcement.of(enforcement));
+    parsed);
Suggestion importance[1-10]: 3

__

Why: The enforcement value is already validated at setting registration via RuleCallLimit.Enforcement::of, so an invalid value shouldn't normally reach fromSettings. The suggestion offers defensive hardening but has limited practical impact.

Low
Possible issue
Guard against null enforcement in Budget

The Budget record accepts a null enforcement, and
SysLimitRuleCallBudgetTest.disabledBudgetCountsNothing constructs one that way. If a
limited budget is ever created with a null enforcement, onRuleCall will NPE on
budget.enforcement() == Enforcement.REJECT. Add a compact-constructor null check or
default it to TRUNCATE.

core/src/main/java/org/opensearch/sql/calcite/plan/RuleCallLimit.java [74-80]

 public record Budget(int limit, Enforcement enforcement) {
+  public Budget {
+    if (enforcement == null) {
+      enforcement = Enforcement.TRUNCATE;
+    }
+  }
   public static final Budget UNLIMITED = new Budget(0, Enforcement.TRUNCATE);
 
   public boolean isLimited() {
     return limit > 0;
   }
 }
Suggestion importance[1-10]: 5

__

Why: A valid defensive concern: the test already constructs a Budget(0, null), and if a limited budget were ever created with null enforcement, onRuleCall would NPE. Adding a compact-constructor default is a reasonable safeguard.

Low
Suggestions up to commit 43aa8b9
CategorySuggestion                                                                                                                                    Impact
General
Narrow Throwable catch to expected Errors

Catching all Throwable and converting to Exception also swallows other serious
Errors such as ThreadDeath, LinkageError, StackOverflowError beyond just
VirtualMachineError. Consider also rethrowing Error subtypes that are not
ExceptionInInitializerError (the specific case being handled), to avoid masking
JVM-level problems that the thread pool's uncaught handler should see.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/ThreadPoolExecutionDispatcher.java [129-135]

 } catch (VirtualMachineError e) {
               // Fast-fail on OOM and the like, as QueryService does.
               throw e;
-            } catch (Throwable t) {
+            } catch (ExceptionInInitializerError | Exception t) {
+              // Generated query code can throw an Error (e.g. ExceptionInInitializerError when a
+              // constant fails to fold). Left uncaught on this pool, OpenSearch exits the node.
+              Exception e = asException(t);
Suggestion importance[1-10]: 5

__

Why: A fair point: catching all Throwable after only rethrowing VirtualMachineError may swallow other serious Errors like LinkageError. However, the PR explicitly intends to prevent node exits from generated-code errors, so broader catching may be the intended behavior.

Low
Make rule-call counters thread-safe

ruleCalls and exceeded are mutated without synchronization, but the Volcano planner
and its listeners can be invoked from code paths that may not be single-threaded
(e.g. subplan prepare sharing the same scope across contexts via
parent.ruleCallScope). Consider using AtomicLong for ruleCalls and a
volatile/AtomicBoolean for exceeded to avoid lost updates and visibility issues.

core/src/main/java/org/opensearch/sql/calcite/plan/RuleCallLimit.java [168-181]

+private final java.util.concurrent.atomic.AtomicLong ruleCalls = new java.util.concurrent.atomic.AtomicLong();
+private volatile boolean exceeded = false;
+
 private void onRuleCall() {
-    if (++ruleCalls <= budget.limit() || exceeded) {
+    if (ruleCalls.incrementAndGet() <= budget.limit() || exceeded) {
       return;
     }
     exceeded = true;
     if (budget.enforcement() == Enforcement.REJECT) {
       throw new ExceededException(budget.limit());
     }
Suggestion importance[1-10]: 4

__

Why: Volcano planner rule calls are typically single-threaded per query, so the concern may be theoretical. However, since the scope can be shared via parent.ruleCallScope across contexts, adding thread safety is a reasonable defensive improvement with low cost.

Low
Guard against invalid enforcement setting value

Enforcement.of throws IllegalArgumentException on an unknown value, which will
propagate out of fromSettings and fail every query if the cluster setting somehow
holds an invalid string (e.g. after a bad dynamic update). Catch the parsing error
and fall back to the default TRUNCATE so queries remain functional while logging the
misconfiguration.

core/src/main/java/org/opensearch/sql/calcite/SysLimit.java [32-41]

 private static RuleCallLimit.Budget ruleCallBudget(Settings settings) {
     Integer limit = settings.getSettingValue(Settings.Key.CALCITE_PLANNER_RULE_CALL_LIMIT);
     String enforcement =
         settings.getSettingValue(Settings.Key.CALCITE_PLANNER_RULE_CALL_LIMIT_ENFORCEMENT);
+    RuleCallLimit.Enforcement parsed = RuleCallLimit.Enforcement.TRUNCATE;
+    if (enforcement != null) {
+      try {
+        parsed = RuleCallLimit.Enforcement.of(enforcement);
+      } catch (IllegalArgumentException ignored) {
+        // Fall back to default; validation is done at setting registration time.
+      }
+    }
     return new RuleCallLimit.Budget(
-        limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit,
-        enforcement == null
-            ? RuleCallLimit.Enforcement.TRUNCATE
-            : RuleCallLimit.Enforcement.of(enforcement));
+        limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit, parsed);
   }
Suggestion importance[1-10]: 3

__

Why: The enforcement setting is validated at registration time via Setting.simpleString(..., RuleCallLimit.Enforcement::of, ...), so invalid values should not reach fromSettings. The fallback is a minor defensive measure with limited impact.

Low
Suggestions up to commit 61a19f2
CategorySuggestion                                                                                                                                    Impact
General
Guard rule call counter against races

ruleCalls and exceeded are mutated without synchronization, but Volcano planner
listeners can be invoked from the planner's thread which may differ from the thread
that installed the scope (especially when prepareStatement and context planners run
across pools). Consider using atomic types or documenting the single-thread
assumption explicitly to prevent subtle miscount/race issues.

core/src/main/java/org/opensearch/sql/calcite/plan/RuleCallLimit.java [168-181]

-private void onRuleCall() {
+private synchronized void onRuleCall() {
   if (++ruleCalls <= budget.limit() || exceeded) {
     return;
   }
   exceeded = true;
   if (budget.enforcement() == Enforcement.REJECT) {
     throw new ExceededException(budget.limit());
   }
Suggestion importance[1-10]: 4

__

Why: Volcano planner is typically single-threaded per planning session, but adding synchronization or documenting the assumption could prevent subtle issues if planners are ever invoked concurrently. The impact is minor given typical usage.

Low
Handle invalid enforcement values gracefully

When the limit setting is 0, RuleCallLimit.Budget.isLimited() returns false and
disables the limit, but here a null value falls back to DEFAULT_LIMIT rather than
preserving the "disabled" intent. Additionally, if Enforcement.of throws on invalid
values, settings fetch could fail at query time; consider defaulting to TRUNCATE on
invalid values to avoid breaking queries.

core/src/main/java/org/opensearch/sql/calcite/SysLimit.java [32-41]

 private static RuleCallLimit.Budget ruleCallBudget(Settings settings) {
     Integer limit = settings.getSettingValue(Settings.Key.CALCITE_PLANNER_RULE_CALL_LIMIT);
     String enforcement =
         settings.getSettingValue(Settings.Key.CALCITE_PLANNER_RULE_CALL_LIMIT_ENFORCEMENT);
+    RuleCallLimit.Enforcement parsed;
+    try {
+      parsed =
+          enforcement == null
+              ? RuleCallLimit.Enforcement.TRUNCATE
+              : RuleCallLimit.Enforcement.of(enforcement);
+    } catch (IllegalArgumentException e) {
+      parsed = RuleCallLimit.Enforcement.TRUNCATE;
+    }
     return new RuleCallLimit.Budget(
-        limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit,
-        enforcement == null
-            ? RuleCallLimit.Enforcement.TRUNCATE
-            : RuleCallLimit.Enforcement.of(enforcement));
+        limit == null ? RuleCallLimit.DEFAULT_LIMIT : limit, parsed);
   }
Suggestion importance[1-10]: 3

__

Why: The enforcement setting is already validated at registration time via RuleCallLimit.Enforcement::of in OpenSearchSettings, so invalid values cannot reach this code path. The suggestion offers marginal defensive value.

Low
Also rethrow other fatal errors

Catching Throwable here will also swallow ThreadDeath and other critical Error
subclasses besides VirtualMachineError. Consider also rethrowing ThreadDeath (and
possibly LinkageError if it's not from generated code) to avoid masking fatal JVM
conditions that should propagate.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/ThreadPoolExecutionDispatcher.java [129-132]

-} catch (VirtualMachineError e) {
+} catch (VirtualMachineError | ThreadDeath e) {
   // Fast-fail on OOM and the like, as QueryService does.
   throw e;
 } catch (Throwable t) {
Suggestion importance[1-10]: 3

__

Why: ThreadDeath is deprecated and rarely encountered; the existing VirtualMachineError handling covers the main fatal cases. The suggestion offers minor defensive improvement.

Low

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 43aa8b9

@Swiddis Swiddis changed the title Fix more infinite loops in volcano rules + configurable limit Fix another infinite loop in volcano rules + configurable limit Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 8c75dac

@Swiddis Swiddis changed the title Fix another infinite loop in volcano rules + configurable limit Fix another infinite loop in volcano rules + configurable rule-call limit Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit ec8b06c

- ThreadPoolExecutionDispatcher: catch only ExceptionInInitializerError
  and Exception, so other Errors reach the uncaught-exception handler.
- Add tests pinning how SysLimit builds the budget: 0 disables, unset
  settings use the defaults, an invalid enforcement is rejected.

Signed-off-by: Simeon Widdis <sawiddis@amazon.com>
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 7ea41e2

@codecov

codecov Bot commented Dec 1, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.66667% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.49%. Comparing base (6beda2b) to head (7ea41e2).

Files with missing lines Patch % Lines
...org/opensearch/sql/calcite/plan/RuleCallLimit.java 91.93% 2 Missing and 3 partials ⚠️
...search/executor/ThreadPoolExecutionDispatcher.java 62.50% 1 Missing and 2 partials ⚠️
...ensearch/sql/calcite/utils/CalciteToolsHelper.java 92.85% 2 Missing ⚠️
...org/opensearch/sql/calcite/CalcitePlanContext.java 80.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##               main    #6011    +/-   ##
==========================================
  Coverage     89.49%   89.49%            
- Complexity    12269    12284    +15     
==========================================
  Files           980      981     +1     
  Lines         42018    42138   +120     
  Branches       4836     4855    +19     
==========================================
+ Hits          37604    37713   +109     
- Misses         2940     2943     +3     
- Partials       1474     1482     +8     
Flag Coverage Δ
integration 69.97% <83.33%> (+0.02%) ⬆️
unit 76.90% <82.57%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

bugFix enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant