Skip to content

Commit 4987c86

Browse files
committed
Phase 23 fix: pin checked-SUM aggregate inputs in every bound query block
Review finding (CRITICAL): checked SUM inside a predicate-owned subquery escaped the window order pin — decorrelation spliced the subplan into the memo where join transforms could reorder accumulation, putting success and checked-overflow plans in one equivalence group. Fix: every Aggregate containing checked SUM pins its complete relational input at bind time, in main blocks and independently bound subqueries alike; pins travel with the subplan into the memo. The window-side child scan is now redundant and removed. Bind-time assertion enforces the invariant. Regressions: reviewer repro (EXISTS subquery, INT64_MAX data) with decorrelation firing but commute pinned; plain no-window SUM-over-join; negative control keeps COUNT join alternatives. Fuzzer: 11049 paths, all frame floors intact, join_commute=409 globally.
1 parent d143e8d commit 4987c86

3 files changed

Lines changed: 155 additions & 20 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,11 +152,13 @@ Aggregate windows reuse the ordinary aggregate state machine. `COUNT(*)` counts
152152

153153
RANGE peer-boundary publication is load-bearing for optimizer correctness. For a row, the visible frame is determined by its complete ORDER BY key and the partition's key-ordered rows; equal-key rows cannot reveal their incidental input order because all peers receive the same value. Thus join commute/associate may reorder equal-key rows without changing a RANGE result. Checked RANGE SUM additionally sorts each peer group's non-NULL INT64 arguments ascending before applying `__builtin_add_overflow` at each prefix step. Key order fixes the order between peer groups, and this canonical within-peer order makes both the value and overflow category a function of key-group contents rather than stable tie order. Canonical checked accumulation can therefore report overflow on an intermediate even when a differently ordered mathematical sum would fit; that canonical outcome is the specification for both engines and every memo alternative.
154154

155-
ROWS deliberately makes peer order observable. Its stable sort retains child input order as the tie-break for equal OVER keys, the same deterministic contract as ROW_NUMBER, and every ROWS aggregate therefore pins its complete child subtree against order-changing transforms. Checked ROWS SUM uses `__builtin_add_overflow` for each input-ordered prefix step, so both its values and its possible intermediate overflow follow that pinned order. Whole-partition SUM keeps its Phase 22 pin because its checked accumulation is likewise input-order-sensitive. Even an order-safe outer RANGE window pins when its child contains an ordinary Aggregate SUM: that grouped child's checked accumulation can still change success versus intermediate overflow if a join below it is reordered. Predicate-placement rewrites that preserve stream order remain available.
155+
ROWS deliberately makes peer order observable. Its stable sort retains child input order as the tie-break for equal OVER keys, the same deterministic contract as ROW_NUMBER, and every ROWS aggregate therefore pins its complete child subtree against order-changing transforms. Checked ROWS SUM uses `__builtin_add_overflow` for each input-ordered prefix step, so both its values and its possible intermediate overflow follow that pinned order. Whole-partition SUM keeps its Phase 22 pin because its checked accumulation is likewise input-order-sensitive.
156+
157+
Every ordinary Aggregate containing checked SUM independently pins its complete relational input subtree at the end of binding that query block. This rule applies to a main block, a Window child, and every predicate-owned or scalar-expression-owned subquery before that subplan becomes opaque to its owner or is later spliced into the memo by decorrelation. The soundness reason is direct: join commute or association can change SUM's input sequence, and checked intermediate overflow makes success versus error observable even when the mathematical total is unchanged. Pinning the Aggregate input is sufficient because all order-changing joins that can affect its accumulation are descendants of that input; the Aggregate and its ancestors need no additional pin. COUNT/MIN/MAX Aggregate inputs and direct RANGE window aggregates therefore retain their verified alternatives, while predicate-placement rewrites that preserve stream order remain available. Binding asserts this invariant before returning each independently bound query block, so memo insertion never has to rediscover expression-owned subplans to repair their permissions.
156158

157159
The vectorized Window operator mirrors the oracle instead of introducing a fallback path. Physical Window carries each definition's bound frame enum unchanged from logical lowering. For each definition, vectorized execution compiles partition keys, order keys, and any aggregate argument once against the child batch. Partitions are built by probing a validity-aware `HashKey` map that uses GROUP BY/DISTINCT-style typed NULL equality; the map is lookup-only, while a separate vector records partitions in first-appearance order and rows in Window input order. Ranking and cumulative frames copy each partition's physical row ids and use the shared stable sort-key comparator. ROWS publishes after each ordered row; RANGE detects typed peers, updates through the peer boundary, and then publishes the shared result. Aggregate windows reuse the existing checked, NULL-skipping kernels, including the canonical RANGE SUM peer update. The operator stores Window values by original physical row id and gathers both child columns and Window columns through the immutable input selection vector, so output rows remain in the Window node's input order even after upstream filters or sorts.
158160

