Repository navigation
fix(#6156): a Postgres schema probe over a typeless row source no longer returns an empty RowDescription - #6172
Conversation
…ger returns an empty RowDescription A `WHERE 1=0` probe was only describable when the query's row source resolved to a declared type. Anything else - no FROM at all, a constant/derived table, a graph function such as shortestPath() or dijkstra(), a TRAVERSE or a MATCH - fell through with no RowDescription at all, so Spark saw zero columns for a query that returns rows perfectly well without the probe filter. The probe is now answered from what the query itself produces: the statement is replayed with its constant-false filters removed and the first row it returns names the columns, with the very types the un-probed query would put on the wire. The filter is recognised in the disjunctive normal form the planner uses, so it holds through parentheses, ANDs and ORs, and only comparisons between operands that need no record are folded. Nothing is replayed when the statement carries no such filter, which leaves a genuinely empty result on the existing schema-discovery path untouched. Two static resolutions back it up for the shapes that cannot be replayed, notably the DESCRIBE that pgJDBC issues before a prepared statement runs: an explicit projection list names its own columns when the row source carries no schema, and a MATCH announces its RETURN list. An expand() projection now reports "unknown" instead of the target's columns, which it never produces. Regression test: PostgresWJdbcIT.schemaProbeForTypelessAndComputedProjectionsReturnsTheDescription.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 92 |
🟢 Coverage 75.32% diff coverage
Metric Results Coverage variation Report missing for de774e31 Diff coverage ✅ 75.32% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (de774e3) Report Missing Report Missing Report Missing Head commit (e0a66fa) 190133 137139 72.13% 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 (#6172) 154 116 75.32% 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%1 Codacy didn't receive coverage data for the commit, or there was an error processing the received data. Check your integration for errors and validate that your coverage setup is correct.
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.
ReviewNice piece of work — replacing the shape-by-shape enumeration with "replay the probe and read the first row" is a much more robust design than chasing every new row-source shape, and the DNF-based A few things worth a second look before merge: 1. The replay can execute side-effecting expressions that previously never ran. 2. The "replay is cheaper" reasoning doesn't hold uniformly. 3. Minor: every genuinely-empty SELECT now pays extra cost, not just probes. 4. Minor: redundant parse in the DESCRIBE-portal path. 5. Edge case not covered by the new test: a real predicate ANDed into the same clause as the constant-false term, bound to a parameter. None of the above looks blocking — the guards (language check, Nice regression-test discipline overall, and the write-up in the PR description makes the reasoning easy to verify against the code. |
… and skips the clauses that only order rows Review follow-ups on the schema-probe replay: - the parsed statement is now read before it is copied, so a query that legitimately returns no rows no longer pays for an AST deep copy it cannot use; the copy happens only once the statement is known to carry a constant-false filter - the replay drops ORDER BY, SKIP and LIMIT along with the filter. A row's columns do not depend on where it sits in the result, and without this the replay of a sorted or aggregated row source had to materialize the whole thing to hand over its first row - the extended protocol already parsed the query text when it prepared the portal, so that statement is threaded through instead of being parsed a second time - the replay evaluating the projection for real - which the probe's own filter prevented - is now stated where it happens, on sampleProbeColumns Two more regression cases: a constant-false term ANDed with a real predicate in the same clause, where dropping the clause leaves a bound parameter with nothing referencing it, and a probe whose row source carries ORDER BY/SKIP/LIMIT.
|
Reviewed the diff ( Potential bug/side-effect risk (the main one)
Concretely: this check runs on every query that legitimately returns zero rows and has a There is a precedent for evaluating early-calculated expressions outside of per-row execution ( Given Minor / nit
Things that look solid
Nothing here looks release-blocking on its own given how narrow the side-effect scenario is (needs a WHERE clause with a record-independent comparison against a function that isn't referentially transparent), but it seems worth a second look given the project's stated performance/correctness bar. |
… function calls isEarlyCalculated() only asks whether an expression can be computed without a record, which admits any function call whose arguments need no record, and nothing on SQLFunction tells a pure function from one with a side effect. Since the question "is this filter a schema probe?" is asked of every query that comes back empty - the vast majority of which are not probes - a filter such as `someStatefulFunction() = 42` had that function invoked once more just to be classified. Constant-false folding is now restricted to comparisons between literals: a number, a string, a boolean, null, or arithmetic over them. A modifier makes an operand a method call or a field access and so no longer a literal. That still recognises every probe idiom - 1=0, 1=0 AND ..., (1=0) OR (2=3) - while never reaching a function. The DESCRIBE-statement path now also takes the statement the portal parsed at Parse time instead of parsing the same text again; it stays purely static, so unbound parameters do not matter to it. Regression test: a filter built on uuid() leaves an otherwise undescribable query undescribable rather than being folded, and a literal comparison that holds is not a probe either.
ReviewI read through the full diff in Overall this is a well-reasoned fix: replaying the probe with its constant-false filter stripped is a much better answer than the shape-enumeration approach it replaces, and the PR clearly anticipated and addressed the two hazards I'd normally flag first:
Minor observations (none blocking)
Test coverageThe new No security concerns: the replay runs under the same session/authorization as the original query, drops only the client's own filter (never widens what the query engine would let the session see beyond what dropping Nice writeup in the PR description, by the way. Solid change. |
stripProbe removes the entire clause rather than just the constant-false term, so a probe such as WHERE 1=0 AND name = :n samples the unfiltered target. That is only sound because the caller reads column names and types off the sampled row and nothing else - the row never reaches the wire. Stating the dependency where it lives, so that a future RowDescription carrying anything derived from sample values does not silently invalidate it.
Review: fix(#6156) Postgres schema probe over typeless row sourcesThis is a well-reasoned fix with an unusually thorough PR description and good regression coverage. One design point below seems worth a second look before merge; the rest are smaller notes. Potential issue: the replay can fire (and run real side effects) on genuine Execute/simple-Query paths, not just DESCRIBE
Since Related, and already flagged in the docstring on Code quality
Performance
Test coverage
One gap: there's no test exercising the side-effect-replay concern above through SecurityNothing that stands out as a new vulnerability class; the replay runs under the same session/authorization as the original statement, no query text is built by string concatenation from user input for the replay (it operates on the parsed AST), and no additional data is sent to the client beyond column metadata. The side-effect point above is more of a correctness/surprise concern than a security one. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #6172 +/- ##
========================================
Coverage 69.91% 69.91%
========================================
Files 1831 1831
Lines 157633 157790 +157
Branches 33253 33304 +51
========================================
+ Hits 110208 110323 +115
- Misses 33641 33655 +14
- Partials 13784 13812 +28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…stead of scanning the target (#6181) * perf(#6174): fold a constant-false filter and LIMIT 0 at plan time instead 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. * fix(#6174): the hardwired count plans chain their own SKIP/LIMIT, and 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. * fix(#6174): the hardwired max/min plan chains its own SKIP/LIMIT too 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. * docs(#6174): name the one thing a folded LIMIT 0 changes, and pin the -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. * chore(#6174): drop a write nothing reads on the fold path, name the arithmetic 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. * test(#6174): assertThatThrownBy instead of a fully-qualified fail() and a hand-rolled try/catch
…ord is no longer "early calculated" isEarlyCalculated() answers "can this be computed without a record", and two nodes answered it without looking at the part that reads one: - BaseExpression judged the expression on its leftmost term alone and ignored the modifier chain, so 'Mr.'.append(surname) and ['a','b'][idx] were reported as record-free; - CaseExpression keeps its branches outside childExpressions, so the inherited walker found an empty list and said yes to a CASE that reads the record on every branch. The planner takes that answer as licence to use an index and to evaluate the expression against a null record, so the record-dependent part resolved to null and the query answered differently depending on whether an index existed: on the fixture in the new test the indexed type returned no rows where the plain scan returned two. The same classification promotes a per-record LET to a global one, with the same effect. The classification now walks the modifier chain (method call arguments, array range and index selectors; a suffix reads a property of the value it is applied to and still needs no record; a filter or nested projection is never assumed record-free) and every CASE branch. The contract is also the trap the issue is named for, so it is now written down where it is read: isEarlyCalculated says nothing about purity, determinism or constant-ness - any function over literals qualifies, uuid() included - and a caller that intends to *evaluate* an expression while planning wants a constant instead. Expression.isLiteral() is that predicate, raised to the parser from the private walk PostgresNetworkExecutor grew in #6172, which now calls it. Its optional allowInputParameters form admits a bound parameter for callers whose result does not outlive the execution. Two plan-time evaluation sites move onto it: - partitioned-bucket pruning binds a coordinate only from a literal now. The bucket it derives is baked into the plan, so the value must be fixed for the plan's life and free to compute; a function was neither, and the path was safe only because FunctionCall.isCacheable() is true for traversals alone, an accidental coupling in an unrelated file that pruning no longer leans on; - the MATCH index-cost estimate evaluates literals and bound parameters only, instead of invoking a user function once per planning pass just to sharpen an estimate.
…ord is no longer "early calculated" (#6182) * fix(#6179): an expression whose modifier or CASE branch reads the record is no longer "early calculated" isEarlyCalculated() answers "can this be computed without a record", and two nodes answered it without looking at the part that reads one: - BaseExpression judged the expression on its leftmost term alone and ignored the modifier chain, so 'Mr.'.append(surname) and ['a','b'][idx] were reported as record-free; - CaseExpression keeps its branches outside childExpressions, so the inherited walker found an empty list and said yes to a CASE that reads the record on every branch. The planner takes that answer as licence to use an index and to evaluate the expression against a null record, so the record-dependent part resolved to null and the query answered differently depending on whether an index existed: on the fixture in the new test the indexed type returned no rows where the plain scan returned two. The same classification promotes a per-record LET to a global one, with the same effect. The classification now walks the modifier chain (method call arguments, array range and index selectors; a suffix reads a property of the value it is applied to and still needs no record; a filter or nested projection is never assumed record-free) and every CASE branch. The contract is also the trap the issue is named for, so it is now written down where it is read: isEarlyCalculated says nothing about purity, determinism or constant-ness - any function over literals qualifies, uuid() included - and a caller that intends to *evaluate* an expression while planning wants a constant instead. Expression.isLiteral() is that predicate, raised to the parser from the private walk PostgresNetworkExecutor grew in #6172, which now calls it. Its optional allowInputParameters form admits a bound parameter for callers whose result does not outlive the execution. Two plan-time evaluation sites move onto it: - partitioned-bucket pruning binds a coordinate only from a literal now. The bucket it derives is baked into the plan, so the value must be fixed for the plan's life and free to compute; a function was neither, and the path was safe only because FunctionCall.isCacheable() is true for traversals alone, an accidental coupling in an unrelated file that pruning no longer leans on; - the MATCH index-cost estimate evaluates literals and bound parameters only, instead of invoking a user function once per planning pass just to sharpen an estimate. * fix(#6179): a CASE built entirely of literals is a literal, and say where the value field went Two points from the review: - CaseExpression kept the MathExpression default for isLiteral() too, so a CASE over literals alone reported false. Conservative, but inconsistent with the predicate's own definition: the extended form now qualifies when its case, when, then and else expressions all do. The simple form's WHEN is a WhereClause and carries no constant-ness, so it still cannot. - The comment on the isLiteral() fall-through now names what isEarlyCalculated() reads there and this does not: the inherited value field, where the pre-ANTLR executor substituted a parameter by hand and which nothing assigns any more. The asymmetry is unreachable rather than a gap, and a reader should not have to prove that again. The unguarded execute() the review also flagged in WhereClause.getEqualityOperations stays as it is: it now only ever runs on a literal or a bound parameter, and an expression that throws there (1/0) would throw at execution too, so failing at planning is the same outcome sooner.
Closes #6156.
Problem
Spark probes a pushed-down query's schema by wrapping it in
SELECT * FROM (...) SPARK_GEN_SUBQ_0 WHERE 1=0. That returns zero rows by construction, so the Postgres wire has to reconstruct theRowDescriptionfrom the schema. That reconstruction only worked when the query's row source resolved to a declared type (#5367, #5368). Everything else came back with no columns at all:SELECT * FROM (SELECT 1 AS n) t WHERE 1=0SELECT * FROM (SELECT expand([1,2,3]) AS n) t WHERE 1=0shortestPath(...)/dijkstra(...)as the row sourceTRAVERSE ... FROM (...) MAXDEPTH nMATCH {...} RETURN ...FROMat allThe very same queries without
WHERE 1=0return their rows and their columns fine, so this was purely a hole in the probe path.Approach
The issue frames this as "extend the schema probe to more shapes". Enumerating shapes is what got the probe into this state - each new row source (a function, a statement type, a nested wrapper) needs another special case, and each one can only ever guess at the types. The fix instead answers the probe with the thing that is authoritative: the query itself.
A probe is a query that has been made to return nothing on purpose. Replaying it with that filter removed, and reading the first row it produces, gives exactly the columns and the types the un-probed query would put on the wire - regardless of whether the rows come from a type, a graph function, a traversal, a pattern match or a constant. One mechanism, no shape list, and the probe's answer cannot drift from what the client will actually receive.
Guards on the replay:
BooleanExpression.flatten()), so1=0,1=0 AND x > 5,(1=0) OR (2=3)and nested-subquery placements are all recognised, while a filter that merely happens to match nothing is not. No constant-false filter, no replay: a genuinely empty result keeps taking the existing schema-discovery path at no extra cost.isEarlyCalculatedare evaluated, against a null record.WHERE 1=0in the planner today), so the replay is the cheaper of the two.Two static resolutions back it up for the cases the replay cannot cover, notably the
DESCRIBEpgJDBC issues forPreparedStatement.getMetaData(), which happens before the statement runs and with parameters still unbound:SELECT 1 AS n, sysdate() AS now);MATCHannounces itsRETURNlist, aliases included.And one correctness fix on the existing path: an
expand()projection used to report the target's columns, which it never produces (SELECT expand(out()) FROM Tdoes not returnT's columns). It now reports "unknown" and lets the replay answer instead.Behavioural trade-offs, stated explicitly
The replay evaluates the projection for real. The probe's own filter discards every row before the projection runs, so a projected function with a side effect - a sequence's
next(), a user-defined function that writes - was never invoked by the probe. The replay invokes it once, on one row, for the probes that take this path. This is inherent to the approach: the runtime shape of a computed projection cannot be learned without computing it, and guessing at it is what left this whole family of queries undescribable. Shapes the schema can already describe are answered without a replay whenever the replay finds no row, and the note now lives onsampleProbeColumnswhere it applies. (The "nothing is folded that could touch a record" guarantee above is about the filter folding, which remains true.)Cost. The replay only runs for a statement that carries a constant-false filter, and only after the check has been made on the parsed statement - a query that legitimately returns zero rows does not even pay for the AST copy. For the probe itself the replay drops
ORDER BY,SKIPandLIMITalong with the filter, since a row's columns do not depend on where it sits in the result; without that, a sorted or aggregated row source had to be materialized in full just to yield its first row. What remains is one extra bounded read per probe, against a probe that already scans its target for nothing.Possible follow-up (not in this PR)
WHERE 1=0is not constant-folded by the planner, so every schema probe currently scans its target in full to return nothing. Recognising an always-false filter at plan time and short-circuiting to an empty result would make every Spark probe free. That is an engine change with its own blast radius, so it is worth its own issue rather than riding along here.Verification
New regression test
PostgresWJdbcIT.schemaProbeForTypelessAndComputedProjectionsReturnsTheDescription, covering every shape in the report plus the boolean-algebra variants of the probe filter, a parameter-bound probe, and thegetMetaData()path. Verified to fail onmainand pass with the fix.Full
postgreswsuite green: 260 unit tests, 122 integration tests (PostgresWJdbcIT44,PostgresProtocolIT73, metrics/Tomcat/bind ITs 5).