Skip to content

perf(#6174): fold a constant-false filter and LIMIT 0 at plan time instead of scanning the target - #6181

Merged
lvca merged 6 commits into
mainfrom
issue-6174-constant-false-filter-fold
Aug 14, 2026
Merged

lvca merged 6 commits into
mainfrom
issue-6174-constant-false-filter-fold

Conversation

@lvca

@lvca lvca commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

Fixes #6174.

The problem

The SQL planner had no notion of a filter that is false for every row. WHERE 1=0 was evaluated per record like
any other condition, so

SELECT * FROM (SELECT name FROM Character) SPARK_GEN_SUBQ_0 WHERE 1=0

scanned every Character, evaluated 1=0 once per record and discarded all of them. That is the shape Spark, and
several BI tools over the Postgres wire, send to discover a query's schema - one probe per pushed-down query,
against the real target. LIMIT 0 is the other spelling of the same intent and cost the same.

The fix

The recognition lives on the AST, next to the isAlwaysTrue() that was already there:

  • BooleanExpression.isAlwaysFalse(CommandContext) - default false, overridden structurally by AndBlock (false
    when any term is), OrBlock (false only when every alternative is), ParenthesisBlock (delegates) and
    BinaryCondition (folds the comparison). Structural rather than over flatten()'s DNF: it is O(n) instead of
    the cartesian product a DNF expansion of a wide OR produces, and it answers the same question.
  • BinaryCondition folds only when both operands are literals (Expression.isLiteral() /
    MathExpression.isLiteral() / BaseExpression.isLiteral()), and folds by calling the very same
    evaluate() the filter step would have called, so the fold and the runtime can never disagree. A bound parameter
    is excluded because the plan outlives the execution that bound it; a function call is excluded because nothing on
    SQLFunction marks a function as pure - isEarlyCalculated() is not a purity check.
  • Limit.isAlwaysEmpty() for a literal LIMIT 0 (not a parameter, not an expression).

SelectExecutionPlanner reads that off the clauses as the statement wrote them (before optimizeQuery()
rearranges them into index searches) and, after the target has been planned, drops the fetch steps and chains an
EmptySourceStep instead. The rest of the plan is untouched.

Three things the fold deliberately keeps:

  • target validation: the fetch is planned and then discarded, so SELECT FROM ATypeThatDoesNotExist WHERE 1=0
    still reports the missing type instead of quietly returning nothing;
  • the aggregation semantics: everything downstream of the fetch stays and receives no row, which is exactly
    what it receives today from the filter being removed - SELECT count(*) FROM T WHERE 1=0 still returns its one
    row with 0, and with a GROUP BY still returns none;
  • a LET evaluated once per statement: it is chained ahead of the empty source, which pulls it exactly like
    EmptyStep does.

EmptySourceStep is a new step rather than a reuse of EmptyStep because EmptyStep.canBeCached() is
(deliberately) false: it encodes one execution's data. "This statement cannot return a row" is a property of
its text, so the folded plan is cacheable.

Because DELETE/UPDATE build their target through SelectExecutionPlanner, they are covered by the same code.

Two behaviour changes, and a wrong answer found next to them

SELECT count(*) FROM T LIMIT 0 used to return one row: count(*) on a bare type is answered by a hardwired plan
that replaces the whole step chain and returns before any LIMIT/SKIP step is chained. It now returns no rows.
This is the SQL twin of the Cypher defect fixed in #5715.

The same hole was a wrong answer for SKIP, on all three hardwired plans: SELECT count(*) FROM T SKIP 1 and
SELECT max(indexedProperty) FROM T SKIP 1 handed back the very row they were told to skip. Both now chain the
statement's SKIP/LIMIT themselves, which costs nothing on a plan that produces one row.

Finally, a LIMIT 0 is folded whatever the WHERE says, so - unlike the constant-false fold, which never reaches
a function - the filter is not evaluated at all. The only way to observe that is a predicate that raises:
SELECT * FROM T WHERE 1/0 = 1 reports a division by zero, and with LIMIT 0 it now returns an empty result.

Reuse over duplication

PostgresNetworkExecutor.isAlwaysFalse (added in #6172) is gone: the probe detection now calls
WhereClause.isAlwaysFalse(), removing ~90 lines that duplicated the recognition.

Tests

New ConstantFalseFilterFoldingTest (24 tests), verified red on main for the folding cases. It asserts the plan
shape (no FetchFrom*/CountFrom* step anywhere, including inside sub-plans) and the readRecord statistic, not
only that zero rows come back - the current behaviour already returns zero rows, it just reads the whole type to do
it. It also pins what must NOT be folded: a bound parameter, a function call, a satisfiable OR branch, NOT (1=0), LIMIT ? and the LIMIT -1 "unlimited" sentinel.

Run: engine com.arcadedb.query.** (10947 tests), the rest of the engine module, postgresw units + integration.

…stead of scanning the target

The SQL planner had no notion of a filter that is false for every row, so a schema probe -
`SELECT * FROM (SELECT name FROM Character) SPARK_GEN_SUBQ_0 WHERE 1=0`, which is what Spark and
several BI tools send over the Postgres wire to discover a query's columns - scanned the whole
target, evaluated `1=0` once per record and discarded all of them. `LIMIT 0` is the other spelling
of the same intent and cost the same.

The recognition now lives on the AST, next to the `isAlwaysTrue()` that was already there:
`BooleanExpression.isAlwaysFalse(CommandContext)` defaults to false and is overridden structurally
by AndBlock (false when any term is), OrBlock (false only when every alternative is),
ParenthesisBlock and BinaryCondition. A comparison is folded only when both operands are literals
(`Expression.isLiteral()`), and it is folded by calling the very same `evaluate()` the filter step
would have called, so the fold and the runtime cannot disagree. A bound parameter is excluded
because the plan outlives the execution that bound it; a function call is excluded because nothing
on SQLFunction marks a function as pure. `Limit.isAlwaysEmpty()` covers a literal `LIMIT 0`.

SelectExecutionPlanner reads that off the clauses as the statement wrote them, before optimizeQuery()
rearranges them into index searches, and - after the target has been planned, so a missing type is
still reported - drops the fetch steps and chains an EmptySourceStep in their place. Everything
downstream of the fetch stays and receives no row, which is exactly what it receives today from the
filter being removed: `SELECT count(*) FROM T WHERE 1=0` still returns its one row with 0, and with a
GROUP BY still returns none. A LET evaluated once per statement is chained ahead of the empty source
and still runs. DELETE and UPDATE build their target through the same planner, so they are covered.

EmptySourceStep is a new step rather than a reuse of EmptyStep because EmptyStep is deliberately not
cacheable: it encodes one execution's data, while "this statement cannot return a row" is a property
of its text.

One behaviour change: `SELECT count(*) FROM T LIMIT 0` used to return one row, because the hardwired
count plan returns before any LIMIT/SKIP step is chained. It now returns no rows - the SQL twin of
the Cypher defect fixed in #5715.

PostgresNetworkExecutor's own copy of the recognition (added in #6172) is gone; the probe detection
calls WhereClause.isAlwaysFalse() instead.
@mergify

mergify Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics -2 complexity

Metric Results
Complexity -2

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review

Went through the full diff (planner, AST isAlwaysFalse/isLiteral additions, EmptySourceStep, the Postgres wire dedup, and the new test class). Overall this is a well-scoped, carefully reasoned change with good test coverage. No blocking issues found. A few observations below.

Code quality

  • The AST additions (BooleanExpression.isAlwaysFalse, Expression/MathExpression/BaseExpression.isLiteral) follow the existing isAlwaysTrue() pattern closely and stay structural (no flatten() DNF blowup), which is the right call for something evaluated on every fresh plan build.
  • BaseExpression.isLiteral() correctly excludes identifier (field refs) and inputParam (bound params) by falling through to false, and MathExpression.isLiteral()'s "empty childExpressions → false" default correctly leaves CaseExpression, ArrayLiteralExpression and ParenthesisExpression unfolded since those subclasses keep their operands outside childExpressions (each has a comment noting this) - good, conservative default.
  • EmptySourceStep.copy() is explicitly implemented to carry the reason field through a plan-cache copy; this matters because canBeCached() == true (unlike EmptyStep), and it's exactly what theFoldedPlanIsCacheableAndReusable pins. Nice attention to detail.
  • Reuse of WhereClause.isAlwaysFalse() from PostgresNetworkExecutor is a clean deletion of ~90 duplicated lines, and the new version is strictly more general (handles <, >, arithmetic, BooleanExpression.FALSE sentinel, etc., not just =).

Potential bugs

Nothing that looks incorrect. Two things worth a second look, both minor:

  • isMinimalQuery() in SelectExecutionPlanner (used by the hardwired count/max/min paths) still has the comment "SKIP/LIMIT are allowed because all hardwired optimizations (count, max, min) return a single row". That's no longer accurate for LIMIT 0 specifically, since emptyReason == null && now intercepts before handleHardwiredOptimizations is reached in that case. Worth a one-line comment update so a future reader doesn't get confused about why LIMIT 0 behaves differently now (this is also the "one behaviour change" called out in the PR description, so it'd be nice to have the code comment match the PR narrative).
  • NotBlock doesn't get an isAlwaysFalse override, so WHERE NOT (1=1) / WHERE NOT true isn't folded even though NotBlock.isAlwaysTrue() already handles the symmetric case (negate flag + sub.isAlwaysTrue()). Not a bug (conservative miss, falls back to the old scan-and-filter path, so correctness is preserved) — just a possible small follow-up for completeness alongside AndBlock/OrBlock/ParenthesisBlock.

Performance

  • The new emptyByConstructionReason() check runs once per fresh plan build (pre-cache), and is O(size of the WHERE tree) - negligible next to the rest of plan construction, and cheaper than the DNF flatten() the old Postgres-side code used.
  • The actual win (skipping the full scan for WHERE 1=0 / LIMIT 0 probes) is the point of the PR and is well demonstrated by the readRecord-statistic assertions in the test class rather than just checking "zero rows," which is the right way to pin this kind of optimization.

Security

No concerns. The literal-only restriction (Expression.isLiteral() excluding bound parameters and function calls) is exactly right for a plan-time fold: a parameter is per-execution while the plan is reused, and folding a function call would mean invoking it (with potential side effects) just to classify the statement. Both are explicitly excluded and tested (aFilterResolvedByAParameterIsNeverFolded, aFilterCallingAFunctionIsNeverFolded).

Test coverage

The 19 tests in ConstantFalseFilterFoldingTest are thorough: parentheses/AND/OR structural folding, satisfiable-OR non-folding, parameter/function exclusion, LIMIT 0 vs LIMIT ?, count(*) with and without GROUP BY, missing-target validation surviving the fold, subquery folding, plan-cache reuse (including the copy-preserves-reason case), once-per-statement LET side effects, DELETE/UPDATE coverage, and a direct readRecord assertion. Asserting on plan shape (no FetchFrom*/CountFrom* anywhere, including nested sub-plans) in addition to row counts is a good way to make sure this doesn't silently regress into "still scans but returns nothing" later.

One small gap: no test exercises the literal WHERE false / WHERE true AND false form (the BooleanExpression.FALSE sentinel path added in BooleanExpression.java) - since that override is a one-liner it's low risk, but a single extra test case would pin it as cheaply as the others.

Nice work - the change is tightly scoped, the "what the fold deliberately keeps" list in the description matches what the code actually does, and the behavior-change callout (LIMIT 0 with count(*)) is exactly the kind of thing that's easy to miss and good that it's flagged explicitly.

… NOT/literal-false filters fold

Review follow-ups on PR #6181.

The `isMinimalQuery()` comment claimed SKIP/LIMIT were safe on a hardwired plan because it returns a
single row - but the plan returns before either step is chained, so `SELECT count(*) FROM T SKIP 1`
handed back the very row it was told to skip. `LIMIT 0` was already claimed by the constant-fold; the
count plans now chain both steps themselves, which costs nothing on one row and makes the comment
true again instead of documenting the hole.

`NotBlock.isAlwaysFalse()` mirrors the `isAlwaysTrue()` next to it: `NOT <always true>` is false for
every record, and without the negation the block is a pass-through. The test pins the hazard in the
other direction - reading `NOT (1=0)` as false would answer a filter matching every record with no
rows at all.

A bare boolean literal parses to the `BooleanExpression.FALSE`/`TRUE` sentinels rather than to a
condition, and `WHERE false` was folded but untested; it and `WHERE true` are covered now.
@lvca

lvca commented Aug 14, 2026

Copy link
Copy Markdown
Member Author

Thanks - all three points addressed in 5c4886c.

isMinimalQuery() comment: rather than update the comment, the hole it would have documented is closed. The hardwired count plans replace the whole step chain and returned without chaining SKIP or LIMIT at all, so SELECT count(*) FROM T SKIP 1 handed back the very row it was told to skip (verified before the fix). handleSkipAndLimitAfterHardwired() now chains both after CountFromTypeStep/CountFromIndexStep - free on a plan that produces one row - and the comment is accurate again. (max/min on index already answered SKIP correctly, so that path is untouched.) New test: countStarWithASkipReturnsNoRow.

NotBlock: added, mirroring the isAlwaysTrue() beside it - NOT <always true> is false for every record, and without the negation the block is a pass-through. Note the negated form only pays off once some leaf answers isAlwaysTrue(); no leaf does today (isAlwaysTrue() has no consumer outside the AST itself), so this is completeness rather than a new fold. The test pins the direction that would be a wrong answer: WHERE NOT (1=0) must still return every row.

WHERE false: it does parse, to the BooleanExpression.FALSE sentinel, and it was already folded - just untested. aLiteralFalseFilterIsFoldedToo now covers WHERE false, WHERE true AND false and the WHERE true counter-case.

Re-ran engine com.arcadedb.query.**: 10952 tests green.

@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review

Nicely scoped change with a clear write-up and a good regression test class (ConstantFalseFilterFoldingTest). I read the merged source directly (the merge commit for this PR is what's checked out in this environment) rather than just the diff, so the line numbers below are exact.

Bug: the MAX/MIN hardwired plan still doesn't chain SKIP/LIMIT

engine/src/main/java/com/arcadedb/query/sql/executor/SelectExecutionPlanner.java

The second commit's whole point was "the hardwired count plans chain their own SKIP/LIMIT" (fixing SELECT count(*) FROM T SKIP 1 handing back the row it was told to skip). That fix was applied to handleHardwiredCountOnType (line 482) and handleHardwiredCountOnIndex (line 520), both now calling the new handleSkipAndLimitAfterHardwired helper -- but handleHardwiredMaxMinOnIndex (lines 585-627) never calls it. It chains only MaxMinFromIndexStep and returns true.

MaxMinFromIndexStep (MaxMinFromIndexStep.java) always produces exactly one row and has no SKIP/LIMIT awareness of its own -- it doesn't consult info.skip/info.limit at all. So the exact same bug this PR fixes for count(*) still reproduces for max/min:

SELECT max(value) FROM TestType SKIP 1

should return zero rows (skip removes the single row) but with the current code still returns the max value, because nothing downstream of MaxMinFromIndexStep ever applies the skip.

Compounding this, isMinimalQuery()'s doc comment (line 526) was updated by this PR to say:

"SKIP/LIMIT are allowed because all hardwired optimizations (count, max, min) return a single row, and because the plan chains the two steps itself"

That's no longer accurate -- only the two count paths do. Since isMinimalQuery() is the shared gate that lets SKIP/LIMIT reach handleHardwiredMaxMinOnIndex in the first place, either:

  • handleHardwiredMaxMinOnIndex should call handleSkipAndLimitAfterHardwired(result, info, context) right after chaining MaxMinFromIndexStep (mirroring the two count methods), or
  • the javadoc should be corrected and MAX/MIN queries with SKIP should be excluded from the hardwired path.

Given the PR is already touching this exact class of bug and the fix pattern is a one-line addition, extending it to MAX/MIN seems like the right call. Worth adding a regression test alongside countStarWithASkipReturnsNoRow (in the new ConstantFalseFilterFoldingTest, or in MaxMinFromIndexTest) for SELECT max(indexedProp) FROM T SKIP 1.

Minor: NOT on a literal-true BinaryCondition isn't folded

NotBlock.isAlwaysFalse (correctly) delegates to sub.isAlwaysTrue() when negated, but BinaryCondition never overrides isAlwaysTrue() (only the new isAlwaysFalse() was added). So WHERE NOT (1=1) -- logically always-false -- isn't recognized as empty-by-construction; it still falls through to a full scan. This is a safe false negative (per the "allowed to return false negatives" doc on BooleanExpression.isAlwaysFalse), not a correctness bug, and it's pre-existing asymmetry (isAlwaysTrue on BinaryCondition was never implemented before this PR either) -- just flagging as a possible small follow-up if this shape is worth covering (Spark/BI probes are unlikely to write NOT (1=1), so probably low priority).

What looks solid

  • The structural isAlwaysFalse recognition (AndBlock/OrBlock/NotBlock/ParenthesisBlock) is logically equivalent to the DNF-based flatten() approach the old PostgresNetworkExecutor code used, just O(n) instead of cartesian-product -- verified this against the boolean algebra by hand, no coverage regression for the Postgres probe-detection use case.
  • EmptySourceStep mirrors EmptyStep correctly (pull-previous-once for the "global LET still runs" behavior), with the right canBeCached()=true since the fold is a property of the statement text, not the data.
  • The info.fetchExecutionPlan.close() guard on !getSteps().isEmpty() is load-bearing: SelectExecutionPlan.close() calls lastStep.close() unconditionally, which NPEs on an empty plan. Good catch keeping that guarded.
  • Target-existence validation, GROUP BY, and the once-per-statement LET are all correctly preserved through the fold, confirmed by tracing handleProjectionsBlock/AggregateProjectionCalculationStep.
  • Removing the ~90-line duplicate PostgresNetworkExecutor implementation in favor of WhereClause.isAlwaysFalse() is a solid simplification with no behavior loss.

Test coverage

The new ConstantFalseFilterFoldingTest (19 tests) is thorough for the filter/LIMIT-0 folding itself, including plan-shape assertions and the readRecord statistic -- good discipline verifying the scan is actually gone, not just that rows are empty. The gap is the MAX/MIN+SKIP case above, which isn't exercised by this PR's tests or the pre-existing MaxMinFromIndexTest.

Review follow-up on PR #6181. The previous commit gave the two count paths the SKIP/LIMIT they
never chained, but left handleHardwiredMaxMinOnIndex out: it also replaces the whole step chain, and
MaxMinFromIndexStep is no more aware of SKIP than CountFromTypeStep is. So
`SELECT max(indexedProperty) FROM T SKIP 1` handed back the row it was told to skip - reproduced,
then fixed by the same one-line call. The path is only taken when the property carries a range
index, which is why the first probe of this bug missed it.

`isMinimalQuery()`'s comment is now true of all three hardwired plans, not two.
@lvca

lvca commented Aug 14, 2026

Copy link
Copy Markdown
Member Author

Good catch on MAX/MIN - fixed in 18f9c2c.

handleHardwiredMaxMinOnIndex: confirmed the bug before fixing it. My first probe of this defect used an unindexed property, so SELECT max(n) FROM T SKIP 1 fell through to the ordinary pipeline and answered correctly - which is exactly why the MAX/MIN path looked clean and got left out. With a range index on the property it reproduces just as you describe. handleSkipAndLimitAfterHardwired is now called there too, and the new test (maxOnAnIndexedPropertyWithASkipReturnsNoRow, which creates the property + LSM_TREE index first) was verified non-vacuous: it fails with Expecting value to be false but was true when the one-line call is removed. isMinimalQuery()'s comment is now true of all three hardwired plans.

NOT (1=1): leaving this one. Folding it needs BinaryCondition.isAlwaysTrue(), and that method's signature takes no CommandContext - the fold would have to call operator.execute(null, ...) through Expression.execute with a null context, which is a wider contract change than the shape justifies. isAlwaysTrue() also has no consumer outside the AST's own recursion today, so implementing it on the leaf buys exactly this one query shape. Happy to take it as a separate issue if you want the symmetry; as a probe shape it is not one anything sends.

Re-ran engine com.arcadedb.query.sql.**: 2538 tests green.

@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review

Went through the diff (16 files, +715/-116) and cross-checked the planner change against LimitExecutionStep, SelectExecutionPlan, AbstractExecutionStep, DeleteExecutionPlanner/UpdateExecutionPlanner, and NumberUtils.saturateToInt. Overall this is a careful, well-scoped change with unusually thorough justification in both the commit messages and the docs entry - genuinely a pleasure to read. A few notes below, nothing blocking.

Correctness

  • Target validation is correctly preserved. handleFetchFromTarget is still called unconditionally before the fold decision is acted on, and Type not found: ... (SelectExecutionPlanner:3070) still throws synchronously during planning, so SELECT FROM ATypeThatDoesNotExist WHERE 1=0 keeps reporting the missing type. Confirmed by anUnknownTargetIsStillReported.
  • foldEmptyByConstruction's close() guard is correct and necessary. SelectExecutionPlan.close() does lastStep.close() unconditionally, so calling it on a plan with zero chained steps would NPE - the !info.fetchExecutionPlan.getSteps().isEmpty() guard avoids that. Good catch on your part; worth calling out because it's easy to regress if this method is touched again later.
  • BinaryCondition.isAlwaysFalse looks safe against 3-valued logic. Boolean.FALSE.equals(evaluate(...)) correctly leaves NULL-producing comparisons (e.g. WHERE null = null) unfolded, since that evaluates to null, not false. Good.
  • DELETE/UPDATE reuse is real, not just claimed. Both planners wrap a nested SelectExecutionPlanner.createExecutionPlan(context, false) in a SubQueryStep, so the fold naturally propagates without any DELETE/UPDATE-specific code path. Confirmed by the two new tests.
  • Limit.isAlwaysEmpty() doesn't collide with the -1 "unlimited" sentinel. saturateToInt only saturates out-of-int-range values; a plain -1 round-trips untouched, so LIMIT -1 is never misread as LIMIT 0. Worth having an explicit test for this (LIMIT -1 not folded) since the whole fold hinges on that sentinel not colliding - it's currently only implied by reading getValue()'s javadoc, not asserted anywhere.

One behavior change beyond what's documented

The PR body calls out one behavior change (SELECT count(*) FROM T LIMIT 0). There's a second, undocumented one worth confirming is intentional: emptyByConstructionReason() returns "LIMIT 0" regardless of what the WHERE clause contains, and foldEmptyByConstruction never calls handleWhere in that branch. So for SELECT * FROM T WHERE someFunctionWithSideEffectsOrThatCanThrow(...) = 1 LIMIT 0, the WHERE clause is now never evaluated at all - no per-record function calls, and no exceptions that evaluating it against real data might have raised. That's consistent with "LIMIT 0 means no rows," but it's a different justification than the constant-false-filter fold (which deliberately never touches functions to avoid this exact class of surprise). If a WHERE clause with a function that legitimately throws (e.g. type-mismatch on some rows) is combined with LIMIT 0, that error now silently disappears. Given the PR is already careful to note the count(*) behavior change, this one might deserve the same explicit callout (and maybe a test), even if the answer is "yes, intentional."

Test coverage

Strong - 19 cases in ConstantFalseFilterFoldingTest, and it asserts plan shape + readRecord stats rather than just row counts, which is exactly right for a perf-motivated fold (a naive test would pass on unfixed code). Things it does cover well: parentheses/AND/OR structural recognition, NOT negation hazard, parameters, function calls, GROUP BY, LET side effects, DELETE/UPDATE, subqueries, plan cache reuse, and the SKIP/LIMIT hardwired-plan regressions found along the way. The one gap noted above (LIMIT 0 + a WHERE clause with a throwing/side-effecting predicate) is the only case I'd add.

Minor

  • EmptySourceStep/copy()/canBeCached() correctly mirror the ExecutionStepInternal default-throws / default-false pattern that EmptyStep relies on implicitly - nice attention to consistency there.
  • The broad catch (Exception e) in BinaryCondition.isAlwaysFalse is fine given it only ever suppresses "can't fold, defer to runtime" - but since it's not scoped to a specific exception type, a genuine bug elsewhere in evaluate() would silently degrade to "not folded" rather than surface. Not worth narrowing given the fallback is always safe, just flagging for awareness.
  • PostgresNetworkExecutor cleanup (~90 lines of duplicated logic removed in favor of WhereClause.isAlwaysFalse()) is a clean, welcome consolidation with no behavior change beyond what the AST-level fold now also gives it (structural AND/OR-through-NOT recognition it didn't have before, which is strictly more correct).

Nice work - the planning-vs-execution-time separation (fold decided before optimizeQuery() rearranges clauses) and the choice to add EmptySourceStep instead of reusing the non-cacheable EmptyStep are both the right calls, and are explained clearly in-code.

… -1 sentinel

Review follow-ups on PR #6181, both test and prose - no behaviour change.

A LIMIT 0 is folded whatever the WHERE says, so unlike the constant-false fold (which never reaches a
function) the filter is simply not evaluated. The only way to observe that is a predicate that raises:
`WHERE 1/0 = 1` reports a division by zero, and with `LIMIT 0` it now returns an empty result. Said so
in emptyByConstructionReason's javadoc and in the release notes, and pinned by a test.

`LIMIT -1` is the sentinel LimitExecutionStep reads as "unlimited", and the fold rests on
`saturateToInt` leaving it alone rather than rounding it into zero. That was only implied by
Limit.getValue()'s javadoc; there is a test for it now.
@lvca

lvca commented Aug 14, 2026

Copy link
Copy Markdown
Member Author

Both points taken - b6b4088 (docs + tests only, no behaviour change).

LIMIT 0 and the un-evaluated WHERE: intentional, and you are right that it deserved the same explicit callout as the count(*) one. The two spellings genuinely are not decided the same way: a constant-false filter is folded only when the statement itself says so and never reaches a function, while a LIMIT 0 truncates the result whatever the filter would have done, so the filter is simply not evaluated. The observable difference is exactly the one you name - a predicate that raises stops raising. SELECT FROM Character WHERE 1/0 = 1 reports ArithmeticErrorException: / by zero; with LIMIT 0 it now returns an empty result. That is now stated in emptyByConstructionReason's javadoc, in the release-notes entry, and pinned by limitZeroIsFoldedWhateverTheFilterSays (which asserts both halves, so the day someone makes the fold conditional on the filter the test says why).

LIMIT -1: added aNonZeroOrParameterizedLimitIsNeverFolded coverage. Confirmed it parses, is not folded, and returns every row - the plan keeps its LIMIT ( LIMIT -1) step, which LimitExecutionStep reads as unlimited.

Broad catch (Exception) in BinaryCondition.isAlwaysFalse: leaving as is, for the reason you give - the fallback is "don't fold, let the runtime report it", which is the same answer any narrower catch would produce for the cases that matter, and BinaryComparator raises a fairly open set of types across the operators.

Engine com.arcadedb.query.sql.executor.** green.

@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review

I went through this PR in depth (AST folding logic in parser/, the SelectExecutionPlanner wiring, EmptySourceStep, the Postgres wire refactor, and the new ConstantFalseFilterFoldingTest). Overall this is a very well-scoped, well-tested change. Notes below.

Correctness

  • The structural isAlwaysFalse recursion (AndBlock/OrBlock/NotBlock/ParenthesisBlock/BinaryCondition) is logically sound: AND is false when any term is, OR only when every alternative is, NOT <always-true> is false, parenthesis delegates. I checked the empty-AndBlock/OrBlock edge cases against the existing isAlwaysTrue() counterparts and they're consistent (empty AND ⇒ neutral/true, empty OR ⇒ not provably false).
  • isLiteral() (Expression/MathExpression/BaseExpression) is appropriately conservative — a bound parameter, a function call, a field reference, or JSON/RID/array-concat all correctly fall through to false. I did trace ParenthesisExpression/CaseExpression/ArrayLiteralExpression/FirstLevelExpression, which don't override isLiteral() and store their payload outside childExpressions, so they inherit the false from an empty list. That means e.g. WHERE (1) = 0 (a math-level parenthesis, not the boolean-level ParenthesisBlock) won't be folded — a missed optimization, not a correctness issue, and consistent with the documented "false negatives are fine" contract. Worth a one-line comment if you want to head off someone "fixing" it later expecting a false positive risk that isn't there.
  • BinaryCondition.isAlwaysFalse reuses the exact evaluate() path the filter step would call and catches evaluation exceptions defensively (deferring incompatible-type comparisons to runtime), which is the right call.
  • Limit.isAlwaysEmpty() correctly restricts to the literal num field (excludes inputParam/expression), and correctly doesn't confuse LIMIT -1 (the "unlimited" sentinel) with zero via saturateToInt.
  • The SelectExecutionPlanner wiring reads emptyByConstructionReason before optimizeQuery() mutates the clauses, still plans (and discards) the fetch so a missing type is reported, and runs handleGlobalLet unconditionally so a once-per-statement LET still executes — all matches the PR description and is exercised by dedicated tests (anUnknownTargetIsStillReported, aLetEvaluatedOncePerStatementStillRuns).
  • EmptySourceStep mirrors EmptyStep (pullPrevious then empty result set) but flips canBeCached() to true; copy(context) correctly threads the new context through rather than closing over the original. Good catch making it a distinct step instead of overloading EmptyStep's cache semantics.
  • The handleSkipAndLimitAfterHardwired fix for CountFromTypeStep/CountFromIndexStep/MaxMinFromIndexStep is a legitimate, separately-worth-it bug fix (SKIP was silently dropped on all three hardwired paths) and is well covered (countStarWithASkipReturnsNoRow, maxOnAnIndexedPropertyWithASkipReturnsNoRow).
  • The PostgresNetworkExecutor refactor is a faithful behavioral match for the removed ~90-line duplicate: where.isAlwaysFalse(context) covers everything the old DNF/flatten()-based isAlwaysFalse/isLiteral pair did, plus NOT and the boolean-literal sentinels, which is strictly more capable, not less.

Minor observations (non-blocking)

  • foldEmptyByConstruction sets info.planCreated = true, but that flag is only read in handleWhere, which is never called on the fold path — currently a no-op write. Harmless (arguably correct defensive bookkeeping for future readers of info), but not load-bearing; a maintainer reading handleWhere looking for why it matters here will find nothing.
  • The one intentionally-documented behavior change (LIMIT 0 skips filter evaluation entirely, so WHERE 1/0 = 1 LIMIT 0 no longer throws) is called out clearly in both the code comment and release notes, and is pinned by limitZeroIsFoldedWhateverTheFilterSays. Good practice.

Test coverage

The new ConstantFalseFilterFoldingTest (19 cases) is thorough: plan-shape assertions (no FetchFrom*/CountFrom*, including inside sub-plans) and the readRecord statistic, not just row counts; negative cases for bound parameters, function calls, satisfiable OR branches, and the LIMIT -1 sentinel; DELETE/UPDATE/subquery coverage; and a plan-cache reuse test. I didn't find a gap worth asking for more tests on.

Performance

The structural isAlwaysFalse walk is O(n) in the condition tree as claimed, versus the flatten() DNF the Postgres-side code used to build — a real improvement for wide ORs, and it now runs on every SELECT/DELETE/UPDATE plan build rather than only in the Postgres probe path, which is the right tradeoff given the check is cheap and short-circuits immediately on the (overwhelmingly common) non-foldable case.

Security

No concerns — the fold never evaluates a function or touches stored data, and target-existence validation is deliberately preserved.

Nice work; I have no blocking findings.

…rithmetic parenthesis

Review follow-ups on PR #6181, no behaviour change.

`info.planCreated` is only read by handleWhere, which the fold path never calls, so setting it there
said something no reader could act on. Gone.

MathExpression.isLiteral()'s javadoc now names the arithmetic parenthesis of `(1) = 0` alongside the
array literal and the CASE, and says plainly that these are missed folds rather than unsafe ones - so
the next reader knows the answer is a choice and not an oversight.
@lvca

lvca commented Aug 14, 2026

Copy link
Copy Markdown
Member Author

Both minor observations applied in 6510f79 - no behaviour change.

info.planCreated: you are right that it was a write nothing reads; handleWhere is the only reader and the fold path never calls it. Removed rather than commented - defensive bookkeeping that no reader can act on is just a question mark for the next person.

(1) = 0: MathExpression.isLiteral()'s javadoc now names the arithmetic parenthesis alongside the array literal and the CASE, and says plainly that these are missed folds rather than unsafe ones, so the omission reads as a choice.

That closes everything raised across the four rounds. Summary of what the reviews changed beyond the original fold: the SKIP that all three hardwired plans (count(*) on type, count(*) on index, max/min on index) silently dropped, NotBlock.isAlwaysFalse, and tests for WHERE false, NOT (1=0), LIMIT -1 and the LIMIT 0 filter-not-evaluated consequence.

@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review

Went through the diff carefully, including the recursive isAlwaysFalse/isLiteral logic, the SelectExecutionPlanner fold path, the hardwired SKIP/LIMIT fix, and the new test suite. Overall this is a very well-reasoned change: the design is documented in-line with the "why", the risk areas (soundness of the fold, resource cleanup, caching) are each addressed deliberately, and the test suite pins the exact hazards called out in the PR description. I could not find a correctness bug. Notes below are minor.

Correctness (verified, no issues found)

  • No false positives possible. AndBlock.isAlwaysFalse folds when any term is false, OrBlock.isAlwaysFalse only when all terms are false — both are logically sound for arbitrary nesting, so the fold can only under-recognize (false negatives), never wrongly empty a satisfiable query. Traced a case like 1=0 OR (a=1 AND (2=0 OR a=2)), which is mathematically always-false but isn't detected by the structural walk — that's an accepted, documented limitation ("allowed to return false negatives"), not a bug.
  • NotBlock.isAlwaysFalse reuses the pre-existing isAlwaysTrue() for the negate branch. Worth noting: BinaryCondition never overrides isAlwaysTrue() (it's not part of this PR), so NOT (1=1) won't fold even though it obviously could. Harmless (false negative, same contract as above), just leaves a small amount of symmetry on the table if anyone wants to pick it up later.
  • foldEmptyByConstruction guards info.fetchExecutionPlan.close() with !getSteps().isEmpty(). That guard is load-bearing: SelectExecutionPlan.close() is lastStep.close() with no null check, so calling it on an empty plan would NPE. Good catch already handled.
  • Target validation, GROUP BY semantics, LET-once-per-statement, ORDER BY, and the DELETE/UPDATE reuse via SubQueryStep all check out against the actual code paths (handleFetchFromTarget runs before the fold discards it; handleProjectionsBlock is shared between the fold and normal paths so ORDER BY/aggregation/skip/limit stay wired).
  • The handleSkipAndLimitAfterHardwired fix is real and independent of the LIMIT 0 fold: CountFromTypeStep/CountFromIndexStep/MaxMinFromIndexStep genuinely never chained SKIP, so SELECT count(*) FROM T SKIP 1 was returning the row it should've skipped. Confirmed there's exactly one call site per hardwired method, so no double-chaining risk.
  • EmptySourceStep.copy()/canBeCached() follow the same conventions as other steps (e.g. FilterStep.copy()), so the plan-cache reuse path (pinned by theFoldedPlanIsCacheableAndReusable) is consistent with how the rest of the executor handles cached/copied plans.

Minor / style

  • ConstantFalseFilterFoldingTest.anUnknownTargetIsStillReported() uses org.assertj.core.api.Assertions.fail(...) fully-qualified instead of an import — CLAUDE.md calls this out explicitly ("don't use fully qualified names if possible, always import the class"). Trivial fix: import static org.assertj.core.api.Assertions.fail;.
  • Same test uses a manual try { ... } catch (Exception e) { assertThat(e.getMessage())... } where assertThatThrownBy(...).hasMessageContaining("ThisTypeDoesNotExist") (already used elsewhere in this file) would be more consistent and slightly shorter.
  • PR description says "19 tests" for ConstantFalseFilterFoldingTest; the class currently has 23 (@Test count is 24 including no it's 24 - 1 non-test beginTest). Stale from an earlier commit in the series — harmless, but worth updating if you touch the description again.

Test coverage

Genuinely thorough: covers parentheses/AND/OR nesting, NOT-negation hazard, bound parameters, function calls, LIMIT 0 vs LIMIT -1 vs LIMIT ?, the div-by-zero short-circuit behavior change, count(*)/GROUP BY/SKIP interactions with the hardwired plans, plan-cache reuse, LET side effects, subqueries, and DELETE/UPDATE. It also asserts on the readRecord stat and plan shape rather than only row counts, which is the right level of rigor for a perf-motivated change like this.

Not verified

I wasn't able to run mvn compile/tests in this sandbox (network-restricted), so I did static analysis only — no build/test execution to back this up. Worth confirming CI is green before merge if it isn't already.

@lvca

lvca commented Aug 14, 2026

Copy link
Copy Markdown
Member Author

Applied in 1585b02: anUnknownTargetIsStillReported now uses assertThatThrownBy(...).hasMessageContaining(...) like the rest of the class, so the fully-qualified Assertions.fail and the hand-rolled try/catch are both gone. PR description refreshed with the real test count (24) and the two behaviour changes.

On NOT (1=1): still leaving it, for the reason given last round - folding it needs BinaryCondition.isAlwaysTrue(), whose signature carries no CommandContext, so the fold would have to evaluate through a null one. That is a wider contract change than a query shape nobody writes justifies.

Nothing outstanding from my side. Local runs backing this branch: engine com.arcadedb.query.** 10952, the rest of the engine module 4928, postgresw 260 units + the integration suite including PostgresWJdbcIT. CI is the authority on the rest.

@codacy-production

codacy-production Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics -2 complexity

Metric Results
Complexity -2

View in Codacy

🟢 Coverage 95.24% diff coverage · -6.47% coverage variation

Metric Results
Coverage variation ✅ -6.47% coverage variation
Diff coverage ✅ 95.24% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (75c46ba) 157812 124174 78.68%
Head commit (1585b02) 190174 (+32362) 137341 (+13167) 72.22% (-6.47%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#6181) 42 40 95.24%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Review

Nicely scoped fix, and unusually well-documented (the javadocs on isLiteral()/isAlwaysFalse() clearly explain why functions and bound parameters are excluded). I read through the AST changes, the planner wiring, the hardwired-plan SKIP/LIMIT fix, and the new test class. Nothing I would block on; a few notes below, mostly minor.

Correctness:

  • AndBlock/OrBlock/NotBlock/ParenthesisBlock.isAlwaysFalse structural recursion checks out against the corresponding evaluate()/isAlwaysTrue() semantics (AND false if any term is, OR false only if every term is, NOT flips through negate, empty blocks conservatively return false). Verified with the 1=0 AND/OR, parentheses, and NOT (1=0) test cases.
  • BinaryCondition.isAlwaysFalse folds only when both operands are isLiteral(), and correctly excludes InputParameter and function calls transitively (neither field is checked directly in BaseExpression.isLiteral(), but since number/string/isNull/expression are all null in those cases, it falls through to false anyway - a little implicit, but the test coverage, aFilterResolvedByAParameterIsNeverFolded and aFilterCallingAFunctionIsNeverFolded, pins it).
  • Good catch on the LIMIT 0 semantics being deliberately different from the constant-false fold (skips filter evaluation entirely, including a throwing predicate) - and it is explicitly tested (limitZeroIsFoldedWhateverTheFilterSays).
  • The three hardwired plans (CountFromType, CountFromIndex, MaxMinFromIndex) previously returning without chaining SKIP/LIMIT was a real, independently-worth-fixing bug; handleSkipAndLimitAfterHardwired centralizes the fix well.
  • Target validation (fetch is planned then discarded rather than skipped) and LET global-once-per-statement semantics are preserved and tested (anUnknownTargetIsStillReported, aLetEvaluatedOncePerStatementStillRuns).

Minor / nit-level:

  • BinaryCondition.isAlwaysFalse catches a bare Exception around evaluate(...). That is clearly intentional (comment explains the runtime should be the one to report a bad comparison), but it also means the fold silently swallows anything unexpected thrown from evaluate(), not just a type-mismatch. Might be worth narrowing the catch, or a comment noting the intentional breadth - not blocking.
  • foldEmptyByConstruction calls info.fetchExecutionPlan.close() on a plan whose steps were built but never pulled. The PR reasons through this in the doc comment (a step that grabbed a resource in its constructor should not outlive the discarded plan), and AbstractExecutionStep.close()'s default just recurses up prev, so this looks safe for the step types exercised by the new tests. Worth a mental double-check that any step which opens something lazily (not in the constructor) does not assume syncPull ran before close() - not something verifiable by reading alone.
  • OrBlock.isAlwaysFalse returns false for an empty subBlocks list; the conservative/safe answer for an optimization allowed false negatives, worth confirming an empty OrBlock can actually occur in a parsed statement - not a bug, just flagging.

Test coverage:
ConstantFalseFilterFoldingTest is thorough: it asserts on plan shape (no FetchFrom*/CountFrom*, including inside sub-plans) and the readRecord stat, not just row count, which is exactly right for a must-not-scan claim. It also pins the negative cases (parameter, function call, satisfiable OR branch, NOT (1=0), LIMIT ?, LIMIT -1 sentinel) and the plan-cache-reuse case. Good regression coverage for the two SKIP bugs found along the way too.

Reuse:
Good removal of the ~90 duplicated lines in PostgresNetworkExecutor in favor of WhereClause.isAlwaysFalse() - one recognizer instead of two that could drift.

Overall: solid, well-tested change. No blocking issues found.

@codecov

codecov Bot commented Aug 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.47619% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.01%. Comparing base (75c46ba) to head (1585b02).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
...edb/query/sql/executor/SelectExecutionPlanner.java 87.87% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6181      +/-   ##
==========================================
+ Coverage   69.91%   70.01%   +0.10%     
==========================================
  Files        1831     1832       +1     
  Lines      157812   157831      +19     
  Branches    33310    33301       -9     
==========================================
+ Hits       110327   110505     +178     
+ Misses      33677    33496     -181     
- Partials    13808    13830      +22     

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Constant-false filters (WHERE 1=0) are not folded at plan time, so every schema probe scans its target in full

1 participant