159-
Window is a rewrite barrier. No filter rule pushes a Filter through it, including filters that reference a window output; partition-key-only pushdown remains future proof work. Memo exploration still descends into an order-safe Window child, so already-proven join transformations remain available below RANK, DENSE_RANK, RANGE COUNT/SUM/MIN/MAX, and whole-partition COUNT/MIN/MAX. ROW_NUMBER, every ROWS aggregate, whole-partition SUM, and any Window whose child contains checked Aggregate SUM trigger the deterministic-input pins described above. This is a fail-closed proof boundary, not a general ban on optimizing below Window.
161+
Window is a rewrite barrier. No filter rule pushes a Filter through it, including filters that reference a window output; partition-key-only pushdown remains future proof work. Memo exploration still descends into an order-safe Window child, so already-proven join transformations remain available below RANK, DENSE_RANK, RANGE COUNT/SUM/MIN/MAX, and whole-partition COUNT/MIN/MAX until it reaches any independently pinned ordinary Aggregate SUM input. ROW_NUMBER, every ROWS aggregate, and whole-partition SUM trigger the Window-specific deterministic-input pins described above. This is a fail-closed proof boundary, not a general ban on optimizing below Window.
160162

161163
The memo hashes and compares every Window definition field, including the effective frame enum, and reconstructs Window in canonical, alternative, and best extraction. Costing preserves input cardinality and uses the documented conservative per-definition formula above. The deterministic SQL fuzzer generates Window queries across all seven functions, whole-partition and cumulative frame variants, partition/order variants, NULL-heavy and string keys, joined/grouped/HAVING inputs, multiple Window definitions, and final ORDER BY aliases; these queries run through unrewritten, rewritten, memo-alternative, and `extract_best` interpreted/vectorized verification. The remaining unsupported frame surface is every bound other than unbounded-preceding through current-row, plus `GROUPS`, exclusions, and other SQL frame modifiers.
162164

‎src/sql/binder.cpp‎

Lines changed: 67 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -973,18 +973,13 @@ void mark_deterministic_order(plan::LogicalPlan& logical) {
973973
}
974974
}
975975

976-
bool plan_contains_checked_sum_aggregate(const plan::LogicalPlan& logical) {
977-
if (logical.kind == plan::LogicalKind::Aggregate &&
978-
std::any_of(logical.aggregate_expressions.begin(),
979-
logical.aggregate_expressions.end(),
980-
[](const auto& aggregate) {
981-
return aggregate.function == AggregateFunction::Sum;
982-
})) {
983-
return true;
984-
}
985-
return (logical.input != nullptr && plan_contains_checked_sum_aggregate(*logical.input)) ||
986-
(logical.left != nullptr && plan_contains_checked_sum_aggregate(*logical.left)) ||
987-
(logical.right != nullptr && plan_contains_checked_sum_aggregate(*logical.right));
976+
bool aggregate_has_checked_sum(const plan::LogicalPlan& logical) {
977+
return logical.kind == plan::LogicalKind::Aggregate &&
978+
std::any_of(logical.aggregate_expressions.begin(),
979+
logical.aggregate_expressions.end(),
980+
[](const auto& aggregate) {
981+
return aggregate.function == AggregateFunction::Sum;
982+
});
988983
}
989984

990985
bool window_requires_deterministic_input(const plan::LogicalPlan& logical) {
@@ -1002,9 +997,30 @@ bool window_requires_deterministic_input(const plan::LogicalPlan& logical) {
1002997
(window.function == WindowFunction::Sum &&
1003998
window.frame == WindowFrame::WholePartition);
1004999
});
1005-
const auto child_has_checked_sum =
1006-
logical.input != nullptr && plan_contains_checked_sum_aggregate(*logical.input);
1007-
return frame_or_function_is_sensitive || child_has_checked_sum;
1000+
return frame_or_function_is_sensitive;
1001+
}
1002+
1003+
void protect_checked_sum_aggregate_inputs(plan::LogicalPlan& logical) {
1004+
if (aggregate_has_checked_sum(logical)) {
1005+
if (logical.input == nullptr) {
1006+
throw std::logic_error("Aggregate logical plan is missing its input");
1007+
}
1008+
// Checked SUM exposes input accumulation order through intermediate
1009+
// overflow. Pin its complete relational input in every independently
1010+
// bound query block, including predicate-owned subqueries that may be
1011+
// spliced into the memo by decorrelation.
1012+
mark_deterministic_order(*logical.input);
1013+
return;
1014+
}
1015+
if (logical.input != nullptr) {
1016+
protect_checked_sum_aggregate_inputs(*logical.input);
1017+
}
1018+
if (logical.left != nullptr) {
1019+
protect_checked_sum_aggregate_inputs(*logical.left);
1020+
}
1021+
if (logical.right != nullptr) {
1022+
protect_checked_sum_aggregate_inputs(*logical.right);
1023+
}
10081024
}
10091025

