Skip to content

fix(#6156): a Postgres schema probe over a typeless row source no longer returns an empty RowDescription - #6172

Merged
lvca merged 4 commits into
mainfrom
issue-6156-postgres-typeless-schema-probe
Aug 14, 2026
Merged

lvca merged 4 commits into
mainfrom
issue-6156-postgres-typeless-schema-probe

Conversation

@lvca

@lvca lvca commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

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 the RowDescription from 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:

shape before
SELECT * FROM (SELECT 1 AS n) t WHERE 1=0 no columns
SELECT * FROM (SELECT expand([1,2,3]) AS n) t WHERE 1=0 no columns
shortestPath(...) / dijkstra(...) as the row source no columns
TRAVERSE ... FROM (...) MAXDEPTH n no columns
MATCH {...} RETURN ... no columns
any query with no FROM at all no columns

The very same queries without WHERE 1=0 return 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:

  • It only fires on a probe. The constant-false filter is read in the disjunctive normal form the planner itself uses (BooleanExpression.flatten()), so 1=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.
  • Nothing is folded that could touch a record. Only comparisons whose two operands are isEarlyCalculated are evaluated, against a null record.
  • It is bounded and read-only. The replay is a copy of the parsed SELECT, executed with the parameters the probe was bound with, and only the first row is pulled. It runs under the same session and the same authorization as the query the client just sent - the only thing dropped is the client's own always-false predicate. Note the probe itself already scans the target (there is no constant-folding of WHERE 1=0 in 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 DESCRIBE pgJDBC issues for PreparedStatement.getMetaData(), which happens before the statement runs and with parameters still unbound:

  • an explicit projection list names its own columns when the row source carries no discoverable schema (SELECT 1 AS n, sysdate() AS now);
  • a MATCH announces its RETURN list, 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 T does not return T'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 on sampleProbeColumns where 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, SKIP and LIMIT along 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=0 is 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 the getMetaData() path. Verified to fail on main and pass with the fix.

Full postgresw suite green: 260 unit tests, 122 integration tests (PostgresWJdbcIT 44, PostgresProtocolIT 73, metrics/Tomcat/bind ITs 5).

…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.
@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

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 92 complexity

Metric Results
Complexity 92

View in Codacy

🟢 Coverage 75.32% diff coverage

Metric Results
Coverage variation Report missing for de774e31
Diff coverage ✅ 75.32% diff coverage

View coverage diff in Codacy

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.

@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review

Nice 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 WHERE 1=0 recognition (BooleanExpression.flatten(), only folding isEarlyCalculated operands against a null record) is a careful way to keep the replay from ever touching a record. The regression test is thorough (constants, expand(), graph functions, TRAVERSE, MATCH, boolean-algebra variants of the filter, bound parameters, and the getMetaData()/DESCRIBE path).

A few things worth a second look before merge:

1. The replay can execute side-effecting expressions that previously never ran.
WHERE 1=0 filters out every row before the projection is (usually) evaluated, so any function call in the SELECT list or in a nested FROM subquery with a side effect (e.g. a sequence's .next(), a custom SQL function that writes) was never actually invoked by the original probe. sampleProbeColumns strips the filter and pulls a real row, so those expressions now execute for real, once, on every DESCRIBE/EXECUTE of a probe that returns zero rows for reasons other than the filter. That's a reasonable trade-off given what the PR is trying to solve, but it's a behavioral change worth calling out explicitly in the PR description/changelog rather than leaving implicit — "nothing is folded that could touch a record" (true for the filter) reads a bit stronger than what actually holds once the projection runs for real.

2. The "replay is cheaper" reasoning doesn't hold uniformly.
For a plain unfiltered scan, capping the replay at 1 row (browseAndCacheResultSet(resultSet, 1, false)) is indeed cheaper than the original full WHERE 1=0 scan. For ORDER BY / GROUP BY / aggregate row sources, though, the executor generally has to materialize the whole result before yielding the first row, so the DESCRIBE round trip roughly doubles for those shapes (original 1=0 scan + full replay). Not a blocker, but worth confirming this is acceptable, since Spark issues one such probe per pushed-down query.

3. Minor: every genuinely-empty SELECT now pays extra cost, not just probes.
sampleProbeColumns always does select.copy() (a full AST deep copy) and walks/evaluates the WHERE clause looking for a constant-false term before concluding "not a probe" and falling through to the pre-existing static path. That's a new, always-paid cost on the common case of a real (non-probe) query that legitimately returns zero rows. Likely negligible per-query, but flagging given the project's performance mantra — might be worth a quick before/after benchmark on a hot empty-result path.

4. Minor: redundant parse in the DESCRIBE-portal path.
In describeCommand(), resolveEmptyResultSchemaColumns(portal.query, ...) re-parses portal.query text from scratch via parseStatement, even though portal.sqlStatement (the already-parsed statement that was just executed) is sitting right there. Re-parsing is cheap relative to the replay execution itself, but since portal.sqlStatement is frequently the same SelectStatement, threading it through instead of re-parsing would avoid the duplicate work.

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.
The new test binds a parameter inside a nested subquery's own WHERE (untouched by the strip), but doesn't cover WHERE 1=0 AND name = ? in a single clause, where removeAlwaysFalseFilters drops the entire clause including the still-referenced ?. This is likely harmless (positional binding by index shouldn't choke on an unused trailing arg, and the whole thing is guarded by the broad try/catch in sampleProbeColumns anyway, falling back gracefully), but a regression test for it would remove the doubt and pin down the behavior explicitly.

None of the above looks blocking — the guards (language check, isEarlyCalculated-only folding, broad try/catch around the replay, bounded LIMIT 1) make this safe to land even if 1–3 turn out to matter in practice. Mostly flagging for awareness and a possible fast-follow.

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.
@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Reviewed the diff (PostgresNetworkExecutor.java + PostgresWJdbcIT.java). The approach (replay the probe with its constant-false filter stripped, rather than enumerating row-source shapes) is a nice simplification and the write-up is unusually thorough. A few things worth a look:

Potential bug/side-effect risk (the main one)

isAlwaysFalse -> isConstantFalseComparison decides a BinaryCondition is worth folding purely on left.isEarlyCalculated(context) && right.isEarlyCalculated(context), then calls condition.evaluate((Result) null, context) to see if it's constant-false. But isEarlyCalculated only means "does not need a record" - FunctionCall.isEarlyCalculated (FunctionCall.java:334) returns true for any function call whose arguments don't reference a record, regardless of whether the function has side effects (a stateful UDF, a sequence accessed via a method chain, anything doing I/O). There's no purity/idempotence marker on SQLFunction to distinguish these.

Concretely: this check runs on every query that legitimately returns zero rows and has a WHERE clause containing a BinaryCondition between two record-independent operands, not just on genuine WHERE 1=0 probes. WHERE someStatefulFunction() = 42 that happens to match no rows today would get someStatefulFunction() invoked a second time by this new path, purely to answer "is this a probe?". If the function has a side effect, that's an extra, unintended invocation.

There is a precedent for evaluating early-calculated expressions outside of per-row execution (WhereClause.getEqualityOperations, used for index-cost estimation), so this isn't unprecedented in the codebase - but that existing call site evaluates only one operand, only during planning of the query that's actually running. This new path adds a genuinely extra evaluation, unconditionally, whenever the result happens to be empty, which is a much more common case than "the client sent a schema probe."

Given isConstantFalseComparison already restricts to BinaryCondition, would it be worth narrowing further to expressions that are guaranteed side-effect-free (e.g. literals/ValueExpression/arithmetic over literals) rather than the general isEarlyCalculated, which admits arbitrary function calls? That would still catch 1=0, (1=0) OR (2=3), etc. (the shapes actually tested) without evaluating arbitrary functions on queries that were never probes.

Minor / nit

  • describeCommand()'s 'S'-type branch (PostgresNetworkExecutor.java:350) still calls the single-arg getColumnsFromQuerySchema(portal.query), which re-parses the query text with parseStatement, even though portal.sqlStatement was already parsed at Parse time (line ~1874) and is sitting on the portal. It may not be reusable directly today since parameters aren't bound yet at this point, but it could at least pass portal.sqlStatement as the already-parsed Statement to avoid the redundant parse, mirroring what was done for the other three call sites in this PR.

Things that look solid

  • sampleProbeColumns calls select.copy() before stripProbe mutates anything, so the cached portal.sqlStatement is never mutated in place - a real risk would've been a later real Execute on the same portal silently running with its WHERE clause stripped, and this avoids it.
  • The replay is properly bounded: browseAndCacheResultSet(resultSet, 1, false) pulls at most one row and closes the ResultSet via try-with-resources either way.
  • The new language != null && !"sql".equalsIgnoreCase(language) gate in resolveEmptyResultSchemaColumns is a tighter guard than the old startsWith("SELECT") textual check (which technically didn't gate on language at all before).
  • Test coverage is thorough - it exercises the DNF recognition (AND, OR, parentheses), graph functions, TRAVERSE, MATCH, parameterized probes, the "constant-false term ANDed with a real predicate that references a bound parameter" edge case, and the pgJDBC getMetaData()/DESCRIBE path. No test currently covers a side-effecting function in the probe's WHERE clause, understandably, since that's the scenario flagged above.

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.
@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review

I read through the full diff in PostgresNetworkExecutor.java and the new integration test, and cross-checked every parser API used (BooleanExpression.flatten(), AndBlock.getSubBlocks(), BinaryCondition.left/right, Expression/BaseExpression/MathExpression fields, MatchStatement.getReturnItems()/getReturnAliases(), SelectStatement.copy()/execute(...)) against their current definitions in engine/. Everything referenced exists with the signatures used, and the public-field mutation style (select.orderBy = null, etc.) matches how SelectStatement.copy() itself accesses those fields.

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:

  • Double execution across DESCRIBE + EXECUTE: describeCommand() (type 'P') always sets portal.rowDescriptionSent = true after its resolveEmptyResultSchemaColumns attempt, whether or not the replay found columns. Since executeCommand() only re-derives columns when !portal.rowDescriptionSent, the replay (and any side effect it triggers) cannot run twice for the same portal. Good.
  • Side effects during the DESCRIBE-statement ('S') path: correctly kept fully static (getColumnsFromQuerySchema/getColumnsFromProjection), since parameters aren't bound yet at that point - no replay happens there.
  • Literal-only folding: restricting isLiteral to number/string/boolean/null/arithmetic (rather than isEarlyCalculated) is the right call and is directly tested (uuid() = 'nomatch' is correctly not folded).

Minor observations (none blocking)

  1. stripProbe drops the whole WHERE clause, not just the false term (PostgresNetworkExecutor.java, stripProbe). For WHERE 1=0 AND name = ?, the replay runs against the entire unfiltered target, not WHERE name = ?. This is intentional and safe for the stated purpose (only column names/types are read off the sampled row via getColumns, never values), and it's exactly what the new test schemaProbeForTypelessAndComputedProjectionsReturnsTheDescription pins down. Worth double-checking it stays true if getColumns/writeRowDescription ever grows to expose sample values (e.g. default-value hints) in the future - at that point the dropped real predicate would matter.

  2. Redundant re-parse on the failure path: in resolveEmptyResultSchemaColumns, if parseStatement(query) fails (returns null), parsed is null, and the subsequent getColumnsFromQuerySchema(query, parsed) call re-invokes parseStatement(query) a second time internally (since alreadyParsed is null). It'll fail again the same way, so it's harmless, just a small wasted parse on an already-rare error path. Not worth a special case.

  3. AndBlock.flatten()'s exponential-explosion guard returns the block unflattened when the cap is exceeded. In that case a deeply nested boolean probe filter could fail to be recognized as constant-false, silently falling back to the pre-[BUG] Postgres wire: Schema probe wrapping for typeless/computed projections produces empty RowDescription #6156 behavior (no columns) instead of erroring. That's a safe degradation, not a correctness bug, but if this ever shows up in practice it'd be worth a DEBUG log line in isAlwaysFalse for visibility, similar to the one in sampleProbeColumns's catch block.

  4. Cost model as documented is accurate: hasAlwaysFalseFilter runs before select.copy(), so a genuinely empty result doesn't pay for the AST deep copy, matching the second commit's stated goal. Confirmed by reading the call order in sampleProbeColumns.

Test coverage

The new schemaProbeForTypelessAndComputedProjectionsReturnsTheDescription test is thorough: it covers every shape called out in the issue (constant projections, expand(), shortestPath()/dijkstra(), TRAVERSE, MATCH both nested and standalone), the DNF boolean-algebra recognition (AND, OR, parenthesized), the negative cases (function-based filters not folded), bound-parameter replay, the ORDER BY/SKIP/LIMIT-stripping behavior, and the getMetaData() static path. That's good regression coverage for a bug this easy to reintroduce piecemeal.

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 WHERE already implies for that target), and only ever surfaces column names and types, never row values, back to the wire protocol.

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.
@claude

claude Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review: fix(#6156) Postgres schema probe over typeless row sources

This 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

resolveEmptyResultSchemaColumns -> sampleProbeColumns is reached from three call sites: describeCommand() (type 'P'), executeCommand(), and queryCommand() (PostgresNetworkExecutor.java:329, :419, :571). The PR description frames the projection-side-effect trade-off as something that happens "once, on one row, for the probes that take this path," which reads as scoped to the DESCRIBE-time metadata probe. In practice it also fires for a plain Execute/simple Query that returns zero rows and happens to match the constant-false-filter heuristic:

  1. The client's real statement runs with its WHERE 1=0-shaped filter and (correctly) returns 0 rows, so the filtered-out projection never executes.
  2. Because the result is empty, sampleProbeColumns replays the statement a second time with the filter (and the whole clause it lives in, plus ORDER BY/SKIP/LIMIT) stripped, and actually executes the projection against a real, unfiltered row purely to infer RowDescription column types.
  3. That sampled row's values are discarded (only used for PostgresType inference in getColumns), but any side effect in the projection (a sequence next(), a stateful UDF, an expand() over something that mutates) has already happened.

Since WHERE 1=0 (or the literal-only variants recognized by isAlwaysFalse) is not a pattern real application queries have a reason to use, the practical blast radius is probably limited to genuine schema probes in practice. But the code doesn't distinguish "this is a DESCRIBE-only metadata request" from "this is a real Execute the client wants the side effects of" - both get the same replay-with-real-side-effects treatment. Worth either: (a) confirming this is intentional and acceptable for the Execute/Query paths too (not just Describe), or (b) gating the replay so it only fires from the DESCRIBE path, where no client-visible execution has "really" happened yet from the client's perspective.

Related, and already flagged in the docstring on stripProbe: because the whole WHERE clause is dropped (not just the false term), WHERE 1=0 AND department = 'legal' samples from the entire unfiltered target, not the department = 'legal' subset. For a schemaless/dynamic property whose type varies across subsets of rows, the inferred PostgresType could differ from what the real (filtered) query would have produced. This is called out as a documented risk if RowDescription ever starts carrying sample values, but it already affects type inference today, since getColumns reads real property values off the sampled row to pick the PostgreSQL OID (arrays vs scalars vs JSON, getDeclaredListType, etc.). Probably fine in practice, but worth a conscious sign-off since it's a step beyond "the row never reaches the wire."

Code quality

  • stripProbe uses select.setWhereClause(null) for the WHERE clause but reaches into select.orderBy, select.skip, select.limit as raw field assignments right next to it. Minor inconsistency; if setters exist for those (setOrderBy/setSkip/setLimit), using them would match the style of the line right above.
  • The new isLiteral(Expression) / isLiteral(MathExpression) pair deliberately narrows past Expression.isEarlyCalculated() to avoid invoking functions during probe classification. The reasoning is spelled out well in the Javadoc and the accompanying test (uuid() = 'nomatch' staying unrecognized) is a good regression guard for exactly this.
  • getColumnsFromProjection and getColumnsFromMatch both bail to null on the first item that can't be named cleanly rather than returning a partial column set - reasonable, since a partial RowDescription would likely be worse than none, and it's applied consistently with the existing applyProjection "keep the full set rather than guess" philosophy.

Performance

  • hasAlwaysFalseFilter/isAlwaysFalse calls BooleanExpression.flatten(), which is already used on the normal SELECT planning path (SelectExecutionPlanner), so it's not a new algorithmic cost class, just a second flatten pass on the empty-result path. Given it's gated behind "result set is already empty," this seems acceptable.
  • Dropping ORDER BY/SKIP/LIMIT at every level of the FROM chain (not just the level carrying the constant-false filter) is a nice touch for avoiding an unnecessary full materialize-and-sort just to hand back one row; the reasoning in the Javadoc on stripProbe is clear.
  • The AST deep copy (select.copy()) is correctly ordered after the cheap hasAlwaysFalseFilter check, so a genuinely-empty query (the common case on this path) doesn't pay for it - the second commit's message explicitly calls this out as a follow-up fix, good catch.

Test coverage

schemaProbeForTypelessAndComputedProjectionsReturnsTheDescription is comprehensive: no-FROM projections, expand(), graph functions (shortestPath/dijkstra), TRAVERSE, MATCH both nested and top-level, DNF variants of the probe filter (AND, OR, parenthesized), the "a filter that merely returns nothing isn't a probe" cases via uuid(), bound-parameter probes, and the AND-with-a-real-predicate parameter case. That's a solid regression suite for the shapes described in the issue.

One gap: there's no test exercising the side-effect-replay concern above through executeCommand/queryCommand (only the DESCRIBE/getMetaData() paths are covered) to confirm the intended scope of when a real execution happens versus when it's "just" metadata discovery. Might be worth an explicit test (or an explicit "yes, this is intended" note in the PR) either way.

Security

Nothing 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

codecov Bot commented Aug 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 53.89610% with 71 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.91%. Comparing base (1c5859a) to head (e0a66fa).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
...com/arcadedb/postgres/PostgresNetworkExecutor.java 53.89% 38 Missing and 33 partials ⚠️
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.
📢 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.

lvca added a commit that referenced this pull request Aug 14, 2026
…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
lvca added a commit that referenced this pull request Aug 14, 2026
…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.
lvca added a commit that referenced this pull request Aug 15, 2026
…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.
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.

[BUG] Postgres wire: Schema probe wrapping for typeless/computed projections produces empty RowDescription

1 participant