Files
discord9 0ce4799e48 feat(query): opt-in experimental factorized join aggregation rewrite (WIP) (#9546)
* feat(query): opt-in experimental factorized join aggregation rewrite

Add an experimental shape-based rewrite for AVG(value * weight) and
SUM(value * weight) over an inner equi-join grouped by (host, area),
turning it into per-side preaggregates joined and combined in a
projection. Opt-in via the new query option
experimental_enable_factorized_join_agg (default false), settable per
session with SET. The rule is registered always and gates at rewrite
time. Approximation contract documented: well-conditioned inputs match
baseline to ~1e-9; heavy cancellation/overflow may diverge and is
accepted in this opt-in mode.

WIP: config/config.md regeneration pending (make config-docs, needs
Docker). Draft.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

* fix(query): finish switch wiring, config docs, engine-level opt-in test

Declare the count_join module without the test gate, register the rule
unconditionally, and read FactorizedJoinAggOptions at rewrite time
(default off -> Transformed::no). Replace the ported fixture suite with
an engine-level test comparing plans with the switch off and on.
Regenerate config/config.md (make config-docs).

Verified: cargo nextest -p query 815 passed / 2 skipped; -p cmd 94
passed; fmt and clippy clean on touched crates. The SQL SET path is not
yet covered by a test.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

* fix(query): address review findings on factorized join aggregation

Address the blind review of PR 9546:

- Admission no longer keys on table/column names: the matcher accepts
  any inner equi-join of two single-table inputs grouped by (left key,
  right group column) with one AVG/SUM over a product of two Float64
  payload columns, either operand order. Renamed tables rewrite;
  qualified names work.
- Operand/group/key columns resolve through intermediate projections
  and must be exact pass-throughs; a projection that computes or
  renames them keeps the baseline plan (previously the rewrite read
  the raw column and silently dropped the computation).
- The rule now fires behind the distributed planner: scan detection
  recurses through the recovering projection, MergeScan extension,
  filters, and subquery aliases. Verified by an engine-level test
  built with the dist planner enabled.
- Payload columns must be Float64; Int64/Decimal inputs keep the
  baseline plan instead of producing mixed-type expressions.
- Session SET experimental_enable_factorized_join_agg = false now
  overrides a server-level true; an unset session inherits the server
  default (tracked via an explicit set flag).
- Renamed rule/module to factorized_join_agg, dropped unused COUNT
  partial aggregates and stale docs, restored the QueryOptions doc.
- Tests: 8 engine-level cases covering renamed tables, result parity
  within 1e-9 with NULL/valid=0 semantics, computed-alias rejection,
  Int64 rejection, near-miss shapes, opt-in default, dist-planner
  firing, and SET override propagation.

Verified: cargo nextest -p query 822 passed / 2 skipped; -p cmd 94
passed; fmt clean; clippy clean on touched code.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

* fix(query): projection operand scope and atomic session setting

Address the post-fix review of PR 9546:

- Product operands extracted from a projection expression reference the
  projection INPUT, so they are no longer re-resolved through the
  projection's output schema; only aggregate-argument columns resolve
  through it, and the unqualified name-only fallback is removed — a
  missing qualified column never silently matches an unrelated
  same-named column. Regression: a projected product with same-named
  columns on opposite sides rewrites with the correct payload columns;
  the projected-product positive shape is now admitted.
- The session setting is one ArcSwap<Option<bool>> (None = unset,
  inherit server default; Some(v) = explicit override). Clone loads a
  single atomic snapshot; the previous value/flag pair could clone a
  state that never existed under a concurrent first SET. Clone
  preservation tests cover unset, explicit false, explicit true.
- Tests: computed-payload rejection keeps the grouping columns
  unchanged so payload validation is the decisive condition; added SUM
  rewrite parity and reversed-operand AVG parity.

Verified: cargo nextest -p query 824 passed / 2 skipped; -p session 17
passed; fmt clean; clippy clean on touched code.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

* test(query): sqlness case for the factorized join aggregation switch

Add a standalone sqlness case exercising the experimental rewrite end to
end through the MySQL protocol on one connection: default off, SET
experimental_enable_factorized_join_agg = true enabling it (EXPLAIN shows
the partial count/sum aggregates joined with the CASE reconstruction),
AVG/SUM result parity including the NULL (valid=0) group, a non-matching
shape left alone, and SET false turning the rewrite back off.

The case must run entirely on the MySQL protocol: session-level SET only
propagates within the same connection, and sqlness sends unannotated
statements over gRPC with a fresh query context. Verified with
cargo sqlness bare -t factorized_join_agg (passes twice in a row on a
rebuilt greptime binary); query 824 passed / 2 skipped; session 17
passed.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

* fix(query): preserve factorized aggregate schema and count semantics

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

* test(query): refresh factorized join agg sqlness expectation for MergeScan pushdown

Upstream #10221 pushes the column projection through MergeScan, so both the
baseline and the rewritten plans now show the projection inside the remote
input instead of above it.

Regenerated with `cargo sqlness bare -t factorized_join_agg`. All 52 changed
lines are Projection/ProjectionExec/MergeScan reordering; result rows, group
counts, and the partial aggregate shape are unchanged, and both the standalone
and distributed environments pass.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

* fix(query): make partial aliases collision-free and refresh CI expectations

Address the post-ready review of PR 9546:

- The four partial-aggregate aliases are now collision-free against every
  field name visible to the rewritten aggregates: `join.left.schema()`,
  `join.right.schema()` and `agg.input.schema()` (the last one includes the
  optional projection above the join). A real column literally named
  `partial_nv_1` used to land next to the qualified grouping key of the same
  bare name in a partial aggregate's output schema, which DFSchema rejects as
  ambiguous. `aliases_do_not_collide_with_column_names` reproduces that shape
  (left join/group key `partial_nv_1`, right group column `partial_nw_3`) and
  asserts both switches plan and produce identical output.
- Both EXPLAIN statements in the new sqlness case now carry
  `-- SQLNESS REPLACE (peers.*) REDACTED`, so the expected output no longer
  embeds allocation-dependent node IDs; the case passed standalone but failed
  in the full suite because of them.
- Regenerated `common/tql-explain-analyze/explain.result`: registering the rule
  adds one `logical_plan after factorized_join_agg_rewrite` row per EXPLAIN
  statement (all `SAME TEXT AS ABOVE`, since the rule leaves those plans
  unchanged).
- `tests-integration/tests/http.rs`: the expected config-API TOML now includes
  `experimental_enable_factorized_join_agg = false` right after
  `allow_query_fallback`, matching the field order in `QueryOptions`.

Verified on this head: `cargo nextest -p query factorized_join_agg` 13 passed;
sqlness `factorized_join_agg` and `tql-explain-analyze` pass in standalone and
distributed; `integration_http_file_test::test_config_api` passes; `cargo fmt`
clean; clippy `-p query -p tests-integration --all-targets -- -D warnings`
clean.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>

---------

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
2026-11-23 07:27:14 +00:00

2.5 KiB
Raw Permalink Blame History

Query options

Query options adjust selected behavior for a connection or request; they are not server-wide settings or resource-pool controls.

Canonical option SQL aliases Values
query.parallelism query_parallelism, query.parallelism Integer 1–1024; server default 0 means automatic CPU-based parallelism. This is not a resource-pool limit.
query.allow_query_fallback query_fallback, allow_query_fallback, query.allow_query_fallback (legacy ALLOW_QUERY_FALLBACK syntax / query_fallback hint also work) true or false
query.experimental_enable_factorized_join_agg experimental_enable_factorized_join_agg, query.experimental_enable_factorized_join_agg true or false; experimental opt-in for shape-based AVG/SUM join aggregation. Server default false; unset inherits it.
query.enable_remote_dynamic_filter_pushdown canonical name true or false
datafusion.optimizer.* canonical name Keys, types, defaults, and validation come from the linked DataFusion version (for example, numeric max_passes and Boolean filter_null_join_keys).

Use SET query_parallelism = 4 or SET query.parallelism TO 4; SHOW VARIABLES query.parallelism works in MySQL and PostgreSQL, which also accepts SHOW query.parallelism. SHOW VARIABLES <option> reports the effective value. Unspecified options inherit engine settings; defaults are automatic parallelism, fallback false, and remote dynamic-filter pushdown true. Invalid values and unsupported names are errors; unknown third-party MySQL/PostgreSQL initialization settings retain existing tolerance.

HTTP X-Greptime-Hints (for example, query.parallelism=4) and gRPC x-greptime-hints request metadata set request options; gRPC hints are not a protobuf Hints field. The Rust Flight client offers Database::sql_with_hint and flight_request().with_hints. Hints override session SET, including within a multi-statement HTTP request. SQL SET lasts for its connection only; SET LOCAL transaction-scoped restoration is not implemented.

query.enable_remote_dynamic_filter_pushdown controls propagation across frontend-to-datanode remote queries; it is distinct from DataFusion's native datafusion.optimizer.enable_dynamic_filter_pushdown.

Internal flow/query-reserved keys are not public query options. HTTP response timeout x-greptime-timeout defaults to 0 (no deadline); this is a response deadline, not a per-statement or stream/body-processing limit.