10101026
void protect_order_sensitive_window_inputs(plan::LogicalPlan& logical) {
@@ -1017,9 +1033,7 @@ void protect_order_sensitive_window_inputs(plan::LogicalPlan& logical) {
10171033
// SUM's checked intermediate overflow follows input accumulation
10181034
// order. RANGE publishes only peer-boundary values; its own SUM
10191035
// evaluator canonicalizes peer arguments before checked updates. A
1020-
// checked SUM in an Aggregate below Window still follows child order,
1021-
// so that dependency pins independently of the outer frame. Without
1022-
// these explicit proofs, order-changing join rules fail closed.
1036+
// Without these explicit proofs, order-changing join rules fail closed.
10231037
mark_deterministic_order(*logical.input);
10241038
return;
10251039
}
@@ -1034,6 +1048,39 @@ void protect_order_sensitive_window_inputs(plan::LogicalPlan& logical) {
10341048
}
10351049
}
10361050

1051+
void assert_deterministic_order_subtree(const plan::LogicalPlan& logical) {
1052+
if (logical.order_permission != plan::OrderPermission::Deterministic) {
1053+
throw std::logic_error("order-sensitive logical plan input is not pinned");
1054+
}
1055+
if (logical.input != nullptr) {
1056+
assert_deterministic_order_subtree(*logical.input);
1057+
}
1058+
if (logical.left != nullptr) {
1059+
assert_deterministic_order_subtree(*logical.left);
1060+
}
1061+
if (logical.right != nullptr) {
1062+
assert_deterministic_order_subtree(*logical.right);
1063+
}
1064+
}
1065+
1066+
void assert_order_sensitive_inputs_are_pinned(const plan::LogicalPlan& logical) {
1067+
if (aggregate_has_checked_sum(logical) || window_requires_deterministic_input(logical)) {
1068+
if (logical.input == nullptr) {
1069+
throw std::logic_error("order-sensitive logical plan is missing its input");
1070+
}
1071+
assert_deterministic_order_subtree(*logical.input);
1072+
}
1073+
if (logical.input != nullptr) {
1074+
assert_order_sensitive_inputs_are_pinned(*logical.input);
1075+
}
1076+
if (logical.left != nullptr) {
1077+
assert_order_sensitive_inputs_are_pinned(*logical.left);
1078+
}
1079+
if (logical.right != nullptr) {
1080+
assert_order_sensitive_inputs_are_pinned(*logical.right);
1081+
}
1082+
}
1083+
10371084
plan::JoinKind bound_join_kind(JoinKind parsed) {
10381085
switch (parsed) {
10391086
case JoinKind::Inner:
@@ -1169,7 +1216,9 @@ plan::LogicalPlan bind_select_impl(const SelectQuery& query,
11691216
bound = plan::LogicalPlan::distinct(std::move(bound));
11701217
}
11711218
mark_arbitrary_order(bound);
1219+
protect_checked_sum_aggregate_inputs(bound);
11721220
protect_order_sensitive_window_inputs(bound);
1221+
assert_order_sensitive_inputs_are_pinned(bound);
11731222
if (!sort_keys.empty()) {
11741223
bound = plan::LogicalPlan::sort(std::move(sort_keys), std::move(bound));
11751224
}

‎tests/vectorized_differential.cpp‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,33 @@ execution::Catalog make_golden_catalog() {
266266
range_overflow.add_column("k", std::move(range_overflow_k));
267267
range_overflow.add_column("v", std::move(range_overflow_v));
268268
catalog.add_table("range_overflow", std::move(range_overflow));
269+
270+
storage::Int64Column checked_sum_outer_k;
271+
checked_sum_outer_k.append(0);
272+
storage::ColumnarBatch checked_sum_outer;
273+
checked_sum_outer.add_column("k", std::move(checked_sum_outer_k));
274+
catalog.add_table("checked_sum_outer", std::move(checked_sum_outer));
275+
276+
storage::Int64Column checked_sum_left_id;
277+
storage::Int64Column checked_sum_left_v;
278+
checked_sum_left_id.append(0);
279+
checked_sum_left_v.append(std::numeric_limits<std::int64_t>::max());
280+
checked_sum_left_id.append(1);
281+
checked_sum_left_v.append(-1);
282+
checked_sum_left_id.append(2);
283+
checked_sum_left_v.append(1);
284+
storage::ColumnarBatch checked_sum_left;
285+
checked_sum_left.add_column("id", std::move(checked_sum_left_id));
286+
checked_sum_left.add_column("v", std::move(checked_sum_left_v));
287+
catalog.add_table("checked_sum_left", std::move(checked_sum_left));
288+
289+
storage::Int64Column checked_sum_right_id;
290+
for (auto value : {0, 2, 1}) {
291+
checked_sum_right_id.append(value);
292+
}
293+
storage::ColumnarBatch checked_sum_right;
294+
checked_sum_right.add_column("id", std::move(checked_sum_right_id));
295+
catalog.add_table("checked_sum_right", std::move(checked_sum_right));
269296
return catalog;
270297
}
271298

@@ -1348,6 +1375,60 @@ void assert_running_window_paths_and_error_equivalence() {
13481375
context));
13491376
}
13501377

