Repository navigation
perf(#6174): fold a constant-false filter and LIMIT 0 at plan time instead of scanning the target - #6181
Conversation
…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.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | -2 |
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.
ReviewWent through the full diff (planner, AST Code quality
Potential bugsNothing that looks incorrect. Two things worth a second look, both minor:
Performance
SecurityNo concerns. The literal-only restriction ( Test coverageThe 19 tests in One small gap: no test exercises the literal 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 ( |
… 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.
|
Thanks - all three points addressed in 5c4886c.
Re-ran engine |
ReviewNicely scoped change with a clear write-up and a good regression test class ( Bug: the MAX/MIN hardwired plan still doesn't chain SKIP/LIMIT
The second commit's whole point was "the hardwired count plans chain their own SKIP/LIMIT" (fixing
SELECT max(value) FROM TestType SKIP 1should return zero rows (skip removes the single row) but with the current code still returns the max value, because nothing downstream of Compounding this,
That's no longer accurate -- only the two
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 Minor:
|
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.
|
Good catch on MAX/MIN - fixed in 18f9c2c.
Re-ran engine |
ReviewWent through the diff (16 files, +715/-116) and cross-checked the planner change against Correctness
One behavior change beyond what's documentedThe PR body calls out one behavior change ( Test coverageStrong - 19 cases in Minor
Nice work - the planning-vs-execution-time separation (fold decided before |
… -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.
|
Both points taken - b6b4088 (docs + tests only, no behaviour change).
Broad Engine |
ReviewI went through this PR in depth (AST folding logic in Correctness
Minor observations (non-blocking)
Test coverageThe new PerformanceThe structural SecurityNo 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.
|
Both minor observations applied in 6510f79 - no behaviour change.
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 ( |
ReviewWent through the diff carefully, including the recursive Correctness (verified, no issues found)
Minor / style
Test coverageGenuinely thorough: covers parentheses/AND/OR nesting, NOT-negation hazard, bound parameters, function calls, Not verifiedI wasn't able to run |
…nd a hand-rolled try/catch
|
Applied in 1585b02: On Nothing outstanding from my side. Local runs backing this branch: engine |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | -2 |
🟢 Coverage 95.24% diff coverage · -6.47% coverage variation
Metric Results Coverage variation ✅ -6.47% coverage variation Diff coverage ✅ 95.24% diff coverage 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.
|
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:
Minor / nit-level:
Test coverage: Reuse: Overall: solid, well-tested change. No blocking issues found. |
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
Fixes #6174.
The problem
The SQL planner had no notion of a filter that is false for every row.
WHERE 1=0was evaluated per record likeany other condition, so
scanned every
Character, evaluated1=0once per record and discarded all of them. That is the shape Spark, andseveral BI tools over the Postgres wire, send to discover a query's schema - one probe per pushed-down query,
against the real target.
LIMIT 0is 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)- defaultfalse, overridden structurally byAndBlock(falsewhen any term is),
OrBlock(false only when every alternative is),ParenthesisBlock(delegates) andBinaryCondition(folds the comparison). Structural rather than overflatten()'s DNF: it is O(n) instead ofthe cartesian product a DNF expansion of a wide OR produces, and it answers the same question.
BinaryConditionfolds only when both operands are literals (Expression.isLiteral()/MathExpression.isLiteral()/BaseExpression.isLiteral()), and folds by calling the very sameevaluate()the filter step would have called, so the fold and the runtime can never disagree. A bound parameteris excluded because the plan outlives the execution that bound it; a function call is excluded because nothing on
SQLFunctionmarks a function as pure -isEarlyCalculated()is not a purity check.Limit.isAlwaysEmpty()for a literalLIMIT 0(not a parameter, not an expression).SelectExecutionPlannerreads that off the clauses as the statement wrote them (beforeoptimizeQuery()rearranges them into index searches) and, after the target has been planned, drops the fetch steps and chains an
EmptySourceStepinstead. The rest of the plan is untouched.Three things the fold deliberately keeps:
SELECT FROM ATypeThatDoesNotExist WHERE 1=0still reports the missing type instead of quietly returning nothing;
what it receives today from the filter being removed -
SELECT count(*) FROM T WHERE 1=0still returns its onerow with 0, and with a
GROUP BYstill returns none;LETevaluated once per statement: it is chained ahead of the empty source, which pulls it exactly likeEmptyStepdoes.EmptySourceStepis a new step rather than a reuse ofEmptyStepbecauseEmptyStep.canBeCached()is(deliberately)
false: it encodes one execution's data. "This statement cannot return a row" is a property ofits text, so the folded plan is cacheable.
Because
DELETE/UPDATEbuild their target throughSelectExecutionPlanner, they are covered by the same code.Two behaviour changes, and a wrong answer found next to them
SELECT count(*) FROM T LIMIT 0used to return one row:count(*)on a bare type is answered by a hardwired planthat replaces the whole step chain and returns before any
LIMIT/SKIPstep 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 1andSELECT max(indexedProperty) FROM T SKIP 1handed back the very row they were told to skip. Both now chain thestatement's SKIP/LIMIT themselves, which costs nothing on a plan that produces one row.
Finally, a
LIMIT 0is folded whatever theWHEREsays, so - unlike the constant-false fold, which never reachesa 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 = 1reports a division by zero, and withLIMIT 0it now returns an empty result.Reuse over duplication
PostgresNetworkExecutor.isAlwaysFalse(added in #6172) is gone: the probe detection now callsWhereClause.isAlwaysFalse(), removing ~90 lines that duplicated the recognition.Tests
New
ConstantFalseFilterFoldingTest(24 tests), verified red on main for the folding cases. It asserts the planshape (no
FetchFrom*/CountFrom*step anywhere, including inside sub-plans) and thereadRecordstatistic, notonly 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 theLIMIT -1"unlimited" sentinel.Run: engine
com.arcadedb.query.**(10947 tests), the rest of the engine module, postgresw units + integration.