|
| 1 | +package io.github.dfa1.vortex.calcite; |
| 2 | + |
| 3 | +import io.github.dfa1.vortex.reader.ArrayStats; |
| 4 | + |
| 5 | +import com.google.common.collect.ImmutableList; |
| 6 | +import org.apache.calcite.interpreter.Bindables; |
| 7 | +import org.apache.calcite.plan.RelOptRule; |
| 8 | +import org.apache.calcite.plan.RelOptRuleCall; |
| 9 | +import org.apache.calcite.plan.RelOptRuleOperand; |
| 10 | +import org.apache.calcite.rel.RelNode; |
| 11 | +import org.apache.calcite.rel.core.Aggregate; |
| 12 | +import org.apache.calcite.rel.core.AggregateCall; |
| 13 | +import org.apache.calcite.rel.core.Project; |
| 14 | +import org.apache.calcite.rel.core.TableScan; |
| 15 | +import org.apache.calcite.rel.logical.LogicalValues; |
| 16 | +import org.apache.calcite.rel.type.RelDataType; |
| 17 | +import org.apache.calcite.rel.type.RelDataTypeField; |
| 18 | +import org.apache.calcite.rex.RexBuilder; |
| 19 | +import org.apache.calcite.rex.RexInputRef; |
| 20 | +import org.apache.calcite.rex.RexLiteral; |
| 21 | +import org.apache.calcite.rex.RexNode; |
| 22 | +import org.apache.calcite.sql.SqlKind; |
| 23 | + |
| 24 | +import java.math.BigDecimal; |
| 25 | +import java.util.ArrayList; |
| 26 | +import java.util.List; |
| 27 | + |
| 28 | +/// Rewrites a whole-table `MIN`/`MAX`/`COUNT` aggregate over a [VortexTable] into a single-row |
| 29 | +/// [LogicalValues] computed from the footer zone-map statistics — answering the query without |
| 30 | +/// decoding a single data segment (ADR 0013 §6, ADR 0018 Phase 2). |
| 31 | +/// |
| 32 | +/// Fires only when it can answer *every* aggregate from statistics: no `GROUP BY`, and each |
| 33 | +/// call is `COUNT(*)`, `COUNT(col)`, `MIN(col)`, or `MAX(col)` over a numeric column. Anything |
| 34 | +/// else (e.g. `SUM`, a grouped aggregate, `MIN` on a non-numeric column) leaves the plan |
| 35 | +/// untouched for the normal scan path. `SUM`/`AVG` join this tier once the writer emits a |
| 36 | +/// per-zone `SUM` statistic. |
| 37 | +// Calcite 1.40 removed RelRule.Config.EMPTY; the modern RelRule.Config path requires the |
| 38 | +// Immutables annotation processor. The classic operand() constructor is deprecated but fully |
| 39 | +// supported and far lighter for a single adapter rule — suppression is localized and justified. |
| 40 | +@SuppressWarnings("deprecation") |
| 41 | +public final class VortexAggregatePushDownRule extends RelOptRule { |
| 42 | + |
| 43 | + /// Matches `Aggregate(Project(TableScan))` — the shape Calcite produces when columns are |
| 44 | + /// selected before aggregation (e.g. `MIN(low)`). |
| 45 | + public static final VortexAggregatePushDownRule WITH_PROJECT = new VortexAggregatePushDownRule( |
| 46 | + operand(Aggregate.class, operand(Project.class, operand(TableScan.class, none()))), |
| 47 | + "VortexAggregatePushDownRule:project"); |
| 48 | + |
| 49 | + /// Matches `Aggregate(TableScan)` — e.g. a bare `COUNT(*)` with no projected columns. |
| 50 | + public static final VortexAggregatePushDownRule NO_PROJECT = new VortexAggregatePushDownRule( |
| 51 | + operand(Aggregate.class, operand(TableScan.class, none())), |
| 52 | + "VortexAggregatePushDownRule:scan"); |
| 53 | + |
| 54 | + /// Every rule variant, for registering with a planner in one call. |
| 55 | + public static final java.util.List<RelOptRule> RULES = java.util.List.of(WITH_PROJECT, NO_PROJECT); |
| 56 | + |
| 57 | + private VortexAggregatePushDownRule(RelOptRuleOperand operand, String description) { |
| 58 | + super(operand, description); |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public void onMatch(RelOptRuleCall call) { |
| 63 | + Aggregate aggregate = call.rel(0); |
| 64 | + if (aggregate.getGroupCount() != 0) { |
| 65 | + return; |
| 66 | + } |
| 67 | + // Explicit operands give concrete rels under both Hep and Volcano: rel(1) is either the |
| 68 | + // Project (then rel(2) is the scan) or the scan directly. |
| 69 | + Project project; |
| 70 | + TableScan scan; |
| 71 | + if (call.rel(1) instanceof Project p) { |
| 72 | + project = p; |
| 73 | + scan = call.rel(2); |
| 74 | + } else { |
| 75 | + project = null; |
| 76 | + scan = call.rel(1); |
| 77 | + } |
| 78 | + VortexTable table = scan.getTable().unwrap(VortexTable.class); |
| 79 | + if (table == null) { |
| 80 | + return; |
| 81 | + } |
| 82 | + // Whole-table stats are only valid for a whole-table scan. If a WHERE predicate was pushed |
| 83 | + // into the scan (BindableTableScan.filters), answering from stats would ignore it and return |
| 84 | + // the wrong MIN/MAX/COUNT — leave the plan to compute it over the filtered rows. |
| 85 | + if (scan instanceof Bindables.BindableTableScan bindable && !bindable.filters.isEmpty()) { |
| 86 | + return; |
| 87 | + } |
| 88 | + RelDataType scanRowType = scan.getRowType(); |
| 89 | + List<String> scanColumns = scanRowType.getFieldNames(); |
| 90 | + |
| 91 | + RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder(); |
| 92 | + List<RelDataType> outTypes = aggregate.getRowType().getFieldList().stream() |
| 93 | + .map(f -> f.getType()).toList(); |
| 94 | + |
| 95 | + List<RexLiteral> row = new ArrayList<>(); |
| 96 | + List<AggregateCall> calls = aggregate.getAggCallList(); |
| 97 | + for (int i = 0; i < calls.size(); i++) { |
| 98 | + RexLiteral literal = evaluate(calls.get(i), outTypes.get(i), table, scanColumns, scanRowType, |
| 99 | + project, rexBuilder); |
| 100 | + if (literal == null) { |
| 101 | + return; // an aggregate we can't answer from stats — abandon the rewrite |
| 102 | + } |
| 103 | + row.add(literal); |
| 104 | + } |
| 105 | + |
| 106 | + RelNode values = LogicalValues.create( |
| 107 | + aggregate.getCluster(), aggregate.getRowType(), |
| 108 | + ImmutableList.of(ImmutableList.copyOf(row))); |
| 109 | + call.transformTo(values); |
| 110 | + } |
| 111 | + |
| 112 | + /// Evaluates one aggregate call from zone-map stats, returning a literal of `outType`, or |
| 113 | + /// `null` if it cannot be answered (so the caller abandons the rewrite). |
| 114 | + private static RexLiteral evaluate(AggregateCall agg, RelDataType outType, VortexTable table, |
| 115 | + List<String> scanColumns, RelDataType scanRowType, |
| 116 | + Project project, RexBuilder rexBuilder) { |
| 117 | + return switch (agg.getAggregation().getKind()) { |
| 118 | + case COUNT -> { |
| 119 | + if (agg.getArgList().isEmpty()) { |
| 120 | + yield exact(rexBuilder, table.totalRows(), outType); // COUNT(*) |
| 121 | + } |
| 122 | + String col = resolveColumn(agg.getArgList().getFirst(), scanColumns, project); |
| 123 | + if (col == null) { |
| 124 | + yield null; |
| 125 | + } |
| 126 | + Long nullCount = table.statsOf(col).nullCount(); |
| 127 | + // COUNT(col) = rows − nulls. Without a NULL_COUNT stat we cannot assume zero nulls |
| 128 | + // for a nullable column (we would overcount), so abandon; a non-nullable column has |
| 129 | + // no nulls and is safe. |
| 130 | + if (nullCount == null && isNullable(scanRowType, col)) { |
| 131 | + yield null; |
| 132 | + } |
| 133 | + long nulls = nullCount == null ? 0L : nullCount; |
| 134 | + yield exact(rexBuilder, table.totalRows() - nulls, outType); |
| 135 | + } |
| 136 | + case MIN, MAX -> { |
| 137 | + if (agg.getArgList().size() != 1) { |
| 138 | + yield null; |
| 139 | + } |
| 140 | + String col = resolveColumn(agg.getArgList().getFirst(), scanColumns, project); |
| 141 | + if (col == null) { |
| 142 | + yield null; |
| 143 | + } |
| 144 | + ArrayStats stats = table.statsOf(col); |
| 145 | + Object value = agg.getAggregation().getKind() == SqlKind.MIN ? stats.min() : stats.max(); |
| 146 | + if (value == null) { |
| 147 | + // No MIN/MAX stat. A genuine SQL NULL is only correct when the column provably has |
| 148 | + // no non-null rows (empty table, or every row null); otherwise the stat is merely |
| 149 | + // absent and we must abandon so the scan computes the real value. |
| 150 | + long total = table.totalRows(); |
| 151 | + Long nullCount = stats.nullCount(); |
| 152 | + boolean provablyNoValues = total == 0 || (nullCount != null && nullCount == total); |
| 153 | + yield provablyNoValues ? rexBuilder.makeNullLiteral(outType) : null; |
| 154 | + } |
| 155 | + yield numericLiteral(rexBuilder, value, outType); |
| 156 | + } |
| 157 | + default -> null; |
| 158 | + }; |
| 159 | + } |
| 160 | + |
| 161 | + /// Returns whether column `col` is nullable per the scan's row type. |
| 162 | + private static boolean isNullable(RelDataType scanRowType, String col) { |
| 163 | + RelDataTypeField field = scanRowType.getField(col, true, false); |
| 164 | + return field == null || field.getType().isNullable(); |
| 165 | + } |
| 166 | + |
| 167 | + /// Maps an aggregate input ordinal to a scan column name, looking through a `Project` of input |
| 168 | + /// refs when present. Returns `null` if the ordinal is a computed expression, not a column. |
| 169 | + private static String resolveColumn(int aggInput, List<String> scanColumns, Project project) { |
| 170 | + if (project == null) { |
| 171 | + return aggInput < scanColumns.size() ? scanColumns.get(aggInput) : null; |
| 172 | + } |
| 173 | + RexNode expr = project.getProjects().get(aggInput); |
| 174 | + if (expr instanceof RexInputRef ref && ref.getIndex() < scanColumns.size()) { |
| 175 | + return scanColumns.get(ref.getIndex()); |
| 176 | + } |
| 177 | + return null; |
| 178 | + } |
| 179 | + |
| 180 | + private static RexLiteral exact(RexBuilder rexBuilder, long value, RelDataType type) { |
| 181 | + return rexBuilder.makeExactLiteral(BigDecimal.valueOf(value), type); |
| 182 | + } |
| 183 | + |
| 184 | + /// Builds a literal for a non-null `MIN`/`MAX` value, supporting only numeric output types |
| 185 | + /// (exact and approximate). A non-numeric value yields `null` so the rule abandons the rewrite. |
| 186 | + private static RexLiteral numericLiteral(RexBuilder rexBuilder, Object value, RelDataType type) { |
| 187 | + if (!(value instanceof Number number)) { |
| 188 | + return null; |
| 189 | + } |
| 190 | + return switch (type.getSqlTypeName()) { |
| 191 | + case TINYINT, SMALLINT, INTEGER, BIGINT -> |
| 192 | + rexBuilder.makeExactLiteral(BigDecimal.valueOf(number.longValue()), type); |
| 193 | + case FLOAT, REAL, DOUBLE, DECIMAL -> |
| 194 | + rexBuilder.makeApproxLiteral(BigDecimal.valueOf(number.doubleValue()), type); |
| 195 | + default -> null; |
| 196 | + }; |
| 197 | + } |
| 198 | +} |
0 commit comments