1378+
void assert_plain_checked_sum_pins_join_order() {
1379+
const auto catalog = make_golden_catalog();
1380+
const std::string context =
1381+
"checked_sum_left(id,v)=[(0,INT64_MAX),(1,-1),(2,1)]; "
1382+
"checked_sum_right(id)=[(0),(2),(1)]";
1383+
differential::ComparisonStats stats;
1384+
const auto sql_text =
1385+
"SELECT SUM(a.v) AS total "
1386+
"FROM checked_sum_left AS a "
1387+
"JOIN checked_sum_right AS b ON a.id = b.id";
1388+
1389+
assert(differential::compare_engines(sql_text, catalog, context, &stats));
1390+
assert(stats.execution_path_count > 0);
1391+
assert(stats.join_commute_firings == 0);
1392+
assert(stats.accepted_error_path_count == 0);
1393+
}
1394+
1395+
void assert_opaque_checked_sum_subquery_pins_after_decorrelation() {
1396+
const auto catalog = make_golden_catalog();
1397+
const std::string context =
1398+
"checked_sum_outer(k)=[(0)]; "
1399+
"checked_sum_left(id,v)=[(0,INT64_MAX),(1,-1),(2,1)]; "
1400+
"checked_sum_right(id)=[(0),(2),(1)]";
1401+
differential::ComparisonStats stats;
1402+
const auto sql_text =
1403+
"SELECT o.k, COUNT(*) OVER (ORDER BY o.k) AS running_n "
1404+
"FROM checked_sum_outer AS o "
1405+
"WHERE EXISTS ("
1406+
"SELECT SUM(a.v) FROM checked_sum_left AS a "
1407+
"JOIN checked_sum_right AS b ON a.id = b.id)";
1408+
1409+
assert(differential::compare_engines(sql_text, catalog, context, &stats));
1410+
assert(stats.execution_path_count > 0);
1411+
assert(stats.alternative_count > 1);
1412+
assert(stats.exists_to_semi_firings > 0);
1413+
assert(stats.join_commute_firings == 0);
1414+
assert(stats.accepted_error_path_count == 0);
1415+
}
1416+
1417+
void assert_order_insensitive_aggregate_keeps_join_alternatives() {
1418+
const auto catalog = make_golden_catalog();
1419+
const std::string context = "checked SUM pin negative control";
1420+
differential::ComparisonStats stats;
1421+
const auto sql_text =
1422+
"SELECT COUNT(*) AS n "
1423+
"FROM checked_sum_left AS a "
1424+
"JOIN checked_sum_right AS b ON a.id = b.id";
1425+
1426+
assert(differential::compare_engines(sql_text, catalog, context, &stats));
1427+
assert(stats.alternative_count > 1);
1428+
assert(stats.join_commute_firings > 0);
1429+
assert(stats.accepted_error_path_count == 0);
1430+
}
1431+
13511432
} // namespace
13521433

13531434
int main() {
@@ -1360,6 +1441,9 @@ int main() {
13601441
assert_correlated_scalar_error_is_equivalent_on_every_oracle_path();
13611442
assert_window_paths_and_vectorized_execution();
13621443
assert_running_window_paths_and_error_equivalence();
1444+
assert_opaque_checked_sum_subquery_pins_after_decorrelation();
1445+
assert_plain_checked_sum_pins_join_order();
1446+
assert_order_insensitive_aggregate_keeps_join_alternatives();
13631447

13641448
bool ok = true;
13651449
ok = run_result_golden_queries() && ok;

0 commit comments

Comments
 (0)