* 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>
* test: add repeatable metric snapshot S3 benchmark
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test: use only existing CI S3 permissions in the metric snapshot benchmark
The CI S3 user is not allowed GetBucketLocation or ListBucketMultipartUploads,
so the bucket probe and the prefix cleanup failed with AccessDenied. Use only
list, put, get and delete under the run prefix, as the object store WAL
benchmark does, and probe S3 before allocating the EC2 runner.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test: scope metric snapshot inventory to the current round
The full round's S3 inventory listed the whole run prefix, so it also counted
the smoke snapshot. List only the round's snapshot prefix while cleanup still
covers the run, and assert that the teardown's S3 cleanup step runs always()
with the validated run prefix.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* docs: record the AWS validation run of the metric snapshot benchmark
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
---------
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* feat: return matching scores from jev
Replace the experimental three-argument Boolean function with jev(text, prompt) returning a Float64 probability in [0, 1]. Move threshold comparisons into SQL and update tests and migration examples.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat: add Jev choice and score functions
Share asynchronous execution across Noul, Choice, and Score. Validate JSON criteria before requests and return typed scalar answers. Add SQL and HTTP mock coverage with usage examples.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor: use generic AI SQL function names
Expose ai_match, ai_choose, and ai_score and move their implementation, tests, and usage guide under generic AI names. Document the current unreleased interface without migration history.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix: share constant AI criteria within each batch
Borrow scalar string arguments and lazily parse constant criteria once per batch. Share the parsed allocation across requests while preserving NULL propagation and batch validation before HTTP calls.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat: preserve AI score uncertainty in JSONB results
Return score, confidence, and probabilities in criteria-level order from one evaluation. Validate the distribution and preserve provider precision. Add JSON extraction, uncertainty, and single-request regressions, and document confidence-aware ranking.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* docs: explain reuse of volatile AI evaluations
Document repeated SELECT and WHERE evaluation costs as N + M requests, and show subquery aliases for reusing scalar or structured AI results without additional model calls.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
---------
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat: add experimental Jev SQL filtering
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat: gate Jev filtering behind an opt-in Cargo feature
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* ci: verify Jev registration with default features
Run the existing registry regression without the jev feature in both PR tests and merge-queue coverage, alongside the existing feature-enabled test runs.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* docs: clarify Jev concurrency scope and stabilization work
Document the per-expression/batch concurrency bound and track process-wide limiting, rate-limit backoff, and request budgets and metrics as stabilization prerequisites.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat: enable renamed ai-functions feature by default
Rename the Jev Cargo feature across the command, query, and function crates and enable it in their defaults. Update CI and documentation, retaining an isolated no-default-features registry check and the runtime API opt-in.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* ci: remove extra AI feature-off checks
Use the regular AI-enabled unit and coverage runs for the default feature configuration. Keep feature-off validation available locally and update the usage guide to match.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor: rename AI feature to ai_functions
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
---------
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat/gdump:
### Add Support for Jemalloc Gdump Flag
- **`jemalloc.rs`**: Introduced `PROF_GDUMP` constant and added functions `set_gdump_active` and `is_gdump_active` to manage the gdump flag.
- **`error.rs`**: Added error handling for reading and updating the jemalloc gdump flag with `ReadGdump` and `UpdateGdump` errors.
- **`lib.rs`**: Exposed `is_gdump_active` and `set_gdump_active` functions for non-Windows platforms.
- **`http.rs`**: Added HTTP routes for checking and toggling the jemalloc gdump flag status.
- **`mem_prof.rs`**: Implemented handlers `gdump_toggle_handler` and `gdump_status_handler` for managing gdump flag via HTTP requests.
Signed-off-by: Lei, HUANG <mrsatangel@gmail.com>
* Update docs/how-to/how-to-profile-memory.md
Co-authored-by: shuiyisong <113876041+shuiyisong@users.noreply.github.com>
* fix: typo in docs
Signed-off-by: Lei, HUANG <mrsatangel@gmail.com>
---------
Signed-off-by: Lei, HUANG <mrsatangel@gmail.com>
Co-authored-by: shuiyisong <113876041+shuiyisong@users.noreply.github.com>
* refactor: use DataFusion's UDAF implementation directly
Signed-off-by: luofucong <luofc@foxmail.com>
* remove: delete how-to guide for writing aggregate functions
Signed-off-by: luofucong <luofc@foxmail.com>
* fix ci
Signed-off-by: luofucong <luofc@foxmail.com>
* refactor: port json_encode_path to datafusion udaf
Signed-off-by: Ning Sun <sunning@greptime.com>
---------
Signed-off-by: luofucong <luofc@foxmail.com>
Signed-off-by: Ning Sun <sunning@greptime.com>
Co-authored-by: Ning Sun <sunning@greptime.com>
* feat: enable prof by default
* docs: don't need to build with features
* feat: add common-pprof as optional dep for pprof feature
* build: remove optional
* feat: use dump_text
* feat: UDAF implementation backed by DataFusion.
Directly Transplant DataFusion's UDAF related structs, traits and functions, like `AggregateUDF`, `Accumulator` or `create_udaf` etc.
Implement median UDAF on top of it and used in unit testing.
Refs: #61
* feat: UDAF made generically
Refs: #61
* fix: cargo fmt
* fix: use prelude
* fix: uniform the name
* fix: move maybe commonly used functions together
* fix: make comments more clear
* fix: resolve conversations in CR
* fix: store input types in AccumulatorCreator, and use ScalarVector's iterator
* feat: introducing List value and List datatype
* refactor: use ArcSwap instead of Mutext
* refactor: shorten some namings
* refactor: move median UDAF out of tests
* refactor: rename
* feat: aggregate function registry
* fix: make `Value` satisfy ordering again
* fix: clippy warnings
* doc: add "how to write aggregate function"
* fix: address PR comments
* fix: trying to get rid of unwraps
Co-authored-by: luofucong <luofucong@greptime.com>