Files
greptimedb/config/flownode.example.toml
T
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

202 lines
7.2 KiB
TOML

## The flownode identifier and should be unique in the cluster.
## @toml2docs:none-default
node_id = 14
## flow engine options.
[flow]
[flow.batching_mode]
## The default batching engine query timeout is 10 minutes.
#+query_timeout="600s"
## will output a warn log for any query that runs for more that this threshold
#+slow_query_threshold="60s"
## The minimum duration between two queries execution by batching mode task
#+experimental_min_refresh_duration="5s"
## The gRPC connection timeout
#+grpc_conn_timeout="5s"
## The gRPC max retry number
#+experimental_grpc_max_retries=3
## Flow wait for available frontend timeout,
## if failed to find available frontend after frontend_scan_timeout elapsed, return error
## which prevent flownode from starting
#+experimental_frontend_scan_timeout="30s"
## Maximum number of filters allowed in a single query
#+experimental_max_filter_num_per_query=20
## Time window merge distance
#+experimental_time_window_merge_threshold=3
## Whether to enable experimental flow incremental source reads.
## When disabled, batching flows always execute full-snapshot queries.
## Can be overridden per flow with WITH (experimental_enable_incremental_read = 'true').
#+experimental_enable_incremental_read=false
## Read preference of the Frontend client.
#+read_preference="Leader"
[flow.batching_mode.frontend_tls]
## Whether to enable TLS for client.
#+enabled=false
## Server Certificate file path.
## @toml2docs:none-default
#+server_ca_cert_path=""
## Client Certificate file path.
## @toml2docs:none-default
#+client_cert_path=""
## Client Private key file path.
## @toml2docs:none-default
#+client_key_path=""
## The gRPC server options.
[grpc]
## The address to bind the gRPC server. Defaults to `127.0.0.1:3004`; this example sets it to `127.0.0.1:6800`.
## @toml2docs:none-default="127.0.0.1:3004"
bind_addr = "127.0.0.1:6800"
## The address advertised to the metasrv, and used for connections from outside the host.
## If left empty or unset, the server will automatically use the IP address of the first network interface
## on the host, with the same port number as the one specified in `grpc.bind_addr`.
## @toml2docs:none-default
server_addr = "127.0.0.1:6800"
## The number of server worker threads. Defaults to 8; this example sets it to 2.
## @toml2docs:none-default="8"
runtime_size = 2
## The maximum receive message size for gRPC server.
max_recv_message_size = "512MB"
## The maximum send message size for gRPC server.
max_send_message_size = "512MB"
## The HTTP server options.
[http]
## The address to bind the HTTP server.
addr = "127.0.0.1:4000"
## HTTP request timeout. Set to 0 to disable timeout.
timeout = "0s"
## HTTP request body limit.
## The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`.
## Set to 0 to disable limit.
body_limit = "64MB"
## The metasrv client options.
[meta_client]
## The addresses of the metasrv.
metasrv_addrs = ["127.0.0.1:3002"]
## Operation timeout.
timeout = "3s"
## DDL timeout.
ddl_timeout = "10s"
## Connect server timeout.
connect_timeout = "1s"
## `TCP_NODELAY` option for accepted connections.
tcp_nodelay = true
## The configuration about the cache of the metadata.
metadata_cache_max_capacity = 100000
## TTL of the metadata cache.
metadata_cache_ttl = "10m"
# TTI of the metadata cache.
metadata_cache_tti = "5m"
## The logging options.
[logging]
## The directory to store the log files. If set to empty, logs will not be written to files.
dir = "./greptimedb_data/logs"
## The log level. Can be `info`/`debug`/`warn`/`error`.
## @toml2docs:none-default
level = "info"
## Enable OTLP tracing.
enable_otlp_tracing = false
## The OTLP tracing endpoint.
otlp_endpoint = "http://localhost:4318/v1/traces"
## Whether to append logs to stdout.
append_stdout = true
## Whether to write logs to files in `dir`.
enable_file_logging = true
## The log format. Can be `text`/`json`.
log_format = "text"
## The maximum amount of log files.
max_log_files = 720
## The maximum total size of managed log files in `dir`.
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
## Requires symbolic links in the log directory; initialization fails if they cannot be created.
## On Windows, enable Developer Mode or leave this at `0B`.
max_log_dir_size = "0B"
## The OTLP tracing export protocol. Can be `grpc`/`http`.
otlp_export_protocol = "http"
## Additional OTLP headers, only valid when using OTLP http
[logging.otlp_headers]
## @toml2docs:none-default
#Authorization = "Bearer my-token"
## @toml2docs:none-default
#Database = "My database"
## The percentage of tracing will be sampled and exported.
## Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.
## ratio > 1 are treated as 1. Fractions < 0 are treated as 0
[logging.tracing_sample_ratio]
default_ratio = 1.0
## The tracing options. Only effect when compiled with `tokio-console` feature.
#+ [tracing]
## The tokio console address.
## @toml2docs:none-default
#+ tokio_console_addr = "127.0.0.1"
[query]
## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
experimental_enable_factorized_join_agg = false
## Parallelism of the query engine for query sent by flownode.
## Default to 1, so it won't use too much cpu or memory
parallelism = 1
## Memory pool size for query execution operators (aggregation, sorting, join).
## Supports absolute size (e.g., "1GB", "2GB") or percentage of system memory (e.g., "20%").
## Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
## When this limit is reached, queries will fail with ResourceExhausted error.
## NOTE: This does NOT limit memory used by table scans.
## @toml2docs:none-default="0"
memory_pool_size = "50%"
## Experimental memory pool allocation policy:
## - "greedy" (default): first-come-first-served allocation; preserves current behavior.
## - "fair": divides available memory among spillable operators and may spill earlier.
## Only effective when `memory_pool_size` is bounded (>0).
#+ experimental_memory_pool_policy = "greedy"
# --- Experimental: DataFusion spill-to-disk controls ---
## Spill mode:
## - "default": preserve DataFusion built-in OS temp directory (default).
## - "custom": explicitly configure spill path, quota, and compression.
## - "disabled": explicitly disable disk spilling.
## Set this to "custom" before using the path/quota/compression keys below.
#+ experimental_spill_mode = "default"
## Spill directory path. Ignored unless mode is "custom".
## @toml2docs:none-default
#+ experimental_spill_path = "/path/to/spill"
## Maximum total size of spill directory (default: "1GiB").
## Ignored unless mode is "custom".
#+ experimental_spill_max_temp_directory_size = "1GiB"
## Compression for spilled data files: "uncompressed" (default), "lz4_frame", "zstd".
## Ignored unless mode is "custom".
#+ experimental_spill_compression = "uncompressed"
# --- End spill-to-disk ---
## The memory options.
[memory]
## Whether to enable heap profiling activation during startup.
## When enabled, heap profiling will be activated if the `MALLOC_CONF` environment variable
## is set to "prof:true,prof_active:false". The official image adds this env variable.
## Default is true.
enable_heap_profiling = true