mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-10-19 18:32:33 +00:00
chore: backport selected changes for 1.3.0-beta.2 (#9529)
* ci(query-regression): bump RUNNER_IMAGE_EPOCH to 7 (#9395) ci(query-regression): bump RUNNER_IMAGE_EPOCH to 7 for image m-0xihbfzm5xpbxolybo6i Signed-off-by: greptimedb-ci <greptimedb-ci@greptime.com> Co-authored-by: greptimedb-ci <greptimedb-ci@greptime.com> (cherry picked from commit886e02f0dc) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): apply offset to subquery evaluation window (#9364) * fix(promql): apply offset to subquery evaluation window `prom_subquery_expr_to_plan` destructured `SubqueryExpr` without reading `offset`, so `<subquery>[range:step] offset <d>` planned exactly the same window as the un-offset form and silently returned data for the wrong time range. The plain vector/matrix-selector paths already threaded the offset through `selector_to_series_normalize_plan` and `RangeManipulate`. Shift the inner evaluation window back by the offset and pass the offset to the subquery's `RangeManipulate`, which maps the inner samples forward onto the evaluation timeline before bucketing them into ranges. This matches Prometheus, whose `evaluator.subqueryTimeRange` evaluates the inner expression over `(start - offset - range, end - offset]` and whose `evalSubquery` then hands the samples to the outer range-vector function as a `MatrixSelector` that still carries the subquery offset. An offset on the inner selector composes additively, as `subqueryTimes` documents. `RangeManipulate`'s protobuf message has no offset field and recovers it on decode from an immediately underlying `SeriesNormalize`. Since `RangeManipulate` is commutative in `dist_plan` and can be pushed below a `MergeScan`, insert that carrier node so the offset survives distributed planning instead of decoding as zero. Known divergence, unchanged by this commit: Prometheus anchors subquery step points on absolute epoch multiples of the step, while GreptimeDB anchors them on the evaluation start. The two agree whenever the offset is a multiple of the subquery step; the added sqlness cases stay within that range. Closes #9330 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Signed-off-by: Aarav <aaravsjadav@gmail.com> * docs(promql): correct the subquery-offset rationale and pin the histogram shift Follow-up toe132c267, which stated two things inaccurately and left one path untested. No behaviour change beyond a conditional clone. The `SeriesNormalize` carrier was described as existing "so the offset survives distributed planning", implying standalone is unaffected. That is wrong. `local_offset` is read on the substrait decode path (`range_manipulate.rs`, `instant_manipulate.rs`), and GreptimeDB routes PromQL plans through `MergeScan`/substrait in standalone too -- the standalone results `promql/encode_substrait.result` and `precisions.result` both show `MergeScan [is_placeholder=false, remote_input=[...]]`. Deleting the carrier therefore empties subquery-with-offset results in standalone as well, while `count_over_time_subquery_with_offset` keeps passing because it asserts the pre-serialization plan. Say so at the node, so the next reader does not remove it believing standalone is safe. The carrier is also not semantically inert: `SeriesNormalizeStream::normalize` shifts native histogram `start_timestamp` payloads by `offset`. On the subquery path that runs on a computed inner result, on top of any offset the inner selector already applied, and nothing pinned it. It is consistent -- `RangeManipulate` moves the millisecond time index forward by the same `offset_ms` -- so the distance from a histogram's start timestamp to the sample carrying it, which reset/rate detection reads, is invariant. Add `subquery_offset_shifts_histogram_start_and_time_index_together`, which executes the subquery's node stack over native histogram samples for a zero and a non-zero inner offset. It cannot be a sqlness case: native histograms are a struct column with no SQL type or literal (`sql_data_type_to_concrete_data_type` rejects structs) and the sqlness runner speaks only MySQL/Postgres, so such rows only arrive over gRPC/remote-write v2. The divergence note blamed sub-step offsets. Measured, that condition is too narrow: an unaligned evaluation timestamp alone diverges, with no offset at all -- `sum_over_time(fine[20s:10s])` at t=57 samples 47s and 57s here against Prometheus's 40s and 50s. The real condition is that `(start - offset)` is not a multiple of the subquery step, and it is pre-existing: the committed `tql eval (359, 359, '1s') sum_over_time(metric_total[60s:10s])` case is already an instance of it (`359 - 60 + 10 = 309`). Reword the comment and the sqlness header accordingly. A sub-step offset stays accepted: `foo[20s:10s] offset 5s` is valid PromQL, erroring on it would be a regression and would not close the gap anyway. This repo has no PromQL-compatibility documentation page, so there is nowhere else to record it. Also stop cloning the series key columns when there is no offset, and stop the `offset 0s` sqlness comment implying its parser error is evidence about this fix -- the same message comes from a `u32` overflow in `promql-parser`'s shared duration check (`offset 9999999999d`). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Signed-off-by: Aarav <aaravsjadav@gmail.com> * refactor(promql): trim subquery-offset comments and tests per review Shorten the planner and sqlness comments to the semantic contract, build `SeriesDivide` with a clone instead of an `Option`, and drop the normalize.rs histogram test and the `offset 0s` parser case. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Bvab9gpXYjKyLN8Mo6JWWL Signed-off-by: Aarav <aaravsjadav@gmail.com> * fix(promql): record the subquery offset as the range fold offset The subquery's `RangeManipulate` now shifts the payload timestamps by the offset, so `predict_linear` over an offset subquery must recover the evaluation time with that offset instead of 0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Bvab9gpXYjKyLN8Mo6JWWL Signed-off-by: Aarav <aaravsjadav@gmail.com> --------- Signed-off-by: Aarav <aaravsjadav@gmail.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> (cherry picked from commitd6474b961c) Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: retry failed nightly release on following weekdays (#9394) Previously the nightly release was scheduled only on Mondays, so a failed run left users without nightly builds for a whole week. Now the schedule triggers every weekday at 00:00 UTC, but the release only proceeds when the latest published nightly release is older than NIGHTLY_RELEASE_MAX_AGE_DAYS (5) days. The check runs in allocate-runners before any EC2 runner is allocated, and gates all schedule-driven jobs (including the Slack notification, so a skipped nightly is silent). Tag pushes and manual dispatches are unaffected. Signed-off-by: Ning Sun <sunning@greptime.com> (cherry picked from commita7f99b3425) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(client): yield Flight batches and affected rows without waiting for next message (#8918) * fix(client): avoid Flight metrics lookahead stalls Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * refactor(client): extract trailing Flight metrics task Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(client): synchronize trailing metrics and bound cancellation Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commitabf1396c28) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): resolve dotted column names as unqualified columns (#9391) * fix(promql): resolve dotted column names as unqualified columns col(), From<&str>/From<String> for Column and string join keys go through Column::from_qualified_name, which splits `service.name` into relation `service` and column `name` and lowercases unquoted identifiers. Build PromQL column references with Column::from_name / ident() instead. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(servers): resolve remote read matcher labels as unqualified columns Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): cover same-name columns differing in case and without() Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit218000e21b) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): align timestamp(), label_join and label_replace with Prometheus semantics (#9385) * fix(promql): align timestamp() and label_join with Prometheus semantics - timestamp() over a selector reports the selected sample's timestamp, without adding the offset. - timestamp() over any other expression reports the evaluation time instead of the input value. - label_join that overwrites an existing label rejects duplicate label sets at runtime. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): align label_replace and label_join edge cases with Prometheus - label_replace leaves non-matching series unchanged instead of copying the source value into the destination label. - label_replace may overwrite an existing label; duplicate label sets are rejected at runtime like label_join. - label_join with no source labels removes the destination label, and an empty source label name is rejected. - Empty label values produced by these functions are NULL, the same as an absent label. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): join absent labels as empty strings in label_join concat_ws skips NULL arguments together with their separator, so a label that is absent (NULL) dropped its separator, e.g. label_join(label_join(vector(1), "a", "", "missing"), "b", "-", "a", "a") lost b="-". Read every source label as coalesce(label, '') like label_replace does. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): skip rows without a sample in timestamp() timestamp() replaced the input fields with the timestamp before the empty-value filter ran, so a row whose fields were all NULL got a timestamp, e.g. timestamp(-m) for a NULL sample. Filter such rows before the projection, for both the selector and the evaluation-time paths. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit78a7b93292) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(mito2): truncate parquet column index min/max for SST writes (#9420) * fix(mito2): truncate parquet column index min/max for SST writes The SST writer and the bulk part encoder disabled column index truncation together with statistics truncation in #6977. Mito never reads the column index, but every page of a large string or binary column still stored its full min and max values, uncompressed. Truncate the column index to the parquet default of 64 bytes and keep chunk statistics untruncated, since primary key pruning decodes them. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * docs(mito2): note that the column index must not be used to decode primary keys Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commita314ac4281) Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: upgrade EC2 runner action to restore runner registration (#9430) ci: update EC2 runner action for minimum runner version enforcement Signed-off-by: evenyag <realevenyag@gmail.com> (cherry picked from commit0d502e1fc1) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(catalog): skip backend batch_get on full cache hits (#9431) fix(catalog): return cached batch values without an empty backend call Count backend batch_get invocations in regression tests and cover empty input. Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commitacebd6b35b) Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: make query regression non-blocking for scheduled nightly releases (#9434) * ci: make query regression non-blocking for scheduled nightly releases Scheduled nightly releases no longer gate publishing on the query regression release test. The test still runs (validation policy stays 'all' for automatic releases) and uploads its report, but any result - failure, timeout, cancellation, or skip - no longer blocks image publishing or the GitHub release for schedule-triggered runs. Since reusable-workflow caller jobs cannot use continue-on-error, the gate is relaxed at the consumers instead: the if conditions of release-images-to-dockerhub and publish-github-release now also pass when github.event_name == 'schedule' regardless of the query-regression result. All other gates (runner allocation, artifact builds, prepare-release-validation) are unchanged. Tag-push and manual-dispatch releases remain fully blocking unless a skip policy is explicitly chosen via the release_validation input. Signed-off-by: Ning Sun <sunning@greptime.com> * ci: preserve downstream nightly release jobs after regression failures Signed-off-by: evenyag <realevenyag@gmail.com> --------- Signed-off-by: Ning Sun <sunning@greptime.com> Signed-off-by: evenyag <realevenyag@gmail.com> Co-authored-by: evenyag <realevenyag@gmail.com> (cherry picked from commita9ce6e2d01) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: coalesce equal histogram quantile bucket boundaries (#9451) * fix: coalesce equal histogram quantile bucket boundaries Merge numerically equivalent bucket boundaries before monotonicity repair, preserving the allocation-free path for unique boundaries. Share coalescing with histogram_fraction and cover duplicate boundaries with unit and SQL regressions. Fixes #9443 Signed-off-by: evenyag <realevenyag@gmail.com> * fix: keep duplicate infinity buckets in one histogram group Confirm classic histogram completion at a series/timestamp boundary or EOF instead of the first positive infinity. Retain lookahead across batches and reject incomplete optimistic groups so equivalent infinity labels reach numeric coalescing together. Add stream and SQL regressions for duplicate infinity labels, including established bucket counts and EOF. Correct older fixtures to use distinct keys for distinct histogram groups. Signed-off-by: evenyag <realevenyag@gmail.com> * fix: avoid buffering histogram groups with invalid trailing bounds Discover candidate bucket counts at the first group boundary and let optimistic validation fall back to safe mode for malformed bounds. Document discovery and cover trailing invalid and null labels with a focused streaming regression. Signed-off-by: evenyag <realevenyag@gmail.com> --------- Signed-off-by: evenyag <realevenyag@gmail.com> (cherry picked from commit97913b4b3a) Signed-off-by: WenyXu <wenymedia@gmail.com> * test(sqlness): wait for mirrored inserts before flushing streaming flows (#9424) Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commitb78dc4b33b) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: accept a bool value for the CLI --auto-create-schema flag (#9450) * fix: accept a value for the CLI --auto-create-schema flag clap derives ArgAction::SetTrue for bool fields, so --auto-create-schema took no value and could only set true, which is already the default. Users could not turn automatic schema creation off from the CLI, unlike metasrv's auto_create_schema = false. Set action = clap::ArgAction::Set so the flag accepts an explicit true/false value while keeping true as the default. Signed-off-by: fengyue-xve <1759519137@qq.com> * chore: enhance CLI argument for auto_create_schema option Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --------- Signed-off-by: fengyue-xve <1759519137@qq.com> Co-authored-by: dennis zhuang <killme2008@gmail.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> (cherry picked from commit329edc88ec) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(otlp): coerce empty and "-" trace attribute strings to null (#9461) * fix(otlp): coerce empty and "-" trace attribute strings to null Instrumentations fill numeric attributes from absent headers with an empty string (PSR-7 getHeaderLine returns ""). Coercing that into an existing numeric column failed and rejected the whole span. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: trim redundant row from empty-string rewrite test Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commitd640ab8bc5) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(meta-client): bound heartbeat handshake timeout (#9438) * fix(meta-client): bound heartbeat handshake timeout Signed-off-by: Aetherance <inkToAether@gmail.com> * chore(meta-client): fix test license header Signed-off-by: Aetherance <inkToAether@gmail.com> * test(meta-client): prefix heartbeat tests with test Signed-off-by: Aetherance <inkToAether@gmail.com> --------- Signed-off-by: Aetherance <inkToAether@gmail.com> (cherry picked from commit9c69e381ae) Signed-off-by: WenyXu <wenymedia@gmail.com> * docs(config): align example configs and config.md with actual defaults (#9460) * docs(config): align example configs and config.md with actual defaults Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(cmd): compare example defaults inside optional sections Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commite2fd8c5695) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(partition): preserve region mapping during repartition (#9458) Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit90f117b957) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): restore exact filtering for nullable label matchers (#9418) * fix(promql): restore exact filtering for nullable label matchers Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: verify compound filter semantics and last-row selection Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: consolidate label filter regression coverage Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * refactor: separate filter evaluation and timestamp adaptation Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * refactor: inline predicate and timestamp tests Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * refactor: keep direct IN predicates outside simple filters Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix: coerce partition bounds before simple filtering Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: cover partition bound overflow after timestamp widening Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit526dd48bda) Signed-off-by: WenyXu <wenymedia@gmail.com> * chore: update rust toolchain to 1.98.1 (#9429) (cherry picked from commit7f0f592b6b) Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: update dev-builder image tag (#9469) Signed-off-by: greptimedb-ci <greptimedb-ci@greptime.com> Co-authored-by: greptimedb-ci <greptimedb-ci@greptime.com> (cherry picked from commit5affb50bb5) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(metasrv): retry failed heartbeat address updates (#9437) * fix(metasrv): retry failed heartbeat address updates Signed-off-by: WenyXu <wenymedia@gmail.com> * refactor(metasrv): move shared heartbeat helpers to utils Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commit65b9a35692) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(operator): bound FlowMirrorTask pending rows to prevent frontend OOM (#9421) * fix(operator): bound FlowMirrorTask pending rows to prevent frontend OOM When flownode is slow or unreachable, FlowMirrorTask::detach spawns unbounded tasks that each pin a full insert batch for ~10s (gRPC timeout). With continuous writes, in-flight memory grows unboundedly (throughput x 10s x peers), causing frontend-write OOMKill and a million-per-hour ERROR storm. Add a MAX_MIRROR_PENDING_ROWS cap (1M rows) on Inserter: detach fetch_adds the batch's row count before spawning; if the cap is exceeded the reservation is rolled back, the batch is dropped, a DIST_MIRROR_DROPPED_ROW_COUNT metric is bumped, and a warn is logged instead of spawning. On normal completion the reservation is released in both success and error paths. This keeps core writes alive while degrading flow mirror writes to best-effort, which is the intended trade-off: protect the primary insert path at the cost of possible flow aggregation gaps. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix: address review - balanced reservation, gauge race, log rate limit P1: Compute pending_rows() from actual per-peer payloads in self.requests instead of the pre-fanout num_rows field. This fixes under-reservation for same-table multi-region batches and over-release in multi-flownode fanout. Each peer task now releases exactly its own share so reservations and releases balance. P2: Replace load+set gauge publication with add/sub symmetry. reserve_mirror_pending_rows does fetch_add + gauge.add, release does fetch_update + gauge.sub, eliminating the stale-value race. P3: Rate-limit the dropped-batch warning to at most once per 10s via MirrorDropLog (atomic compare_exchange), accumulating batch/row counts between reports. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test: fix race in dual-peer test - wait for gauge release before unlocking The dual-peer test previously only waited for the pending budget to return to its start value before releasing MIRROR_METRIC_TEST_LOCK. But release_mirror_pending_rows moves the budget before the gauge, so a worker's gauge.sub could still be in flight when the next test acquires the lock and records its baseline, polluting the result. Now waits for both pending == start AND gauge == gauge_before. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(operator): preserve instant writes and limit mirror failure logs Reject saturated requests containing instant-TTL rows with the existing retryable write-admission error before mirror or datanode dispatch. Keep normal source-table inserts independent of best-effort mirror drops. Reuse a smaller process-wide event limiter for both dropped batches and failed peer tasks, reporting at most once per 10 seconds with failure count, peer context, and error chain. Cover actual mirror construction, mixed and instant admission, fast/slow peer shares, failed-task release, and log concurrency. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(operator): reject oversized instant mirror batches permanently Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit198d92407c) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): align subqueries to the absolute evaluation grid (#9400) * fix(promql): align subqueries to the absolute evaluation grid Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * docs(promql): streamline subquery comments Remove redundant arithmetic narration and restated test comments. Keep grid, fallback, validation and overflow contracts, and preserve all regression tests and assertions. Regenerate SQLness output only for comment echoes. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit0d2cb1aa7e) Signed-off-by: WenyXu <wenymedia@gmail.com> * build(deps): update opensrv-mysql to fix MariaDB 12.3 USE information_schema hang (#9357) Update opensrv-mysql from f3135e5 to 1f3d88c, which replies a proper EOF packet to COM_FIELD_LIST instead of a malformed OK packet that MariaDB 12.3 misparses and hangs on USE information_schema. Fixes #9158 Signed-off-by: tian1220A <1573612521@qq.com> (cherry picked from commit21536a092b) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): keep vector labels when a computed scalar is on the right (#9478) * fix(promql): keep vector labels when a computed scalar is on the right `metric + time()` or `metric * scalar(other)` planned the join with the scalar side's context, which has no tags, so every series collapsed into one unlabeled series. Use the vector side's context when the right operand is scalar-typed. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): update results for labels kept with a computed scalar on the right v * pi() and v + time() now keep the vector's labels and time index name, as in Prometheus. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): qualify columns of an unnamed operand in vector joins A comparison filter's projection has no table name, so after the join its time index resolved unqualified and was ambiguous when the other operand had the same column. Also keep the empty-metric branch unchanged for scalar left operands. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): cover comparison filters joined with a scalar Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit6da5352c53) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(otlp): convert boolean metric attributes into label values (#9468) Signed-off-by: fengyue-xve <1759519137@qq.com> (cherry picked from commit2ebb03fbf6) Signed-off-by: WenyXu <wenymedia@gmail.com> * perf(catalog): optimize single-table lookups in information_schema.partitions (#9473) * perf(catalog): optimize single-table lookups in information_schema.partitions Signed-off-by: 风月 <1759519137@qq.com> * style: apply rustfmt formatting to partitions tests Signed-off-by: 风月 <1759519137@qq.com> --------- Signed-off-by: 风月 <1759519137@qq.com> (cherry picked from commit4ade13d9b6) Signed-off-by: WenyXu <wenymedia@gmail.com> * test(promql): cover label_replace normalization with distinct series (#9485) The duplicate-label-set rejection must not fire when a label rewrite keeps every series distinct through another label. Normalizing mixed histogram boundary representations (`10.0` -> `10`) while `instance` still differs is the false positive reported in #9444. The check already accounts for it since it became a per-timestamp row count instead of a planning-time rejection, but no fixture covered the positive case. Add one, together with the aggregation variant that produces a genuine duplicate and must still fail. Signed-off-by: fengyue-xve <1759519137@qq.com> (cherry picked from commit764ab8bc1a) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): return no point for zero-interval irate/idelta (#9455) fix(promql): irate/idelta return no point for a zero-ms sample gap Signed-off-by: Niladri Adhikary <niladrix719@gmail.com> (cherry picked from commit0dde3a7b70) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(metasrv): stop parking the heartbeat response on the region supervisor queue (#9474) * fix(meta-srv): stop parking the heartbeat response on the region supervisor queue Signed-off-by: lczllx <2181719471@qq.com> * test(meta-srv): cover the heartbeat response path at the handler level Signed-off-by: lczllx <2181719471@qq.com> --------- Signed-off-by: lczllx <2181719471@qq.com> (cherry picked from commitd1151b0ed6) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): keep metric name for comparison operators (#9332) * fix(promql): keep metric name for comparison operators `collect_metric_names` dropped the response `__name__` for every binary operator except `and` / `or` / `unless`, so comparisons such as `node_load1 > 5` came back without the metric name. Grafana rendered them as `{instance="..."}` and alert templates reading `$labels.__name__` got nothing. Follow Prometheus' `shouldDropMetricName` / `resultMetric`: arithmetic operators drop the name, comparisons keep the left-hand name, except when the comparison returns a bool or is a one-to-one `on(...)` match. A `group_left` / `group_right` modifier does not reduce the labels, so the name is kept there. Both the HTTP PromQL API and the gRPC gateway share `retrieve_metric_name_and_result_type`, so one fix covers both. Signed-off-by: Aumnertic <hznuzc@gmail.com> * docs: document binary_keeps_metric_name Signed-off-by: Aumnertic <hznuzc@gmail.com> * fix(promql): handle on(__name__), scalar lhs and group_right Signed-off-by: Aumnertic <hznuzc@gmail.com> * chore(promql): correct result-side docs and drop unreachable String arm Signed-off-by: Aumnertic <hznuzc@gmail.com> * fix(promql): drop metric name when explicitly ignored Handle ignoring(__name__) for one-to-one comparisons and cover comparison, group_left, group_right and unless behavior. Signed-off-by: Aumnertic <hznuzc@gmail.com> --------- Signed-off-by: Aumnertic <hznuzc@gmail.com> (cherry picked from commitc33a6cfa56) Signed-off-by: WenyXu <wenymedia@gmail.com> * perf(promql): reduce timestamp payload allocations and use narrow cursor scans (#9417) * perf(promql): zero-copy timestamp payload for millisecond zero-offset ranges RangeManipulate rebuilt the timestamp range payload per sample through wide-precision i128 conversion even for millisecond input with zero offset, where the input is already millisecond and nothing changes. That turned a previously zero-copy path into a per-sample loop plus a Vec allocation, regressing range-function queries. Reuse the input timestamp array directly when the time index is already millisecond and the offset is zero. Other units and non-zero offsets keep the wide-precision conversion (required so ns/us data near the native type limits stays correct under large offsets). Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> Signed-off-by: discord9 <discord9@163.com> * perf(promql): vectorize timestamp payload with plain i64 RangeManipulate rebuilt the timestamp range payload per sample through wide-precision i128 conversion, turning a hot path into a scalar loop with a Vec allocation. Realistic timestamps and offsets stay far inside i64, so the wide path is unnecessary. - millisecond + zero offset reuses the input array with zero copy; - other units / offsets shift in one vectorized i64 pass (no i128, no per-sample Option, no overflow branch). Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> Signed-off-by: discord9 <discord9@163.com> * perf(promql): check timestamp payload overflow via arrow try_unary Replace the silent wrapping shift with try_unary + checked_mul/checked_add. checked arithmetic lowers to a per-lane overflow flag so the single pass still vectorizes over the dense i64 buffer; any overflow short-circuits to an error instead of silently wrapping to a wrong timestamp. No i128, no per-sample Option. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> Signed-off-by: discord9 <discord9@163.com> * perf(promql): vectorize cursor scans with i64 fast path RangeManipulate::calculate_range and InstantManipulate::manipulate compared every sample through i128 wide-precision arithmetic. For realistic timestamps and offsets the shifted values stay far inside i64, so the wide path was pure overhead. Split both scans into an i64 fast path (checked arithmetic precomputed once per batch) and an i128 exact fallback. Any input that would overflow i64 falls back to the i128 scan, keeping window membership semantics identical. Verified: 47/47 range_manipulate + instant_manipulate tests, 275/275 promql crate tests, 1612 randomized cases byte-identical to i128 scan. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> Signed-off-by: discord9 <discord9@163.com> * refactor(promql): generalize cursor scans and share endpoint precheck Address review comments on PR #9417: - Generalize scan_ranges/scan_instants over Nanoseconds (i64/i128), eliminating the duplicated scan bodies. - Extract shared narrow_scan precheck used by both RangeManipulate and InstantManipulate, with identical checked endpoint logic. - Trim doc comments to one line; fix factual errors about fallback trigger (2262 for ms/s, not native type limits). Semantics unchanged: same cursor algorithm, same overflow fallback, same i64-vs-i128 selection, same stale/null/tie handling. Verified: 47/47 range_manipulate + instant_manipulate tests, clippy clean. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> Signed-off-by: discord9 <discord9@163.com> * perf(promql): vectorize payload with try_unary and add scan carrier bench Replace the per-sample i128 payload loop with a single arrow try_unary pass: i128 intermediate holds any native timestamp shift, only the final millisecond result must fit i64. This is semantically equivalent to the original i128 implementation (no silent wrap, no per-sample branching). Add cursor_scan_carriers A/B benchmark: i64 fast path vs i128 exact fallback on four workloads. Add five deterministic differential tests pinning scan_ranges::<i64> and scan_ranges::<i128> to be pointwise equivalent on boundary shapes (sub-ms samples, fallback triggers, nanosecond extremes, seeded precision matrix). Bench (N=4096, 15s cadence): - payload wall_time 20x15s: 74.94us -> 48.98us (-35%) - payload wall_time 240x15s: 102.44us - scan i64 fast path: 10.97us vs i128 19.84us (1.81x) Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * perf(promql): restore zero-copy payload for ms+offset=0 and fix comment Restore the zero-copy fast path for millisecond timestamps with zero offset, guarded by the input column's exact data type (Timestamp (Millisecond, None)) rather than self.time_unit. The old time_unit guard would accept a tz-carrying millisecond column and produce a dictionary value type disagreeing with the output schema; the datatype guard is the correct check. Also fix the comment: arrow's try_unary is a fallible kernel that LLVM cannot auto-vectorize; the win over the hand-written loop comes from eliminating the per-sample Option/Vec and branches, not SIMD. Add a regression test with a timezone-carrying millisecond index to prove it falls back to the try_unary path. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * perf(promql): replace try_unary with unary + Cell overflow flag Arrow's try_unary is a fallible kernel that LLVM cannot auto-vectorize. Replace it with the infallible unary kernel: the closure is a plain i64 -> i64 mapping that sets a Cell<bool> on overflow instead of returning Err per sample. The flag is checked once after the loop. This removes the per-lane Result construction and lets LLVM vectorize the shift+truncate sequence. Bench (N=4096, 15s cadence): - window4x15s: 42.12us -> 28.77us (-32%) - window20x15s: 48.98us -> 27.68us (-43%) - window240x15s: 102.44us -> 27.61us (-73%) - regular_sparse: 90.04us -> 29.20us (-68%) All cases now run at ~27-29us regardless of window size; the zero-copy path dominates for ms+offset=0. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * perf(promql): dispatch payload conversion on null_count; drop wall-time bench Null-free batches (dominant PromQL case) take arrow's vectorizable unary kernel with a Cell<bool> overflow flag; nullable batches take try_unary so a NULL slot's arbitrary underlying value cannot raise a false batch-wide overflow error. Add a regression test exercising both paths. Remove bench_range_manipulate_wall_time (all-ms zero-offset cases only exercised the zero-copy path, measuring nothing about the conversion) and its orphaned helpers; restore the cursor-scan bench helpers it shared. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(promql): keep nullable timestamp cursor scans on i128 NULL slots may contain unordered arbitrary values, so the endpoint-only narrow-scan proof cannot bound their interior timestamp arithmetic. Both range and instant scans now attempt i64 only for null-free timestamp arrays and otherwise retain the existing exact i128 path. Add focused interior-NULL regressions through both active entrypoints, checking concrete selections and output against the existing wide scan. The null-free fast path and timestamp payload conversion are unchanged. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> Signed-off-by: discord9 <discord9@163.com> (cherry picked from commitb3c756a7dd) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(metasrv): stop holding the pusher registry lock across mailbox sends (#9445) fix(meta-srv): stop holding the pusher registry lock across mailbox sends Signed-off-by: lczllx <2181719471@qq.com> (cherry picked from commit7605f27608) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(mito): flush memtables containing skip-WAL writes on region close (#9440) * fix(mito): flush unlogged writes when closing regions Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(mito): align skip-WAL naming and metric recovery tests Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commita026b3b280) Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: enhance benchmark workflows with version comparisons and diagnostics (#9383) * ci: update Agent and Traces benchmark runtime Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: use unrestricted benchmark runtimes by default Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: retry benchmark image pulls before generating datasets Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: increase tracesbench defaults to 8 CPU and 32 GiB Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: configure tracesbench query timeout and update runtime Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: update tracesbench runtime and configure import scan workers Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: use shared parallel tracesbench import preparation Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: update tracesbench runtime to preserve Tempo trace requests Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: summarize tracesbench query results and lifecycle Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: show benchmark resource usage and update parallel loader runtime Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(ci): resolve shared summary module in existing test harness Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: select tracesbench engines and GreptimeDB image version Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: update benchmark runtime with parallel Agent preparation Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: select benchmark runtime registry by cloud provider Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: retry long-range benchmark image pulls Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: compare baseline and candidate GreptimeDB benchmarks Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: pin published dual-version benchmark runtime Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: prepare agent benchmark indexes with updated runtime Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: validate agent admission and render traces version comparison Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: use runtime with traces index preparation Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: use consolidated runtime for benchmark version reports Signed-off-by: WenyXu <wenymedia@gmail.com> * test: add license header to benchmark comparison tests Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(ci): read legacy Tempo ingestion metrics in traces summaries Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: require tracesbench query plan artifacts Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: use optimized tracesbench report runtime Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: update tracesbench runtime to merged report validation Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commit6e1a137411) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): accept evaluation times before the Unix epoch (#9480) * fix(promql): accept evaluation times before the Unix epoch Prometheus accepts negative timestamps in query parameters; GreptimeDB rejected them while parsing and would panic converting them in the planner. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: update flow_tql error for a negative TQL end time A negative end now parses and fails the end >= start check instead of the timestamp conversion. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): reject evaluation times outside the millisecond range The signed millisecond conversion cast u128 to i64 unchecked, so a far-past time wrapped into the future. Reuse the checked conversion from label_values and return an error instead. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * chore: drop an unused import Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): round query times to milliseconds like Prometheus Numeric times round the fraction of a second to milliseconds, and pre-epoch times floor sub-millisecond parts, matching Prometheus' parseTime and timestamp.FromTime. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): round the float fraction before converting to nanoseconds Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: skip the overflow case where SystemTime cannot hold it Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commita8e293fd79) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: unify unknown flow option rejection across OSS and enterprise builds (#9319) * fix(operator): unify unknown flow option rejection across OSS and enterprise builds Remove the enterprise-gated passthrough that let unknown flow options through SQL-layer validation. Both OSS and enterprise binaries now reject unknown flow options with a single 1004(InvalidArguments) error at the SQL layer, producing identical sqlness output. The metasrv-side validate_flow_options remains as a defensive check. Signed-off-by: discord9 <discord9@163.com> * fix(flow): use DISTINCT output columns as sink key for streaming flows When a streaming flow's source table has no primary key, sink key inference produced an empty key. For SELECT DISTINCT v, the DISTINCT establishes v as the output key, but the inference only looked at source primary keys. Combined with the zero-valued placeholder timestamp, all output rows shared the same storage identity and were deduplicated into a single row. Use all non-time-index output columns as the sink key when the plan is a DISTINCT and no source primary key was inherited. Signed-off-by: discord9 <discord9@163.com> * fix(flow): preserve extension options and complete DISTINCT sink identity Keep enterprise CREATE FLOW options available to the existing handler and report unknown ordinary options as InvalidArguments with the OSS SQL error text. Infer DISTINCT sink keys from every selected non-time-index output column, including when source key columns survive. Wait for asynchronous mirrors in show_create_flow and exercise 1000 distinct sink rows in the SQL regression. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(flow): align meta unknown option status assertions Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(flow): use valid aliases in DISTINCT sink regression SQL Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(flow): record complete DISTINCT sink SQL results Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <discord9@163.com> Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit178a0021b8) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): return range-vector results for instant queries (#9477) * fix(promql): return range-vector results for instant queries An instant query of a range selector or subquery (e.g. `up[5m]`) returned the internal range arrays, which panicked when the frontend decoded them as dictionaries. Plan such queries as the selected samples with their own timestamps, and reject range-vector expressions in range queries like Prometheus does. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): keep encode_substrait on a valid range query A range query of a range-vector expression now fails like in Prometheus. Wrap the subquery in max_over_time so the case still encodes both RangeManipulate nodes through substrait. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): plan wrapped range-vector roots and reject a zero subquery step TQL EXPLAIN, ANALYZE and AS alias wrap the root in an extension, which the range-vector path did not unwrap. A zero subquery step divided by zero. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): cover wrapped range-vector roots and a zero subquery step Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): default subquery step and reject range vectors in range queries A root subquery without a step uses the one-minute default instead of the query step. The HTTP range query endpoint rejects range-vector expressions even when start equals end. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: cover root subquery default step Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * refactor(promql): align root subqueries with subquery_child_window Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): return millisecond timestamps for range-vector results Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * refactor(promql): keep the time index timezone and name its table in errors Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commitb913be2af7) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(query): stop reporting region scans as hash partitioned (#9491) * fix(query): stop reporting region scans as hash partitioned Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): use current DataFusion plan downcasts Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): match null rendering in join regression Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): refresh union plan for unknown scan partitioning Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): refresh shared plans after distribution rule removal Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): cover semi joins with remote dynamic filtering Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): strengthen partitioned merge scan regressions Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): remove unused merge scan test helpers Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(perf): measure merge scan hash repartition cost Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(query): adapt merge scan deserialization to two-arg constructor Adapt the production and test serializer callers added by #9206 and remove the obsolete partition_cols assertion. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(query): adapt nested merge scan integration constructor Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit32e8467cda) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(table): require complete primary keys for hash partitioning (#9507) Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit28ec3ff5aa) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(deps): bump OpenDAL to 0.59.4 for OSS RRSA credentials (#9520) Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commite6f3ca10a5) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): default a stepless subquery to a one-minute step (#9481) * fix(promql): default a stepless subquery to a one-minute step `x[5m:]` evaluated the inner expression at the query step, which is 1s for instant queries. Prometheus uses the evaluation interval, one minute by default. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): cover the default subquery step Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): cover the default subquery step in a range query Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit845fc0af9c) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): follow IEEE 754 float semantics in comparisons and aggregations (#9479) * fix(promql): follow IEEE 754 float semantics in operators and aggregations - Comparisons: Arrow orders floats totally (NaN == NaN, NaN > +Inf); PromQL comparisons with NaN are false except !=. - min/max: skip NaN unless the whole group is NaN. DataFusion's grouped min/max let NaN replace and be replaced by neighbours, so the result depended on input order. - topk/bottomk rank NaN last. - round() rounds ties up and returns NaN for a zero step, like Prometheus. - sqrt() of a negative number is NaN instead of an error. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): round() without a step rounds to integers The planner passed a zero step for single-argument round(), which now yields NaN like Prometheus; pass 1 instead. Found by the compatibility harness. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): apply the sqrt guard to builtin functions and register min/max for plan decoding sqrt resolves through the session's builtin functions, not the UDF branch. Distributed plans are decoded with the serializer's session, which did not know prom_min/prom_max. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): cover NaN and rounding semantics Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): keep the nested count rewrite for PromQL min/max count(min(x) by (l)) was rewritten by count_nest_aggr only for the builtin min/max names. prom_min/prom_max return NULL for the same groups, so the rewrite stays valid. Update plan snapshots for the IEEE comparison, sqrt, topk and min/max changes. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): register prom_min/prom_max in the function registry Distributed plans split an aggregation into state and merge steps only for functions whose state function exists in FUNCTION_REGISTRY; prom_min and prom_max lived in the promql crate, so min/max stopped being pushed down to datanodes. Move them to common-function and register them before the state functions are derived. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: update sqlness results for PromQL float semantics Plans and column names now show prom_min/prom_max, the NaN guards of comparisons and sqrt, and the NaN sort key of topk. round() results follow Prometheus' formula. Distributed min/max keep the state/merge split. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): keep column names and NULLs in IEEE comparisons and sqrt Rewriting comparisons as `a op b AND NOT (isnan(a) OR isnan(b))` changed TQL output column names and turned NULL operands into true for `!=` and false for the bool forms. Implement comparisons and sqrt as PromQL UDFs that propagate NULL and report the column name of the expression they replace; prom_min/prom_max report min/max column names the same way. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: restore column names in sqlness results for PromQL float semantics Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): share the prom_min/prom_max groups accumulator with tests Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): keep distinct names for prom_min/prom_max Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commitf3a0841f4f) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(query): keep filter fetch when rewriting matches term (#9521) * test: cover matches term limit dropped by constant rewrite Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(query): keep filter fetch when rewriting matches term Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit483d1e49a3) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: adapt release OptionMap iteration to Rust 1.98 Signed-off-by: WenyXu <wenymedia@gmail.com> * build: reduce checkout-specific inputs for cache reuse (#9198) * test(mito2): cover regex inverted index pruning Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * build: keep build inputs checkout-relative for cross-worktree cache reuse Two small changes so compilations are byte-identical across worktrees of the same commit and can share a build cache (mbx, sccache): - src/common/version/build.rs: derive the workspace root relative to CARGO_MANIFEST_DIR instead of the CARGO_WORKSPACE_DIR injected by .cargo/config.toml (an absolute path). The env var remains as an explicit override for the submodule case; the [env] injection in .cargo/config.toml is removed so the relative derivation is used by default. - Replace three env!("CARGO_MANIFEST_DIR") uses in test/bench code (servers prom_decode bench + decode test, common-meta test_util) with a runtime std::env::var lookup, so the compiled artifact no longer embeds the checkout path. No behavior change: same files are read, same version info emitted. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * build: address cross-worktree cache review feedback Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commitf50f42140a) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(mito): preserve version ordering in bulk merges and flushes (#9517) * fix(mito): preserve delete barriers in flat last-non-null dedup Signed-off-by: evenyag <realevenyag@gmail.com> * fix(mito): respect sequence ranges in bulk merges and flushes Signed-off-by: evenyag <realevenyag@gmail.com> * perf(mito): avoid merge selection on the bulk write path Signed-off-by: evenyag <realevenyag@gmail.com> --------- Signed-off-by: evenyag <realevenyag@gmail.com> (cherry picked from commit674ba72669) Signed-off-by: WenyXu <wenymedia@gmail.com> * ci: benchmark the object store WAL against S3 from an EC2 runner (#9536) * ci: benchmark the object store WAL against S3 from an EC2 runner Add a workflow_dispatch workflow that loads the o11ybench agent observability dataset into a fresh GreptimeDB container per cell and compares three WAL configurations that differ only in [wal]: Raft Engine with sync_write on the instance store, and the object store WAL in durable and enqueued mode, with the data files on S3 in the runner's region for all three. Rounds alternate the configuration order. A summary reports rows per second, D/R and E/R as the geometric mean over rounds, append acknowledgement p50 and p99, and the object store WAL counters. A smoke mode runs the same chain on ubuntu-latest against the MinIO fixture. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: scrape WAL metrics on failed loads and keep logic out of the benchmark YAML Scrape the object store WAL metrics before stopping a cell's server whether the load succeeded or failed, so failed cells keep their stall, poison and create failure counters. Build the summary from the plan so that cells which never ran are listed and leave their ratios undefined. Move budget, region, runtime image, manifest and credential scan logic from the workflow into the helper scripts, and drive the cell lifecycle in the tests through fake docker and curl binaries. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: drop redundant required flags from benchmark inputs Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: fail a benchmark cell whose metrics scrape fails and zero untouched WAL counters A load that succeeds without its metrics scrape now fails the cell with exit code 4 and records metrics_scraped in cell.json. The summary reports an event counter that never registered as zero when the cell is an object store WAL cell whose scrape succeeded and created objects, and as unknown otherwise. Planned cells that never ran are read through the same path as recorded ones. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: register the S3 benchmark workflow for dispatch from its branch A workflow_dispatch workflow can only be dispatched once GitHub has registered it, which happens on the default branch or when one of its triggers fires. A push trigger limited to this branch registers it; validate runs only for workflow_dispatch, so a push run skips every job. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: delete the benchmark S3 prefix one object at a time boto3 now sends a CRC checksum instead of Content-MD5 with DeleteObjects, which the MinIO fixture of the smoke run rejects. DeleteObject needs neither and the prefix of one run holds at most a few thousand objects. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: default the S3 benchmark to c6id.2xlarge c7id is not offered in the runner region ap-southeast-1, where DescribeInstanceTypes rejects it. c6id is the compute optimized x86 family with a local NVMe instance store that the region offers, with the same 8 vCPU and 16 GiB at 2xlarge. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: drop the registration trigger of the S3 benchmark workflow The workflow is registered now, so dispatches no longer need a push trigger on its branch. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: fail an S3 benchmark run on EC2 without a local instance store Without an instance store the Raft Engine WAL of the R cells silently stayed on the root EBS volume, so the run measured a different baseline. Only a smoke run may keep it on the root volume now. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * ci: let the instance store check fail its workflow step The step piped wal-disk into tee without pipefail, so a rejected host still passed. wal-disk now writes its record itself and the step runs it alone. Signed-off-by: jeremyhi <fengjiachun@gmail.com> --------- Signed-off-by: jeremyhi <fengjiachun@gmail.com> (cherry picked from commitc1a0ca9595) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(mito2): ignore missing inverted indexes in old SSTs (#9545) Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commit287ced2de2) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: prevent stale leader metadata after concurrent writes (#9549) fix: fence leader cache fills around store mutations Signed-off-by: jeremyhi <fengjiachun@gmail.com> (cherry picked from commit394562aa9e) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): stop fabricating histogram fold hash partitioning (#9509) * fix(promql): stop fabricating histogram fold hash partitioning Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(promql): cover histogram fraction binary join missing rows Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(promql): normalize dictionary labels in histogram regression Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test: cover histogram joins on logical metric tables Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test: specify insert columns for logical metric fixture Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test: use supported histogram child replacement API Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(promql): keep histogram fold fixtures truthful Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit2039f508fc) Signed-off-by: WenyXu <wenymedia@gmail.com> * feat(client): support region request reuse and route refresh hints (#9540) * feat(client): support shared region requests without deep cloning Signed-off-by: WenyXu <wenymedia@gmail.com> * feat: propagate route refresh retry hints Signed-off-by: WenyXu <wenymedia@gmail.com> * style: preserve local error variant imports in retry hints Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(mito2): distinguish staging rejection from write backpressure Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(meta): preserve legacy retry hints in instruction replies Signed-off-by: WenyXu <wenymedia@gmail.com> * test(client): inline retry hint compatibility cases Signed-off-by: WenyXu <wenymedia@gmail.com> * test(datanode): align batch-open retry hint assertion Signed-off-by: WenyXu <wenymedia@gmail.com> * style: use imported types in region request tests Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commit684c8ff291) Signed-off-by: WenyXu <wenymedia@gmail.com> * refactor(operator): centralize write partitioning and dispatch (#9541) * refactor(operator): centralize write partitioning and dispatch Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(operator): preserve write dispatch behavior during refactor Signed-off-by: WenyXu <wenymedia@gmail.com> * style(operator): import write dispatch error paths Signed-off-by: WenyXu <wenymedia@gmail.com> * style(operator): align dispatch imports and test utilities Signed-off-by: WenyXu <wenymedia@gmail.com> * style(operator): use imported types in partition tests Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commita2d28e6060) Signed-off-by: WenyXu <wenymedia@gmail.com> * feat(operator): retry failed writes with refreshed partitions (#9542) * feat(operator): retry failed writes with refreshed partitions Signed-off-by: WenyXu <wenymedia@gmail.com> * style(operator): simplify retry test type references Signed-off-by: WenyXu <wenymedia@gmail.com> * refactor(operator): clarify write request rebuilding names Signed-off-by: WenyXu <wenymedia@gmail.com> * refactor(operator): encapsulate write retry attempts Signed-off-by: WenyXu <wenymedia@gmail.com> * style(operator): group inserter configuration methods Signed-off-by: WenyXu <wenymedia@gmail.com> * refactor(operator): share routed peers and separate retry decisions Signed-off-by: WenyXu <wenymedia@gmail.com> * refactor(operator): avoid temporary write routing allocations Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commitd86741d0ad) Signed-off-by: WenyXu <wenymedia@gmail.com> * feat(frontend): retry transient distributed write failures (#9543) * refactor(operator): route shared requests through NodeManager Remove the concrete NodeClients requester API and use the existing node manager for owned and shared requests. Preserve the original write hint while the legacy error adapter remains in place. Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(meta): preserve retry policy through error hints Propagate client errors through External and let DDL read retry hints while preserving cleanup and terminal-child policies. Region transport failures retain the legacy Retryable classification, which now also participates in bounded write retries. Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(operator): restore sparse partition tags when rebuilding writes Decode retained primary keys when refreshed partition expressions need different tags. Keep the partitioner and multi-region sparse write regression tests with the fix. Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(operator): stop detached write retries when callers cancel Signed-off-by: WenyXu <wenymedia@gmail.com> * feat(frontend): configure retries across distributed write paths Wire the shared dispatcher through frontend and logical batching, preserving partition columns and request headers. Keep standalone retries disabled and include configuration, batching, and storage regression coverage. Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commit863eebdecb) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(table): stop claiming tag order for logical metric scans (#9522) * test: cover metric logical scan tag ordering Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(table): only claim projected primary key prefix ordering Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(table): keep physical key ordering for metric projections Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(table): compare unknown partition counts explicitly Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * test(table): model scoped internal TSID scan properties Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit75bc4ce46d) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(promql): stop claiming scalar calculate preserves order (#9523) * test: cover scalar calculate order contract Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * fix(promql): stop claiming scalar calculate preserves order Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> * docs(test): describe scalar ordering regression as pre-fix behavior Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --------- Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit0e40281262) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: align fulltext bloom tokens with matches_term and use them for LIKE (#9470) * fix: align fulltext bloom tokens with matches_term and use them for LIKE The bloom fulltext index stored tokens that did not follow matches_term's word boundaries (`_`, ASCII next to Han, Han substrings), so pruning dropped rows matches_term accepts. Tokens and query probes now share the character classes of matches_term, Han runs are indexed as bigrams, and LIKE patterns use the same probes. The bloom blob is written under a new key; blobs from older versions are no longer probed. Tantivy no longer serves matches_term. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * chore: drop unused lazy_static from index and avoid typo-flagged test tokens Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * docs: link like_probes to tokenize instead of the downstream ScriptTokenizer Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * refactor: name probe extraction with verbs and document CharClass Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * feat: rebuild legacy fulltext bloom indexes and probe lower(col) The manifest records the fulltext bloom version per column, so ADMIN BUILD_INDEX now rebuilds SSTs whose bloom index predates the current tokens, and ssts_index_meta shows the version. Case-insensitive bloom indexes also store the tokens of the whole lowercased text for rows where it can differ (U+0130, U+212A, sigma), so matches_term(lower(col), ..) and lower(col) LIKE .. use the index. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test: cover legacy bloom index rewrite by compaction in the compat case Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * chore: log outdated fulltext bloom indexes in the consistency check Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * docs: explain the unrecorded fulltext bloom version Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit5c4d9eb4f8) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(query): guard deep expressions during query planning (#9564) * fix(query): avoid speculative clones in constant normalization Signed-off-by: evenyag <realevenyag@gmail.com> * fix(query): reject deeply nested expressions before optimization Signed-off-by: evenyag <realevenyag@gmail.com> --------- Signed-off-by: evenyag <realevenyag@gmail.com> (cherry picked from commit00aa65de7a) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(operator): reuse catalog table resolution for write retries (#9574) * fix(operator): inherit logical table partitions when retrying writes Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(operator): resolve retried writes through catalog manager Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com> (cherry picked from commit36423a95c6) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(query): accept narrowed nullability in MergeScan remote schema check (#9592) On append-mode tables a region reports an exact row count. When it is zero, DataFusion's AggregateStatistics replaces the region-side __min_state/__max_state aggregate with a non-null struct literal, so the remote stream advertises the state column as non-nullable. The MergeScan schema check required equal nullability and failed the query. Accept a remote field that is non-nullable where the expected field is nullable, matching DataFusion's own physical-plan schema invariant. Batches are already rebuilt with the expected schema. Widening is still rejected, and nested field nullability is still compared exactly as part of the data type. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commitef1298ce02) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(table): stop claiming exact null and distinct counts for append scans (#9593) RegionScanExec reported null_count = 0 and distinct_count = total_rows for every column of an append-only table. DataFusion answers count(col) and count(DISTINCT col) from these statistics, so both returned the row count. Keep the exact row count and an exact zero null count for non-nullable columns, so count(*) is still answered from statistics. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commit5cfdc30a69) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix: avoid pinning memtables during series-index reconciliation (#9588) Signed-off-by: evenyag <realevenyag@gmail.com> (cherry picked from commitce66d8d4ac) Signed-off-by: WenyXu <wenymedia@gmail.com> * perf(query): infer safe aggregate input bounds from HAVING (#9582) * perf(query): infer safe aggregate input bounds from HAVING Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> * test(query): refresh explain snapshots for aggregate bound inference Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> * fix(query): avoid reinferring bounds across MergeScan Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> * fix(query): validate aggregate bound column provenance Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> * test(query): retain zero-match groups for nonpositive HAVING thresholds Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> * test(query): assert inferred bounds in remote scan plans Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> --------- Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> (cherry picked from commitaf396e60a3) Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(query): keep state column names unique when splitting aggregates (#9594) * fix(query): keep state column names unique when splitting aggregates Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(query): probe allocated names when renaming colliding state columns Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com> (cherry picked from commitf7a3a7033c) Signed-off-by: WenyXu <wenymedia@gmail.com> * chore: bump version to 1.3.0-beta.2 Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: greptimedb-ci <greptimedb-ci@greptime.com> Signed-off-by: WenyXu <wenymedia@gmail.com> Signed-off-by: Aarav <aaravsjadav@gmail.com> Signed-off-by: Ning Sun <sunning@greptime.com> Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> Signed-off-by: Dennis Zhuang <killme2008@gmail.com> Signed-off-by: evenyag <realevenyag@gmail.com> Signed-off-by: fengyue-xve <1759519137@qq.com> Signed-off-by: Aetherance <inkToAether@gmail.com> Signed-off-by: tian1220A <1573612521@qq.com> Signed-off-by: 风月 <1759519137@qq.com> Signed-off-by: Niladri Adhikary <niladrix719@gmail.com> Signed-off-by: lczllx <2181719471@qq.com> Signed-off-by: Aumnertic <hznuzc@gmail.com> Signed-off-by: discord9 <discord9@163.com> Signed-off-by: jeremyhi <fengjiachun@gmail.com> Signed-off-by: Lei, HUANG <ratuthomm@gmail.com> Co-authored-by: LFC <990479+MichaelScofield@users.noreply.github.com> Co-authored-by: greptimedb-ci <greptimedb-ci@greptime.com> Co-authored-by: DeviousCardi <115358213+DeviousCardi@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: Ning Sun <sunng@protonmail.com> Co-authored-by: discord9 <discord9@163.com> Co-authored-by: dennis zhuang <killme2008@gmail.com> Co-authored-by: Yingwen <realevenyag@gmail.com> Co-authored-by: fengyue-xve <1759519137@qq.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Aether <98370028+Aetherance@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: zhaiAohan <1573612521@qq.com> Co-authored-by: Niladri Adhikary <91966855+niladrix719@users.noreply.github.com> Co-authored-by: Dragon Roar <2181719471@qq.com> Co-authored-by: Aum <hznuzc@gmail.com> Co-authored-by: jeremyhi <jiachun_feng@proton.me> Co-authored-by: Lei, HUANG <6406592+v0y4g3r@users.noreply.github.com>
This commit is contained in:
co-authored by
LFC
greptimedb-ci
DeviousCardi
Claude Opus 5
Ning Sun
discord9
dennis zhuang
Yingwen
fengyue-xve
Copilot Autofix powered by AI
Aether
github-actions[bot]
zhaiAohan
Niladri Adhikary
Dragon Roar
Aum
jeremyhi
Lei, HUANG
parent
865986d306
commit
a788cd977a
@@ -14,6 +14,7 @@ async-trait.workspace = true
|
||||
bitvec = "1.0"
|
||||
bytes.workspace = true
|
||||
futures.workspace = true
|
||||
icu_properties.workspace = true
|
||||
lazy_static.workspace = true
|
||||
pin-project.workspace = true
|
||||
regex.workspace = true
|
||||
|
||||
@@ -25,6 +25,7 @@ pub mod readable_size;
|
||||
pub mod regex_pattern;
|
||||
pub mod secrets;
|
||||
pub mod serde;
|
||||
pub mod term_token;
|
||||
|
||||
pub type AffectedRows = usize;
|
||||
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Word boundaries shared by `matches_term` and the fulltext bloom index.
|
||||
//!
|
||||
//! Bloom pruning is only sound if the index splits text exactly where
|
||||
//! `matches_term` sees word boundaries, so both use [`classify_char`], and the
|
||||
//! query side derives its probes with [`extract_term_probes`] and [`extract_like_probes`].
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use icu_properties::props::Script;
|
||||
use icu_properties::{CodePointMapData, CodePointMapDataBorrowed};
|
||||
|
||||
/// Classes of characters that decide where `matches_term` sees a word boundary.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CharClass {
|
||||
/// `[0-9A-Za-z]`.
|
||||
AsciiWord,
|
||||
/// Characters of the Han script, alphanumeric or not.
|
||||
Han,
|
||||
/// Non-ASCII alphanumerics outside the Han script, such as `é` or `д`.
|
||||
UnicodeWord,
|
||||
/// Everything else, including `_`.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Returns the [`CharClass`] of `c`. [`tokenize`] splits text wherever the class
|
||||
/// changes and at every [`CharClass::Other`] character.
|
||||
pub fn classify_char(c: char) -> CharClass {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
CharClass::AsciiWord
|
||||
} else if is_han(c) {
|
||||
CharClass::Han
|
||||
} else if c.is_alphanumeric() {
|
||||
CharClass::UnicodeWord
|
||||
} else {
|
||||
CharClass::Other
|
||||
}
|
||||
}
|
||||
|
||||
static HAN_SCRIPT_DATA: CodePointMapDataBorrowed<'static, Script> =
|
||||
CodePointMapData::<Script>::new();
|
||||
|
||||
fn is_han(c: char) -> bool {
|
||||
HAN_SCRIPT_DATA.get(c) == Script::Han
|
||||
}
|
||||
|
||||
/// Returns whether lowercasing `text` as a whole can produce tokens that lowercasing
|
||||
/// each token of `text` doesn't, which `matches_term(lower(col), ..)` and
|
||||
/// `lower(col) LIKE ..` rely on. Every other character lowercases to one character
|
||||
/// of the same class, but U+0130 and U+212A change length or class, and `Σ`
|
||||
/// lowercases depending on the characters after it.
|
||||
pub fn has_irregular_lowercase(text: &str) -> bool {
|
||||
!text.is_ascii() && text.contains(['\u{130}', '\u{212A}', 'Σ'])
|
||||
}
|
||||
|
||||
/// Returns the tokens the fulltext bloom index stores for `text`.
|
||||
///
|
||||
/// A token is a maximal run of ASCII alphanumerics or of non-Han alphanumerics;
|
||||
/// `_` and other symbols only separate tokens. A run of Han characters is
|
||||
/// emitted as its bigrams, or as itself when it has a single character, since
|
||||
/// `matches_term` matches Han terms as plain substrings.
|
||||
pub fn tokenize(text: &str) -> Vec<&str> {
|
||||
let mut tokens = Vec::new();
|
||||
for_each_word_run(text, |class, range| {
|
||||
let run = &text[range];
|
||||
if class == CharClass::Han {
|
||||
push_han_tokens(run, &mut tokens);
|
||||
} else {
|
||||
tokens.push(run);
|
||||
}
|
||||
});
|
||||
tokens
|
||||
}
|
||||
|
||||
/// Calls `f` on every maximal run of word characters of the same class.
|
||||
fn for_each_word_run(text: &str, mut f: impl FnMut(CharClass, Range<usize>)) {
|
||||
if text.is_ascii() {
|
||||
// ASCII text only has `AsciiWord` and `Other` characters, so scan bytes
|
||||
// instead of decoding chars. Most log lines take this path.
|
||||
let mut start = None;
|
||||
for (i, b) in text.bytes().enumerate() {
|
||||
match (b.is_ascii_alphanumeric(), start) {
|
||||
(true, None) => start = Some(i),
|
||||
(false, Some(s)) => {
|
||||
f(CharClass::AsciiWord, s..i);
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(s) = start {
|
||||
f(CharClass::AsciiWord, s..text.len());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let mut run: Option<(CharClass, usize)> = None;
|
||||
for (i, c) in text.char_indices() {
|
||||
let class = classify_char(c);
|
||||
if let Some((run_class, start)) = run {
|
||||
if run_class == class {
|
||||
continue;
|
||||
}
|
||||
f(run_class, start..i);
|
||||
run = None;
|
||||
}
|
||||
if class != CharClass::Other {
|
||||
run = Some((class, i));
|
||||
}
|
||||
}
|
||||
if let Some((run_class, start)) = run {
|
||||
f(run_class, start..text.len());
|
||||
}
|
||||
}
|
||||
|
||||
fn push_han_tokens<'a>(run: &'a str, tokens: &mut Vec<&'a str>) {
|
||||
let mut starts = run.char_indices().map(|(i, _)| i).skip(1);
|
||||
let Some(mut second) = starts.next() else {
|
||||
tokens.push(run);
|
||||
return;
|
||||
};
|
||||
let mut first = 0;
|
||||
for next in starts.chain(std::iter::once(run.len())) {
|
||||
tokens.push(&run[first..next]);
|
||||
first = second;
|
||||
second = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns tokens that every text satisfying `matches_term(text, term)` contains,
|
||||
/// as produced by [`tokenize`].
|
||||
pub fn extract_term_probes(term: &str) -> Vec<String> {
|
||||
// Non-Han terms only match between word boundaries that `tokenize` also
|
||||
// splits at, so their edge runs are whole tokens. Han-containing terms match
|
||||
// as plain substrings and give no such guarantee at their edges.
|
||||
let bounded = !term.chars().any(|c| classify_char(c) == CharClass::Han);
|
||||
let mut probes = Vec::new();
|
||||
push_literal_probes(term, bounded, bounded, &mut probes);
|
||||
probes
|
||||
}
|
||||
|
||||
/// Returns tokens that every text satisfying `text LIKE pattern` contains, as
|
||||
/// produced by [`tokenize`]. `\` escapes the next character, following
|
||||
/// arrow's `like` kernel; a trailing `\` is a literal backslash.
|
||||
pub fn extract_like_probes(pattern: &str) -> Vec<String> {
|
||||
let mut probes = Vec::new();
|
||||
let mut literal = String::new();
|
||||
// The pattern start and end are anchors; a wildcard can stand for word
|
||||
// characters, so a run touching it may be part of a longer token.
|
||||
let mut anchored_left = true;
|
||||
let mut chars = pattern.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'%' | '_' => {
|
||||
push_literal_probes(&literal, anchored_left, false, &mut probes);
|
||||
literal.clear();
|
||||
anchored_left = false;
|
||||
}
|
||||
'\\' => literal.push(chars.next().unwrap_or('\\')),
|
||||
c => literal.push(c),
|
||||
}
|
||||
}
|
||||
push_literal_probes(&literal, anchored_left, true, &mut probes);
|
||||
probes
|
||||
}
|
||||
|
||||
/// Pushes the tokens of `literal` that stay whole tokens wherever `literal`
|
||||
/// occurs. A side is bounded when the character beyond it can't extend the
|
||||
/// adjacent run.
|
||||
fn push_literal_probes(
|
||||
literal: &str,
|
||||
left_bounded: bool,
|
||||
right_bounded: bool,
|
||||
probes: &mut Vec<String>,
|
||||
) {
|
||||
for_each_word_run(literal, |class, range| {
|
||||
let whole =
|
||||
(range.start > 0 || left_bounded) && (range.end < literal.len() || right_bounded);
|
||||
let run = &literal[range];
|
||||
if class == CharClass::Han && run.chars().nth(1).is_some() {
|
||||
// Bigrams inside the run occur in every text containing it.
|
||||
let mut tokens = Vec::new();
|
||||
push_han_tokens(run, &mut tokens);
|
||||
probes.extend(tokens.into_iter().map(str::to_string));
|
||||
} else if whole {
|
||||
probes.push(run.to_string());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn han_detection_uses_script_not_all_cjk() {
|
||||
assert!(is_han('汉'));
|
||||
assert!(is_han('\u{30000}'));
|
||||
assert!(!is_han('あ'));
|
||||
assert!(!is_han('한'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_script_tokenizer() {
|
||||
let cases: [(&str, &[&str]); 7] = [
|
||||
("hello_world __x__", &["hello", "world", "x"]),
|
||||
("trace_id=abc", &["trace", "id", "abc"]),
|
||||
("错误error日志", &["错误", "error", "日志"]),
|
||||
("连接timeout.5次", &["连接", "timeout", "5", "次"]),
|
||||
("用户user-123登录", &["用户", "user", "123", "登录"]),
|
||||
("中国农业银行", &["中国", "国农", "农业", "业银", "银行"]),
|
||||
("Größe日x", &["Gr", "öß", "e", "日", "x"]),
|
||||
];
|
||||
for (text, expected) in cases {
|
||||
assert_eq!(tokenize(text), expected, "text: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_irregular_lowercase_chars() {
|
||||
for c in (0..=0x10FFFF).filter_map(char::from_u32) {
|
||||
let lower = c.to_lowercase().collect::<Vec<_>>();
|
||||
let regular = lower.len() == 1 && classify_char(lower[0]) == classify_char(c);
|
||||
let expect_regular = !matches!(c, '\u{130}' | '\u{212A}');
|
||||
assert_eq!(regular, expect_regular, "U+{:04X}", c as u32);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_term_probes() {
|
||||
let cases: [(&str, &[&str]); 8] = [
|
||||
("world", &["world"]),
|
||||
("hello world", &["hello", "world"]),
|
||||
("/start", &["start"]),
|
||||
("naïve", &["na", "ï", "ve"]),
|
||||
// Han terms match as substrings: only bigrams and runs enclosed by
|
||||
// other characters of the term are safe.
|
||||
("农业", &["农业"]),
|
||||
("农", &[]),
|
||||
("机号1888", &["机号"]),
|
||||
("x错误y日z", &["错误", "y", "日"]),
|
||||
];
|
||||
for (term, expected) in cases {
|
||||
assert_eq!(extract_term_probes(term), expected, "term: {term}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_like_probes() {
|
||||
let cases: [(&str, &[&str]); 11] = [
|
||||
("%timeout%", &[]),
|
||||
("% timeout %", &["timeout"]),
|
||||
("timeout%", &[]),
|
||||
("timeout: %", &["timeout"]),
|
||||
("%: timeout", &["timeout"]),
|
||||
("a_b c", &["c"]),
|
||||
(r"trace\_id=%", &["trace", "id"]),
|
||||
(r"100\% done", &["100", "done"]),
|
||||
(r"x\\y", &["x", "y"]),
|
||||
("%错误error日%", &["错误", "error"]),
|
||||
("%错误 x%", &["错误"]),
|
||||
];
|
||||
for (pattern, expected) in cases {
|
||||
assert_eq!(extract_like_probes(pattern), expected, "pattern: {pattern}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,10 @@ use crate::status_code::StatusCode;
|
||||
pub enum RetryHint {
|
||||
/// The operation may succeed if retried later.
|
||||
Retryable,
|
||||
/// The operation may succeed after refreshing routing and partition information.
|
||||
/// The request may need rebuilding when its partition assignment changes.
|
||||
/// This hint does not imply that a failed operation had no side effects.
|
||||
RetryAfterRouteRefresh,
|
||||
/// Retrying the same operation is not expected to help.
|
||||
///
|
||||
/// This is the default for errors that do not explicitly opt in to retry.
|
||||
@@ -53,16 +57,23 @@ pub enum RetryHint {
|
||||
}
|
||||
|
||||
const RETRY_HINT_RETRYABLE: &str = "retryable";
|
||||
const RETRY_HINT_AFTER_ROUTE_REFRESH: &str = "retry_after_route_refresh";
|
||||
const RETRY_HINT_NON_RETRYABLE: &str = "non_retryable";
|
||||
|
||||
impl RetryHint {
|
||||
/// Returns whether another attempt may succeed, possibly after refreshing routes.
|
||||
pub fn is_retryable(self) -> bool {
|
||||
matches!(self, RetryHint::Retryable)
|
||||
matches!(
|
||||
self,
|
||||
RetryHint::Retryable | RetryHint::RetryAfterRouteRefresh
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the retry hint encoded in gRPC error metadata.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
RetryHint::Retryable => RETRY_HINT_RETRYABLE,
|
||||
RetryHint::RetryAfterRouteRefresh => RETRY_HINT_AFTER_ROUTE_REFRESH,
|
||||
RetryHint::NonRetryable => RETRY_HINT_NON_RETRYABLE,
|
||||
}
|
||||
}
|
||||
@@ -90,6 +101,7 @@ impl FromStr for RetryHint {
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
RETRY_HINT_RETRYABLE => Ok(RetryHint::Retryable),
|
||||
RETRY_HINT_AFTER_ROUTE_REFRESH => Ok(RetryHint::RetryAfterRouteRefresh),
|
||||
RETRY_HINT_NON_RETRYABLE => Ok(RetryHint::NonRetryable),
|
||||
_ => Err(()),
|
||||
}
|
||||
@@ -133,7 +145,9 @@ pub trait ErrorExt: StackError {
|
||||
///
|
||||
/// Implementations should return [`RetryHint::Retryable`] only when retrying the
|
||||
/// same operation may succeed without changing the request. The default is
|
||||
/// [`RetryHint::NonRetryable`] to avoid accidental retry loops.
|
||||
/// [`RetryHint::NonRetryable`] to avoid accidental retry loops. Use
|
||||
/// [`RetryHint::RetryAfterRouteRefresh`] when routing or partition information
|
||||
/// must be refreshed before another attempt.
|
||||
fn retry_hint(&self) -> RetryHint {
|
||||
RetryHint::NonRetryable
|
||||
}
|
||||
|
||||
@@ -164,6 +164,15 @@ fn test_transparent_flag() {
|
||||
#[test]
|
||||
fn test_retry_hint_helpers() {
|
||||
assert!(RetryHint::Retryable.is_retryable());
|
||||
assert!(RetryHint::RetryAfterRouteRefresh.is_retryable());
|
||||
assert_eq!(
|
||||
RetryHint::RetryAfterRouteRefresh.as_str(),
|
||||
"retry_after_route_refresh"
|
||||
);
|
||||
assert_eq!(
|
||||
RetryHint::from_str("retry_after_route_refresh").unwrap(),
|
||||
RetryHint::RetryAfterRouteRefresh
|
||||
);
|
||||
assert!(!RetryHint::NonRetryable.is_retryable());
|
||||
|
||||
assert_eq!(RetryHint::Retryable.as_str(), "retryable");
|
||||
|
||||
@@ -46,7 +46,6 @@ geo-types = { version = "0.7", optional = true }
|
||||
geohash = { version = "0.13", optional = true }
|
||||
h3o = { version = "0.6", optional = true }
|
||||
hyperloglogplus = "0.4"
|
||||
icu_properties.workspace = true
|
||||
jsonb.workspace = true
|
||||
memchr = "2.7"
|
||||
mito-codec.workspace = true
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
pub mod approximate;
|
||||
pub mod count_hash;
|
||||
pub mod extremum;
|
||||
#[cfg(feature = "geo")]
|
||||
pub mod geo;
|
||||
pub mod vector;
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
//! `foo_merge`'s input arg is the same as `foo_state`'s output, and its output is the same as `foo`'s input.
|
||||
//!
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -183,7 +184,13 @@ impl StateMergeHelper {
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut lower_aggr_exprs = vec![];
|
||||
// (unaliased state expression, output column name)
|
||||
let mut lower_states: Vec<(Expr, String)> = vec![];
|
||||
let mut lower_output_names: HashSet<String> = aggr
|
||||
.group_expr
|
||||
.iter()
|
||||
.map(|e| e.qualified_name().1)
|
||||
.collect();
|
||||
let mut upper_aggr_exprs = vec![];
|
||||
|
||||
// group exprs for upper plan should refer to the output group expr as column from lower plan
|
||||
@@ -218,9 +225,28 @@ impl StateMergeHelper {
|
||||
params: aggr_func.params.clone(),
|
||||
};
|
||||
let expr = Expr::AggregateFunction(expr);
|
||||
let lower_state_output_col_name = expr.schema_name().to_string();
|
||||
|
||||
lower_aggr_exprs.push(expr);
|
||||
// The state column is named after the unaliased state expression, which can
|
||||
// repeat even though the original output names are unique: a name-preserving
|
||||
// rewrite such as `count(*)` -> `count(ts) AS count(*)` can make two aggregates
|
||||
// share one state expression, and schema names hide casts, so
|
||||
// `count(CAST(ts AS Int64))` is named `count(t.ts)` too. Identical states are
|
||||
// computed once; a different state with a taken name gets a numeric suffix.
|
||||
let lower_state_output_col_name =
|
||||
if let Some((_, name)) = lower_states.iter().find(|(e, _)| *e == expr) {
|
||||
name.clone()
|
||||
} else {
|
||||
let base = expr.schema_name().to_string();
|
||||
let mut name = base.clone();
|
||||
let mut suffix = 0;
|
||||
while lower_output_names.contains(&name) {
|
||||
suffix += 1;
|
||||
name = format!("{base}_{suffix}");
|
||||
}
|
||||
lower_output_names.insert(name.clone());
|
||||
lower_states.push((expr, name.clone()));
|
||||
name
|
||||
};
|
||||
|
||||
// then create the merge function using the physical expression of the original aggregate function
|
||||
let (name, human_display) = match aggr_expr {
|
||||
@@ -270,7 +296,16 @@ impl StateMergeHelper {
|
||||
}
|
||||
|
||||
let mut lower = aggr.clone();
|
||||
lower.aggr_expr = lower_aggr_exprs;
|
||||
lower.aggr_expr = lower_states
|
||||
.into_iter()
|
||||
.map(|(expr, name)| {
|
||||
if expr.schema_name().to_string() == name {
|
||||
expr
|
||||
} else {
|
||||
expr.alias(name)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let lower_plan = LogicalPlan::Aggregate(lower);
|
||||
|
||||
// update aggregate's output schema
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! PromQL `min` and `max` aggregation operators.
|
||||
//!
|
||||
//! PromQL ignores NaN samples unless every sample of a group is NaN. DataFusion's
|
||||
//! `min`/`max` order NaN differently depending on the code path (its grouped
|
||||
//! accumulator lets NaN replace the current value and be replaced by the next one),
|
||||
//! so the result depends on the order of the input.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::arrow::array::{ArrayRef, AsArray};
|
||||
use datafusion::arrow::datatypes::{DataType, Field, FieldRef, Float64Type};
|
||||
use datafusion::error::Result as DfResult;
|
||||
use datafusion::logical_expr::function::{AccumulatorArgs, StateFieldsArgs};
|
||||
use datafusion::logical_expr::{
|
||||
Accumulator, AggregateUDF, AggregateUDFImpl, GroupsAccumulator, Signature, Volatility,
|
||||
};
|
||||
use datafusion_common::ScalarValue;
|
||||
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::prim_op::PrimitiveGroupsAccumulator;
|
||||
|
||||
use crate::function_registry::FunctionRegistry;
|
||||
|
||||
/// `max` or `min` with PromQL NaN semantics.
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Extremum {
|
||||
name: &'static str,
|
||||
is_max: bool,
|
||||
signature: Signature,
|
||||
}
|
||||
|
||||
impl Extremum {
|
||||
pub const MAX_NAME: &'static str = "prom_max";
|
||||
pub const MIN_NAME: &'static str = "prom_min";
|
||||
|
||||
/// Registers both functions; the registry also derives their state functions, which
|
||||
/// distributed plans need to split the aggregation between datanodes and the frontend.
|
||||
pub fn register(registry: &FunctionRegistry) {
|
||||
registry.register_aggr(Self::max_udaf());
|
||||
registry.register_aggr(Self::min_udaf());
|
||||
}
|
||||
|
||||
pub fn max_udaf() -> AggregateUDF {
|
||||
AggregateUDF::from(Self::new(Self::MAX_NAME, true))
|
||||
}
|
||||
|
||||
pub fn min_udaf() -> AggregateUDF {
|
||||
AggregateUDF::from(Self::new(Self::MIN_NAME, false))
|
||||
}
|
||||
|
||||
fn new(name: &'static str, is_max: bool) -> Self {
|
||||
Self {
|
||||
name,
|
||||
is_max,
|
||||
signature: Signature::exact(vec![DataType::Float64], Volatility::Immutable),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds `value` into `current` like Prometheus' aggregation: a NaN is replaced by any
|
||||
/// sample, and a NaN sample never replaces a number.
|
||||
fn fold(is_max: bool, current: &mut f64, value: f64) {
|
||||
let better = if is_max {
|
||||
value > *current
|
||||
} else {
|
||||
value < *current
|
||||
};
|
||||
if current.is_nan() || better {
|
||||
*current = value;
|
||||
}
|
||||
}
|
||||
|
||||
impl AggregateUDFImpl for Extremum {
|
||||
fn name(&self) -> &str {
|
||||
self.name
|
||||
}
|
||||
|
||||
fn signature(&self) -> &Signature {
|
||||
&self.signature
|
||||
}
|
||||
|
||||
fn return_type(&self, _arg_types: &[DataType]) -> DfResult<DataType> {
|
||||
Ok(DataType::Float64)
|
||||
}
|
||||
|
||||
fn accumulator(&self, _acc_args: AccumulatorArgs) -> DfResult<Box<dyn Accumulator>> {
|
||||
Ok(Box::new(ExtremumAccumulator {
|
||||
is_max: self.is_max,
|
||||
value: None,
|
||||
}))
|
||||
}
|
||||
|
||||
fn state_fields(&self, args: StateFieldsArgs) -> DfResult<Vec<FieldRef>> {
|
||||
Ok(vec![Arc::new(Field::new(
|
||||
format!("{}[{}]", args.name, self.name),
|
||||
DataType::Float64,
|
||||
true,
|
||||
))])
|
||||
}
|
||||
|
||||
fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn create_groups_accumulator(
|
||||
&self,
|
||||
_args: AccumulatorArgs,
|
||||
) -> DfResult<Box<dyn GroupsAccumulator>> {
|
||||
Ok(groups_accumulator(self.is_max))
|
||||
}
|
||||
}
|
||||
|
||||
fn groups_accumulator(is_max: bool) -> Box<dyn GroupsAccumulator> {
|
||||
Box::new(
|
||||
PrimitiveGroupsAccumulator::<Float64Type, _>::new(&DataType::Float64, move |cur, v| {
|
||||
fold(is_max, cur, v)
|
||||
})
|
||||
.with_starting_value(f64::NAN),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ExtremumAccumulator {
|
||||
is_max: bool,
|
||||
value: Option<f64>,
|
||||
}
|
||||
|
||||
impl ExtremumAccumulator {
|
||||
fn update(&mut self, values: &ArrayRef) {
|
||||
for v in values.as_primitive::<Float64Type>().iter().flatten() {
|
||||
match &mut self.value {
|
||||
Some(current) => fold(self.is_max, current, v),
|
||||
None => self.value = Some(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Accumulator for ExtremumAccumulator {
|
||||
fn update_batch(&mut self, values: &[ArrayRef]) -> DfResult<()> {
|
||||
self.update(&values[0]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn merge_batch(&mut self, states: &[ArrayRef]) -> DfResult<()> {
|
||||
self.update(&states[0]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn state(&mut self) -> DfResult<Vec<ScalarValue>> {
|
||||
Ok(vec![ScalarValue::Float64(self.value)])
|
||||
}
|
||||
|
||||
fn evaluate(&mut self) -> DfResult<ScalarValue> {
|
||||
Ok(ScalarValue::Float64(self.value))
|
||||
}
|
||||
|
||||
fn size(&self) -> usize {
|
||||
size_of_val(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use datafusion::arrow::array::Float64Array;
|
||||
use datafusion::logical_expr::EmitTo;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn groups_result(
|
||||
is_max: bool,
|
||||
values: Vec<Option<f64>>,
|
||||
groups: Vec<usize>,
|
||||
) -> Vec<Option<f64>> {
|
||||
let num_groups = groups.iter().max().map_or(0, |g| g + 1);
|
||||
let mut acc = groups_accumulator(is_max);
|
||||
let values: ArrayRef = Arc::new(Float64Array::from(values));
|
||||
acc.update_batch(&[values], &groups, None, num_groups)
|
||||
.unwrap();
|
||||
let out = acc.evaluate(EmitTo::All).unwrap();
|
||||
out.as_primitive::<Float64Type>().iter().collect()
|
||||
}
|
||||
|
||||
fn is_nan(v: Option<f64>) -> bool {
|
||||
v.is_some_and(f64::is_nan)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_is_ignored_unless_the_group_is_all_nan() {
|
||||
// Group 0 has NaN on both sides of a number; group 1 is all NaN; group 2 has only NULL.
|
||||
let values = vec![
|
||||
Some(f64::NAN),
|
||||
Some(3.0),
|
||||
Some(f64::NAN),
|
||||
Some(f64::NAN),
|
||||
None,
|
||||
];
|
||||
let groups = vec![0, 0, 0, 1, 2];
|
||||
for is_max in [true, false] {
|
||||
let out = groups_result(is_max, values.clone(), groups.clone());
|
||||
assert_eq!(out[0], Some(3.0));
|
||||
assert!(is_nan(out[1]));
|
||||
assert_eq!(out[2], None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_does_not_depend_on_input_order() {
|
||||
let forward = vec![Some(1.0), Some(f64::NAN), Some(4.0), Some(2.0)];
|
||||
let mut backward = forward.clone();
|
||||
backward.reverse();
|
||||
assert_eq!(
|
||||
groups_result(true, forward.clone(), vec![0; 4]),
|
||||
vec![Some(4.0)]
|
||||
);
|
||||
assert_eq!(
|
||||
groups_result(true, backward.clone(), vec![0; 4]),
|
||||
vec![Some(4.0)]
|
||||
);
|
||||
assert_eq!(groups_result(false, forward, vec![0; 4]), vec![Some(1.0)]);
|
||||
assert_eq!(groups_result(false, backward, vec![0; 4]), vec![Some(1.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_partial_states_keep_nan_semantics() {
|
||||
let mut partial_nan = ExtremumAccumulator {
|
||||
is_max: true,
|
||||
value: None,
|
||||
};
|
||||
partial_nan.update(&(Arc::new(Float64Array::from(vec![f64::NAN])) as ArrayRef));
|
||||
let mut partial_num = ExtremumAccumulator {
|
||||
is_max: true,
|
||||
value: None,
|
||||
};
|
||||
partial_num.update(&(Arc::new(Float64Array::from(vec![2.0, 5.0])) as ArrayRef));
|
||||
|
||||
let mut merged = ExtremumAccumulator {
|
||||
is_max: true,
|
||||
value: None,
|
||||
};
|
||||
for partial in [&mut partial_nan, &mut partial_num] {
|
||||
let state = partial.state().unwrap()[0].to_array().unwrap();
|
||||
merged.merge_batch(&[state]).unwrap();
|
||||
}
|
||||
assert_eq!(merged.evaluate().unwrap(), ScalarValue::Float64(Some(5.0)));
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ use crate::admin::AdminFunction;
|
||||
use crate::aggrs::aggr_wrapper::StateMergeHelper;
|
||||
use crate::aggrs::approximate::ApproximateFunction;
|
||||
use crate::aggrs::count_hash::CountHash;
|
||||
use crate::aggrs::extremum::Extremum;
|
||||
use crate::aggrs::vector::VectorFunction as VectorAggrFunction;
|
||||
use crate::function::{Function, FunctionRef};
|
||||
use crate::function_factory::ScalarFunctionFactory;
|
||||
@@ -260,6 +261,9 @@ pub static FUNCTION_REGISTRY: LazyLock<Arc<FunctionRegistry>> = LazyLock::new(||
|
||||
// CountHash function
|
||||
CountHash::register(&function_registry);
|
||||
|
||||
// PromQL min/max; registered before the state functions are derived.
|
||||
Extremum::register(&function_registry);
|
||||
|
||||
// state function of supported aggregate functions
|
||||
StateMergeHelper::register(&function_registry);
|
||||
|
||||
|
||||
@@ -15,13 +15,12 @@
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_base::term_token::{CharClass, classify_char};
|
||||
use datafusion_common::arrow::array::{Array, AsArray, BooleanArray, BooleanBuilder};
|
||||
use datafusion_common::arrow::compute;
|
||||
use datafusion_common::arrow::datatypes::DataType;
|
||||
use datafusion_common::{DataFusionError, ScalarValue};
|
||||
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, Signature, Volatility};
|
||||
use icu_properties::props::Script;
|
||||
use icu_properties::{CodePointMapData, CodePointMapDataBorrowed};
|
||||
use memchr::memmem;
|
||||
|
||||
use crate::function::Function;
|
||||
@@ -231,14 +230,6 @@ pub struct MatchesTermFinder {
|
||||
ends_with_other: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum CharClass {
|
||||
AsciiWord,
|
||||
Han,
|
||||
UnicodeWord,
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum TermKind {
|
||||
AsciiLike,
|
||||
@@ -246,25 +237,6 @@ enum TermKind {
|
||||
HanContaining,
|
||||
}
|
||||
|
||||
fn classify_char(c: char) -> CharClass {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
CharClass::AsciiWord
|
||||
} else if is_han(c) {
|
||||
CharClass::Han
|
||||
} else if c.is_alphanumeric() {
|
||||
CharClass::UnicodeWord
|
||||
} else {
|
||||
CharClass::Other
|
||||
}
|
||||
}
|
||||
|
||||
static HAN_SCRIPT_DATA: CodePointMapDataBorrowed<'static, Script> =
|
||||
CodePointMapData::<Script>::new();
|
||||
|
||||
fn is_han(c: char) -> bool {
|
||||
HAN_SCRIPT_DATA.get(c) == Script::Han
|
||||
}
|
||||
|
||||
fn classify_term(term: &str) -> TermKind {
|
||||
let mut has_han = false;
|
||||
let mut has_unicode_word = false;
|
||||
@@ -508,12 +480,4 @@ mod tests {
|
||||
assert!(MatchesTermFinder::new("行账号").find("中国农业银行账号"));
|
||||
assert!(MatchesTermFinder::new("登录").find("登录手机号18888888888的动态key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn han_detection_uses_script_not_all_cjk() {
|
||||
assert!(is_han('汉'));
|
||||
assert!(is_han('\u{30000}'));
|
||||
assert!(!is_han('あ'));
|
||||
assert!(!is_han('한'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,10 @@ pub fn binlit_as_veclit(bytes: &[u8]) -> Result<Cow<'_, [f32]>> {
|
||||
})
|
||||
} else {
|
||||
let v = bytes
|
||||
.chunks_exact(std::mem::size_of::<f32>())
|
||||
.map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap()))
|
||||
.as_chunks::<{ std::mem::size_of::<f32>() }>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|chunk| f32::from_le_bytes(*chunk))
|
||||
.collect::<Vec<f32>>();
|
||||
Ok(Cow::Owned(v))
|
||||
}
|
||||
|
||||
@@ -41,3 +41,12 @@ cargo nextest run -p common-meta
|
||||
```
|
||||
|
||||
Backend-specific coverage may also need `pg_kvbackend` or `mysql_kvbackend`.
|
||||
|
||||
`test_util::etcd_certs_dir` and `test_util::test_certs_dir` resolve fixture
|
||||
certificates using `CARGO_MANIFEST_DIR` at **run time** (`std::env::var`, not `env!`).
|
||||
`cargo nextest run` sets it; direct test-binary execution requires setting the
|
||||
variable to the crate directory. Run this example from the repository root:
|
||||
|
||||
```bash
|
||||
CARGO_MANIFEST_DIR="$PWD/src/common/meta" ./target/debug/deps/<test_binary>
|
||||
```
|
||||
|
||||
@@ -42,7 +42,7 @@ use crate::cache_invalidator::Context;
|
||||
use crate::ddl::DdlContext;
|
||||
use crate::ddl::event::flow::{CREATE_FLOW_EVENT_TYPE, CreateFlowEventIntent, FlowDdlEvent};
|
||||
use crate::ddl::utils::{add_peer_context_if_needed, map_to_procedure_error};
|
||||
use crate::error::{self, Result, UnexpectedSnafu};
|
||||
use crate::error::{self, InvalidFlowOptionSnafu, Result, UnexpectedSnafu};
|
||||
use crate::instruction::{CacheIdent, CreateFlow, DropFlow};
|
||||
use crate::key::flow::flow_info::{FlowInfoValue, FlowScheduleConfig, FlowStatus};
|
||||
use crate::key::flow::flow_route::FlowRouteValue;
|
||||
@@ -558,9 +558,9 @@ pub fn validate_flow_options(flow_task: &CreateFlowTask) -> Result<()> {
|
||||
| FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY
|
||||
| FlowType::FLOW_TYPE_KEY => {}
|
||||
unknown => {
|
||||
return UnexpectedSnafu {
|
||||
return InvalidFlowOptionSnafu {
|
||||
err_msg: format!(
|
||||
"Unknown flow option '{unknown}', supported user options: {DEFER_ON_MISSING_SOURCE_KEY}, {FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY}"
|
||||
"unknown flow option '{unknown}', supported options: {DEFER_ON_MISSING_SOURCE_KEY}, {FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY}"
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
|
||||
@@ -19,6 +19,8 @@ use std::collections::HashMap;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use common_error::ext::BoxedError;
|
||||
#[cfg(feature = "enterprise")]
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_event_recorder::Event;
|
||||
use common_procedure::error::{ExternalSnafu, FromJsonSnafu, ToJsonSnafu};
|
||||
use common_procedure::{
|
||||
@@ -53,7 +55,7 @@ use crate::rpc::router::{RegionRoute, operating_leader_region_roles};
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
fn ensure_retry_later(err: error::Error) -> error::Error {
|
||||
if err.is_retry_later() {
|
||||
if err.retry_hint().is_retryable() {
|
||||
err
|
||||
} else {
|
||||
error::Error::retry_later(err)
|
||||
|
||||
@@ -18,6 +18,8 @@ use std::sync::Arc;
|
||||
|
||||
use api::v1::flow::CreateRequest;
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_procedure::{Procedure, Status};
|
||||
use common_procedure_test::execute_procedure_until_done;
|
||||
use table::table_name::TableName;
|
||||
@@ -326,6 +328,26 @@ fn test_validate_flow_options_allows_incremental_read_option() {
|
||||
validate_flow_options(&task).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_flow_options_unknown_option_matches_invalid_sql_error() {
|
||||
let mut task = test_create_flow_task(
|
||||
"my_flow",
|
||||
vec![],
|
||||
TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "my_sink_table"),
|
||||
false,
|
||||
);
|
||||
task.flow_options
|
||||
.insert("foo".to_string(), "sensitive-value".to_string());
|
||||
|
||||
let err = validate_flow_options(&task).unwrap_err();
|
||||
assert_eq!(StatusCode::InvalidArguments, err.status_code());
|
||||
assert_eq!(
|
||||
"Invalid SQL, error: unknown flow option 'foo', supported options: defer_on_missing_source, experimental_enable_incremental_read",
|
||||
err.output_msg()
|
||||
);
|
||||
assert!(!err.output_msg().contains("sensitive-value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_flow_options_rejects_schedule_and_internal_keys_as_unknown() {
|
||||
for key in [
|
||||
@@ -346,9 +368,10 @@ fn test_validate_flow_options_rejects_schedule_and_internal_keys_as_unknown() {
|
||||
.insert(key.to_string(), "value".to_string());
|
||||
|
||||
let err = validate_flow_options(&task).unwrap_err();
|
||||
assert_eq!(StatusCode::InvalidArguments, err.status_code());
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains(&format!("Unknown flow option '{key}'")),
|
||||
.contains(&format!("unknown flow option '{key}'")),
|
||||
"unexpected error for {key}: {err}"
|
||||
);
|
||||
}
|
||||
@@ -884,10 +907,10 @@ async fn test_create_flow_rejects_unknown_option_in_meta_task() {
|
||||
let mut procedure = CreateFlowProcedure::new(task, query_ctx, ddl_context);
|
||||
|
||||
let err = procedure.on_prepare().await.unwrap_err();
|
||||
assert_matches!(err, error::Error::Unexpected { .. });
|
||||
assert_eq!(StatusCode::InvalidArguments, err.status_code());
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("Unknown flow option 'unknown_option'")
|
||||
.contains("unknown flow option 'unknown_option'")
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ use api::v1::region::{
|
||||
use async_trait::async_trait;
|
||||
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
|
||||
use common_procedure::{
|
||||
Context as ProcedureContext, EventContext, EventTrigger, LockKey, Procedure,
|
||||
Result as ProcedureResult, Status,
|
||||
Context as ProcedureContext, Error as ProcedureError, EventContext, EventTrigger, LockKey,
|
||||
Procedure, Result as ProcedureResult, Status,
|
||||
};
|
||||
use common_telemetry::tracing_context::TracingContext;
|
||||
use common_telemetry::warn;
|
||||
@@ -156,6 +156,7 @@ impl UndropTableProcedure {
|
||||
}
|
||||
.await;
|
||||
if let Err(err) = restore_result {
|
||||
// Keep this classification aligned with map_restore_error().
|
||||
let should_cleanup_opened_regions = !err.is_retry_later();
|
||||
let err = self.map_restore_metadata_error(err);
|
||||
if should_cleanup_opened_regions
|
||||
@@ -274,6 +275,19 @@ impl UndropTableProcedure {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_restore_error(err: error::Error) -> ProcedureError {
|
||||
// Restore retries keep opened regions, while other failures close them. Preserve
|
||||
// this policy even when the underlying metadata error carries a retry hint:
|
||||
// retrying after cleanup would restore metadata without reopening the regions.
|
||||
if err.is_retry_later() {
|
||||
map_to_procedure_error(err)
|
||||
} else if err.need_clean_poisons() {
|
||||
ProcedureError::external_and_clean_poisons(err)
|
||||
} else {
|
||||
ProcedureError::external(err)
|
||||
}
|
||||
}
|
||||
|
||||
fn map_restore_metadata_error(&self, err: error::Error) -> error::Error {
|
||||
match err {
|
||||
error::Error::TombstoneTargetAlreadyExists { .. } => {
|
||||
@@ -413,7 +427,12 @@ impl Procedure for UndropTableProcedure {
|
||||
async fn execute(&mut self, _: &ProcedureContext) -> ProcedureResult<Status> {
|
||||
match self.data.state {
|
||||
UndropTableState::Prepare => self.on_prepare().await,
|
||||
UndropTableState::RestoreMetadata => self.on_restore_metadata().await,
|
||||
UndropTableState::RestoreMetadata => {
|
||||
return self
|
||||
.on_restore_metadata()
|
||||
.await
|
||||
.map_err(Self::map_restore_error);
|
||||
}
|
||||
UndropTableState::OpenRegions => self.on_open_regions().await,
|
||||
UndropTableState::InvalidateTableCache => self.on_broadcast().await,
|
||||
}
|
||||
@@ -606,7 +625,8 @@ mod tests {
|
||||
use api::v1::region::region_request;
|
||||
use async_trait::async_trait;
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_error::mock::MockError;
|
||||
use common_error::status_code::StatusCode;
|
||||
use store_api::storage::RegionId;
|
||||
use table::table_name::TableName;
|
||||
@@ -635,6 +655,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_metadata_retry_policy() {
|
||||
let source = error::Error::retry_later(MockError::new(StatusCode::Internal));
|
||||
let err = Err::<(), _>(BoxedError::new(source))
|
||||
.context(error::ExternalSnafu)
|
||||
.unwrap_err();
|
||||
assert!(err.retry_hint().is_retryable());
|
||||
assert!(!err.is_retry_later());
|
||||
let err = UndropTableProcedure::map_restore_error(err);
|
||||
assert!(!err.is_retry_later());
|
||||
assert!(!err.need_clean_poisons());
|
||||
|
||||
for retryable in [false, true] {
|
||||
for clean_poisons in [false, true] {
|
||||
let source = BoxedError::new(MockError::new(StatusCode::Internal));
|
||||
let err = if retryable {
|
||||
error::Error::RetryLater {
|
||||
source,
|
||||
clean_poisons,
|
||||
}
|
||||
} else {
|
||||
Err::<(), _>(source)
|
||||
.context(error::AbortProcedureSnafu { clean_poisons })
|
||||
.unwrap_err()
|
||||
};
|
||||
let err = UndropTableProcedure::map_restore_error(err);
|
||||
assert_eq!(err.is_retry_later(), retryable);
|
||||
assert_eq!(err.need_clean_poisons(), clean_poisons);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map_restore_metadata_error_without_table_name() {
|
||||
let context = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
|
||||
|
||||
@@ -28,7 +28,7 @@ use api::v1::region::{
|
||||
region_request,
|
||||
};
|
||||
use common_catalog::consts::{METRIC_ENGINE, MITO_ENGINE};
|
||||
use common_error::ext::BoxedError;
|
||||
use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_procedure::error::Error as ProcedureError;
|
||||
use common_telemetry::tracing_context::TracingContext;
|
||||
use common_telemetry::{error, info, warn};
|
||||
@@ -61,7 +61,7 @@ use crate::wal_provider::RegionWalOptions;
|
||||
pub fn add_peer_context_if_needed(datanode: Peer) -> impl FnOnce(Error) -> Error {
|
||||
move |err| {
|
||||
error!(err; "Failed to operate datanode, peer: {}", datanode);
|
||||
if !err.is_retry_later() {
|
||||
if !err.retry_hint().is_retryable() {
|
||||
return Err::<(), BoxedError>(BoxedError::new(err))
|
||||
.context(OperateDatanodeSnafu { peer: datanode })
|
||||
.unwrap_err();
|
||||
@@ -84,7 +84,7 @@ pub(crate) fn is_metric_engine_logical_table(
|
||||
/// This function determines whether the error should be retried and if poison cleanup is needed,
|
||||
/// then maps it to the appropriate procedure error variant.
|
||||
pub fn map_to_procedure_error(e: Error) -> ProcedureError {
|
||||
match (e.is_retry_later(), e.need_clean_poisons()) {
|
||||
match (e.retry_hint().is_retryable(), e.need_clean_poisons()) {
|
||||
(true, true) => ProcedureError::retry_later_and_clean_poisons(e),
|
||||
(true, false) => ProcedureError::retry_later(e),
|
||||
(false, true) => ProcedureError::external_and_clean_poisons(e),
|
||||
@@ -256,7 +256,7 @@ pub fn handle_multiple_results<T: Debug>(results: Vec<Result<T>>) -> MultipleRes
|
||||
match result {
|
||||
Ok(value) => ok_results.push(value),
|
||||
Err(err) => {
|
||||
if err.is_retry_later() {
|
||||
if err.retry_hint().is_retryable() {
|
||||
retryable_results.push(err);
|
||||
} else {
|
||||
non_retryable_results.push(err);
|
||||
@@ -475,8 +475,74 @@ pub fn extract_column_metadatas(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use common_error::mock::MockError;
|
||||
use common_error::status_code::StatusCode;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn external_error(retryable: bool) -> Error {
|
||||
let source = MockError::new(StatusCode::Internal);
|
||||
let source = if retryable {
|
||||
BoxedError::new(Error::retry_later(source))
|
||||
} else {
|
||||
BoxedError::new(source)
|
||||
};
|
||||
Err::<(), _>(source)
|
||||
.context(error::ExternalSnafu)
|
||||
.unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map_to_procedure_error() {
|
||||
for retryable in [false, true] {
|
||||
for clean_poisons in [false, true] {
|
||||
let err = if retryable {
|
||||
Error::RetryLater {
|
||||
source: BoxedError::new(external_error(false)),
|
||||
clean_poisons,
|
||||
}
|
||||
} else {
|
||||
Err::<(), _>(BoxedError::new(external_error(true)))
|
||||
.context(error::AbortProcedureSnafu { clean_poisons })
|
||||
.unwrap_err()
|
||||
};
|
||||
let err = map_to_procedure_error(err);
|
||||
assert_eq!(err.is_retry_later(), retryable);
|
||||
assert_eq!(err.need_clean_poisons(), clean_poisons);
|
||||
}
|
||||
let err = map_to_procedure_error(external_error(retryable));
|
||||
assert_eq!(err.is_retry_later(), retryable);
|
||||
assert!(!err.need_clean_poisons());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_multiple_results_retry_hint() {
|
||||
assert!(matches!(
|
||||
handle_multiple_results(vec![Ok(()), Err(external_error(true))]),
|
||||
MultipleResults::PartialRetryable(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
handle_multiple_results::<()>(vec![
|
||||
Err(external_error(true)),
|
||||
Err(external_error(true))
|
||||
]),
|
||||
MultipleResults::AllRetryable(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
handle_multiple_results(vec![
|
||||
Ok(()),
|
||||
Err(external_error(true)),
|
||||
Err(external_error(false))
|
||||
]),
|
||||
MultipleResults::PartialNonRetryable(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
handle_multiple_results::<()>(vec![Err(external_error(false))]),
|
||||
MultipleResults::AllNonRetryable(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_catalog_and_schema() {
|
||||
let test_catalog = "my_catalog";
|
||||
|
||||
@@ -515,6 +515,13 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Invalid SQL, error: {err_msg}"))]
|
||||
InvalidFlowOption {
|
||||
err_msg: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Invalid flow request body: {:?}", body))]
|
||||
InvalidFlowRequestBody {
|
||||
body: Box<Option<api::v1::flow::flow_request::Body>>,
|
||||
@@ -1247,6 +1254,7 @@ impl ErrorExt for Error {
|
||||
|
||||
ProcedureNotFound { .. }
|
||||
| InvalidViewInfo { .. }
|
||||
| InvalidFlowOption { .. }
|
||||
| PrimaryKeyNotFound { .. }
|
||||
| EmptyKey { .. }
|
||||
| AlterLogicalTablesInvalidArguments { .. }
|
||||
@@ -1338,8 +1346,11 @@ impl ErrorExt for Error {
|
||||
use Error::*;
|
||||
|
||||
match self {
|
||||
RetryLater { .. }
|
||||
| GetLatestCacheRetryExceeded { .. }
|
||||
RetryLater { source, .. } => match source.retry_hint() {
|
||||
RetryHint::RetryAfterRouteRefresh => RetryHint::RetryAfterRouteRefresh,
|
||||
RetryHint::Retryable | RetryHint::NonRetryable => RetryHint::Retryable,
|
||||
},
|
||||
GetLatestCacheRetryExceeded { .. }
|
||||
| NoLeader { .. }
|
||||
| ElectionNoLeader { .. }
|
||||
| ElectionLeaderLeaseExpired { .. }
|
||||
@@ -1362,15 +1373,15 @@ impl ErrorExt for Error {
|
||||
| StartProcedureManager { source, .. }
|
||||
| StopProcedureManager { source, .. }
|
||||
| RegisterProcedureLoader { source, .. }
|
||||
| PutPoison { source, .. }
|
||||
| ProcedureStateReceiver { source, .. } => source.retry_hint(),
|
||||
| PutPoison { source, .. } => source.retry_hint(),
|
||||
External { source, .. }
|
||||
| ResponseExceededSizeLimit { source, .. }
|
||||
| OperateDatanode { source, .. }
|
||||
| AbortProcedure { source, .. }
|
||||
| RegisterRepartitionProcedureLoader { source, .. }
|
||||
| CreateRepartitionProcedure { source, .. }
|
||||
| PersistRepartitionGcRequirement { source, .. } => source.retry_hint(),
|
||||
// These errors end an operation; their sources cannot make it retryable.
|
||||
AbortProcedure { .. } | ProcedureStateReceiver { .. } => RetryHint::NonRetryable,
|
||||
Table { source, .. } => source.retry_hint(),
|
||||
ConvertAlterTableRequest { source, .. } => source.retry_hint(),
|
||||
ConvertColumnDef { source, .. } => source.retry_hint(),
|
||||
@@ -1455,6 +1466,7 @@ mod retry_hint_tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_error::mock::MockError;
|
||||
use snafu::ResultExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -1472,6 +1484,42 @@ mod retry_hint_tests {
|
||||
assert_eq!(err.retry_hint(), RetryHint::Retryable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_leader_retry_hints() {
|
||||
for (error, expected) in [
|
||||
(
|
||||
NoLeaderSnafu { table_id: 1_u32 }.build(),
|
||||
RetryHint::Retryable,
|
||||
),
|
||||
(ElectionNoLeaderSnafu.build(), RetryHint::Retryable),
|
||||
(
|
||||
ElectionLeaderLeaseExpiredSnafu.build(),
|
||||
RetryHint::Retryable,
|
||||
),
|
||||
(
|
||||
ElectionLeaderLeaseChangedSnafu.build(),
|
||||
RetryHint::Retryable,
|
||||
),
|
||||
] {
|
||||
assert_eq!(error.retry_hint(), expected, "{error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_procedure_error_retry_hints() {
|
||||
let source = common_procedure::Error::retry_later(MockError::new(StatusCode::Internal));
|
||||
let err = Err::<(), _>(source).context(PutPoisonSnafu).unwrap_err();
|
||||
assert_eq!(err.retry_hint(), RetryHint::Retryable);
|
||||
|
||||
let source = common_procedure::Error::retry_later(MockError::new(StatusCode::Internal));
|
||||
let err = Err::<(), _>(source)
|
||||
.context(ProcedureStateReceiverSnafu {
|
||||
procedure_id: ProcedureId::random(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_cache_forwards_retry_hint() {
|
||||
let source = Arc::new(Error::retry_later(MockError::new(StatusCode::Internal)));
|
||||
|
||||
@@ -49,7 +49,7 @@ pub struct InstructionError {
|
||||
pub message: String,
|
||||
/// Retry hint serialized as a string.
|
||||
#[serde(
|
||||
serialize_with = "RetryHint::serialize_as_str",
|
||||
serialize_with = "InstructionError::serialize_retry_hint",
|
||||
deserialize_with = "RetryHint::deserialize_from_str"
|
||||
)]
|
||||
pub retry_hint: RetryHint,
|
||||
@@ -108,6 +108,18 @@ impl InstructionError {
|
||||
retry_hint: error.retry_hint(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps instruction replies readable by peers that only know the legacy hints.
|
||||
fn serialize_retry_hint<S>(hint: &RetryHint, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let hint = match hint {
|
||||
RetryHint::RetryAfterRouteRefresh => RetryHint::Retryable,
|
||||
hint => *hint,
|
||||
};
|
||||
RetryHint::serialize_as_str(&hint, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for InstructionError {
|
||||
@@ -732,12 +744,12 @@ impl PackedRegionFileRefs {
|
||||
}
|
||||
|
||||
let mut refs = HashSet::new();
|
||||
for bytes in files.chunks_exact(16) {
|
||||
for bytes in files.as_chunks::<16>().0 {
|
||||
let mut id = [0; 16];
|
||||
id.copy_from_slice(bytes);
|
||||
refs.insert(FileRef::new(region, FileId::from_bytes(id), None));
|
||||
}
|
||||
for bytes in indexed.chunks_exact(24) {
|
||||
for bytes in indexed.as_chunks::<24>().0 {
|
||||
let mut id = [0; 16];
|
||||
id.copy_from_slice(&bytes[..16]);
|
||||
let mut version = [0; 8];
|
||||
@@ -1450,6 +1462,26 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_instruction_error_route_refresh_compatibility() {
|
||||
let error = InstructionError::new(
|
||||
StatusCode::RegionNotFound,
|
||||
"region not found",
|
||||
RetryHint::RetryAfterRouteRefresh,
|
||||
);
|
||||
let serialized = serde_json::to_string(&error).unwrap();
|
||||
assert_eq!(
|
||||
r#"{"code":4005,"message":"region not found","retry_hint":"retryable"}"#,
|
||||
serialized
|
||||
);
|
||||
let decoded: InstructionError = serde_json::from_str(&serialized).unwrap();
|
||||
assert_eq!(decoded.code, error.code);
|
||||
assert_eq!(decoded.message, error.message);
|
||||
assert_eq!(decoded.retry_hint, RetryHint::Retryable);
|
||||
assert_eq!(error.retry_hint, RetryHint::RetryAfterRouteRefresh);
|
||||
assert_eq!(error.retry_hint.as_str(), "retry_after_route_refresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_instruction_error_from_error() {
|
||||
let error = MockError::new(StatusCode::RegionNotFound);
|
||||
|
||||
@@ -82,7 +82,7 @@ impl KvBackend for ChrootKvBackend {
|
||||
|
||||
async fn batch_put(&self, mut req: BatchPutRequest) -> Result<BatchPutResponse, Self::Error> {
|
||||
for kv in req.kvs.iter_mut() {
|
||||
kv.key = self.key_prepend_root(kv.key.drain(..).collect());
|
||||
kv.key = self.key_prepend_root(std::mem::take(&mut kv.key));
|
||||
}
|
||||
let mut res = self.inner.batch_put(req).await?;
|
||||
res.prev_kvs = res
|
||||
|
||||
@@ -28,12 +28,22 @@ use crate::peer::Peer;
|
||||
#[async_trait::async_trait]
|
||||
pub trait Datanode: Send + Sync {
|
||||
/// Handles DML, and DDL requests.
|
||||
async fn handle(&self, request: RegionRequest) -> Result<RegionResponse>;
|
||||
async fn handle_request(&self, request: Arc<RegionRequest>) -> Result<RegionResponse>;
|
||||
|
||||
/// Handles query requests
|
||||
async fn handle_query(&self, request: QueryRequest) -> Result<SendableRecordBatchStream>;
|
||||
}
|
||||
|
||||
impl dyn Datanode + '_ {
|
||||
/// Handles an owned or shared request without cloning its payload.
|
||||
pub async fn handle<R>(&self, request: R) -> Result<RegionResponse>
|
||||
where
|
||||
R: Into<Arc<RegionRequest>> + Send,
|
||||
{
|
||||
self.handle_request(request.into()).await
|
||||
}
|
||||
}
|
||||
|
||||
pub type DatanodeRef = Arc<dyn Datanode>;
|
||||
|
||||
/// The trait for handling requests to flownode
|
||||
|
||||
@@ -22,6 +22,9 @@ use crate::cluster::NodeInfo;
|
||||
use crate::error::Error;
|
||||
use crate::{DatanodeId, FlownodeId};
|
||||
|
||||
/// Shared reference to a [`Peer`].
|
||||
pub type PeerRef = Arc<Peer>;
|
||||
|
||||
/// [`PeerResolver`] provides methods to look up peer information by node ID.
|
||||
///
|
||||
/// This trait allows resolving both datanode and flownode peers, regardless of their current activity status.
|
||||
|
||||
@@ -16,6 +16,7 @@ use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
use std::time::Instant;
|
||||
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_procedure::error::FromJsonSnafu;
|
||||
use common_procedure::{
|
||||
Context as ProcedureContext, Error as ProcedureError, EventContext, EventTrigger, LockKey,
|
||||
@@ -191,7 +192,7 @@ impl Procedure for ReconcileCatalogProcedure {
|
||||
Ok(status)
|
||||
}
|
||||
Err(e) => {
|
||||
if e.is_retry_later() {
|
||||
if e.retry_hint().is_retryable() {
|
||||
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
|
||||
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
|
||||
.inc();
|
||||
|
||||
@@ -23,6 +23,7 @@ use std::fmt::Debug;
|
||||
use std::time::Instant;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
|
||||
use common_procedure::{
|
||||
Context as ProcedureContext, Error as ProcedureError, EventContext, EventTrigger, LockKey,
|
||||
@@ -231,7 +232,7 @@ impl Procedure for ReconcileDatabaseProcedure {
|
||||
Ok(status)
|
||||
}
|
||||
Err(e) => {
|
||||
if e.is_retry_later() {
|
||||
if e.retry_hint().is_retryable() {
|
||||
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
|
||||
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
|
||||
.inc();
|
||||
|
||||
@@ -22,6 +22,7 @@ use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
|
||||
use common_procedure::{
|
||||
Context as ProcedureContext, Error as ProcedureError, EventContext, EventTrigger, LockKey,
|
||||
@@ -207,7 +208,7 @@ impl Procedure for ReconcileLogicalTablesProcedure {
|
||||
Ok(status)
|
||||
}
|
||||
Err(e) => {
|
||||
if e.is_retry_later() {
|
||||
if e.retry_hint().is_retryable() {
|
||||
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
|
||||
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
|
||||
.inc();
|
||||
|
||||
@@ -20,6 +20,7 @@ pub(crate) mod update_table_info;
|
||||
|
||||
use std::fmt::Debug;
|
||||
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
|
||||
use common_procedure::{
|
||||
Context as ProcedureContext, Error as ProcedureError, EventContext, EventTrigger, LockKey,
|
||||
@@ -318,7 +319,7 @@ impl Procedure for ReconcileTableProcedure {
|
||||
Ok(status)
|
||||
}
|
||||
Err(e) => {
|
||||
if e.is_retry_later() {
|
||||
if e.retry_hint().is_retryable() {
|
||||
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
|
||||
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
|
||||
.inc();
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn region_distribution(region_routes: &[RegionRoute]) -> RegionDistribution
|
||||
.add_follower_region(region_number);
|
||||
}
|
||||
}
|
||||
for (_, region_role_set) in regions_id_map.iter_mut() {
|
||||
for region_role_set in regions_id_map.values_mut() {
|
||||
// Sort the regions in ascending order.
|
||||
region_role_set.sort()
|
||||
}
|
||||
@@ -114,15 +114,25 @@ pub fn convert_to_region_leader_map(region_routes: &[RegionRoute]) -> HashMap<Re
|
||||
.collect::<HashMap<_, _>>()
|
||||
}
|
||||
|
||||
/// Returns the leader of the first route matching the region number.
|
||||
pub fn find_region_leader(
|
||||
region_routes: &[RegionRoute],
|
||||
region_number: RegionNumber,
|
||||
) -> Option<Peer> {
|
||||
find_region_leader_ref(region_routes, region_number).cloned()
|
||||
}
|
||||
|
||||
/// Borrows the leader of the first route matching the region number.
|
||||
///
|
||||
/// Returns `None` if no route matches or the first matching route has no leader.
|
||||
pub fn find_region_leader_ref(
|
||||
region_routes: &[RegionRoute],
|
||||
region_number: RegionNumber,
|
||||
) -> Option<&Peer> {
|
||||
region_routes
|
||||
.iter()
|
||||
.find(|x| x.region.id.region_number() == region_number)
|
||||
.and_then(|r| r.leader_peer.as_ref())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// Returns the region numbers of the leader regions on the target datanode.
|
||||
@@ -442,6 +452,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_region_leader() {
|
||||
let mut routes = vec![
|
||||
new_test_region_route(RegionId::new(1, 1)),
|
||||
new_test_region_route(RegionId::new(1, 1)),
|
||||
];
|
||||
routes[1].leader_peer = Some(Peer::new(2, "a2"));
|
||||
|
||||
assert_eq!(
|
||||
find_region_leader_ref(&routes, 1),
|
||||
routes[0].leader_peer.as_ref()
|
||||
);
|
||||
assert_eq!(find_region_leader(&routes, 1), routes[0].leader_peer);
|
||||
assert_eq!(find_region_leader_ref(&routes, 2), None);
|
||||
assert_eq!(find_region_leader(&routes, 2), None);
|
||||
|
||||
routes[0].leader_peer = None;
|
||||
assert_eq!(find_region_leader_ref(&routes, 1), None);
|
||||
assert_eq!(find_region_leader(&routes, 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_leader_is_downgraded() {
|
||||
let mut region_route = RegionRoute {
|
||||
|
||||
@@ -199,7 +199,7 @@ impl RangeResponse {
|
||||
}
|
||||
|
||||
pub fn take_kvs(&mut self) -> Vec<KeyValue> {
|
||||
self.kvs.drain(..).collect()
|
||||
std::mem::take(&mut self.kvs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,7 +451,7 @@ impl BatchPutResponse {
|
||||
}
|
||||
|
||||
pub fn take_prev_kvs(&mut self) -> Vec<KeyValue> {
|
||||
self.prev_kvs.drain(..).collect()
|
||||
std::mem::take(&mut self.prev_kvs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -780,7 +780,7 @@ impl DeleteRangeResponse {
|
||||
}
|
||||
|
||||
pub fn take_prev_kvs(&mut self) -> Vec<KeyValue> {
|
||||
self.prev_kvs.drain(..).collect()
|
||||
std::mem::take(&mut self.prev_kvs)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ impl Inner {
|
||||
}
|
||||
|
||||
error::NextSequenceSnafu {
|
||||
err_msg: format!("{}.next()", &self.name),
|
||||
err_msg: format!("{}.next()", self.name),
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
@@ -264,7 +264,7 @@ impl Inner {
|
||||
}
|
||||
|
||||
error::NextSequenceSnafu {
|
||||
err_msg: format!("{}.next_range()", &self.name),
|
||||
err_msg: format!("{}.next_range()", self.name),
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
|
||||
@@ -111,7 +111,8 @@ struct MockNode<T> {
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: MockDatanodeHandler> Datanode for MockNode<T> {
|
||||
async fn handle(&self, request: RegionRequest) -> Result<RegionResponse> {
|
||||
async fn handle_request(&self, request: Arc<RegionRequest>) -> Result<RegionResponse> {
|
||||
let request = Arc::try_unwrap(request).expect("mock request must be exclusively owned");
|
||||
self.handler.handle(&self.peer, request).await
|
||||
}
|
||||
|
||||
@@ -322,8 +323,8 @@ macro_rules! maybe_skip_etcd_tls_integration_test {
|
||||
|
||||
/// Returns the directory of the etcd TLS certs.
|
||||
pub fn etcd_certs_dir() -> PathBuf {
|
||||
let project_path = env!("CARGO_MANIFEST_DIR");
|
||||
let project_path = PathBuf::from(project_path);
|
||||
let project_path =
|
||||
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
|
||||
let base = project_path.ancestors().nth(3).unwrap();
|
||||
base.join("tests-integration")
|
||||
.join("fixtures")
|
||||
@@ -332,8 +333,8 @@ pub fn etcd_certs_dir() -> PathBuf {
|
||||
|
||||
/// Returns the directory of the test certs.
|
||||
pub fn test_certs_dir() -> PathBuf {
|
||||
let project_path = env!("CARGO_MANIFEST_DIR");
|
||||
let project_path = PathBuf::from(project_path);
|
||||
let project_path =
|
||||
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
|
||||
let base = project_path.ancestors().nth(3).unwrap();
|
||||
base.join("tests-integration")
|
||||
.join("fixtures")
|
||||
|
||||
@@ -306,7 +306,8 @@ impl ErrorExt for Error {
|
||||
| Error::DeletePoison { source, .. }
|
||||
| Error::GetPoison { source, .. }
|
||||
| Error::CheckStatus { source, .. } => source.retry_hint(),
|
||||
Error::ProcedureExec { source, .. } => source.retry_hint(),
|
||||
// The watcher reports this only after the child has failed or been poisoned.
|
||||
Error::ProcedureExec { .. } => RetryHint::NonRetryable,
|
||||
Error::StartRemoveOutdatedMetaTask { source, .. }
|
||||
| Error::StopRemoveOutdatedMetaTask { source, .. } => source.retry_hint(),
|
||||
Error::DeleteState { error, .. } => retry_hint_from_opendal_error(error),
|
||||
@@ -379,8 +380,11 @@ mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_error::mock::MockError;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use super::*;
|
||||
use crate::procedure::ProcedureState;
|
||||
use crate::watcher;
|
||||
|
||||
#[test]
|
||||
fn test_retry_later_hint_is_retryable() {
|
||||
@@ -397,6 +401,21 @@ mod tests {
|
||||
assert_eq!(err.retry_hint(), RetryHint::Retryable);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_finished_procedure_hint_is_non_retryable() {
|
||||
let source = Arc::new(Error::retry_later(MockError::new(StatusCode::Internal)));
|
||||
for state in [
|
||||
ProcedureState::failed(source.clone()),
|
||||
ProcedureState::poisoned(Default::default(), source),
|
||||
] {
|
||||
let (sender, mut receiver) = watch::channel(ProcedureState::Running);
|
||||
sender.send(state).unwrap();
|
||||
let err = watcher::wait(&mut receiver).await.unwrap_err();
|
||||
|
||||
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_retry_exceeded_hint_is_non_retryable() {
|
||||
let source = Arc::new(Error::retry_later(MockError::new(StatusCode::Internal)));
|
||||
|
||||
@@ -95,7 +95,7 @@ impl DisplayAs for StreamScanAdapter {
|
||||
f,
|
||||
"StreamScanAdapter: [<SendableRecordBatchStream>], schema: ["
|
||||
)?;
|
||||
write!(f, "{:?}", &self.arrow_schema)?;
|
||||
write!(f, "{:?}", self.arrow_schema)?;
|
||||
write!(f, "]")
|
||||
}
|
||||
}
|
||||
|
||||
+124
-1091
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,944 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Predicate recognition, execution, and precompiled regular expressions.
|
||||
|
||||
use datafusion::logical_expr::{Expr, Operator};
|
||||
use datafusion_common::ScalarValue;
|
||||
use datafusion_common::arrow::array::{ArrayRef, Datum, Scalar};
|
||||
use datafusion_common::arrow::buffer::BooleanBuffer;
|
||||
use datafusion_common::arrow::compute::kernels::cmp;
|
||||
use datafusion_common::cast::as_string_array;
|
||||
use datatypes::arrow::array::{
|
||||
Array, ArrayAccessor, ArrayData, BooleanArray, BooleanBufferBuilder, DictionaryArray,
|
||||
StringArrayType,
|
||||
};
|
||||
use datatypes::arrow::datatypes::{DataType, UInt32Type};
|
||||
use datatypes::arrow::error::ArrowError;
|
||||
use datatypes::compute::or_kleene;
|
||||
use regex::Regex;
|
||||
use snafu::ResultExt;
|
||||
|
||||
use crate::error::{ArrowComputeSnafu, Result, UnsupportedOperationSnafu};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum SimplePredicate {
|
||||
Comparison {
|
||||
literal: Scalar<ArrayRef>,
|
||||
op: Operator,
|
||||
regex: Option<Regex>,
|
||||
regex_negative: bool,
|
||||
},
|
||||
OrEqChain {
|
||||
literals: Vec<Scalar<ArrayRef>>,
|
||||
},
|
||||
IsNull {
|
||||
negated: bool,
|
||||
},
|
||||
Constant(Option<bool>),
|
||||
And(Box<Self>, Box<Self>),
|
||||
Or(Box<Self>, Box<Self>),
|
||||
}
|
||||
|
||||
impl SimplePredicate {
|
||||
pub(crate) fn try_new(expr: &Expr, column_type: Option<&DataType>) -> Option<Self> {
|
||||
match expr {
|
||||
Expr::BinaryExpr(binary) if matches!(binary.op, Operator::And | Operator::Or) => {
|
||||
let left = Self::try_new(&binary.left, column_type)?;
|
||||
let right = Self::try_new(&binary.right, column_type)?;
|
||||
if binary.op == Operator::And {
|
||||
return Some(Self::And(Box::new(left), Box::new(right)));
|
||||
}
|
||||
// Preserve the encoded-key IN-list fast path for pure equality disjunctions.
|
||||
if let (Some(mut lhs), Some(rhs)) =
|
||||
(left.equality_literals(), right.equality_literals())
|
||||
{
|
||||
lhs.extend(rhs);
|
||||
return Some(Self::OrEqChain { literals: lhs });
|
||||
}
|
||||
Some(Self::Or(Box::new(left), Box::new(right)))
|
||||
}
|
||||
Expr::BinaryExpr(binary) => {
|
||||
let mut op = binary.op;
|
||||
if !matches!(
|
||||
op,
|
||||
Operator::Eq
|
||||
| Operator::NotEq
|
||||
| Operator::Lt
|
||||
| Operator::LtEq
|
||||
| Operator::Gt
|
||||
| Operator::GtEq
|
||||
| Operator::RegexMatch
|
||||
| Operator::RegexIMatch
|
||||
| Operator::RegexNotMatch
|
||||
| Operator::RegexNotIMatch
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
let literal = if let Expr::Literal(literal, _) = &*binary.right {
|
||||
Self::check_column(&binary.left, column_type)?;
|
||||
literal
|
||||
} else if let Expr::Literal(literal, _) = &*binary.left {
|
||||
Self::check_column(&binary.right, column_type)?;
|
||||
op = op.swap()?;
|
||||
literal
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let (regex, regex_negative) = Self::maybe_build_regex(op, literal).ok()?;
|
||||
Some(Self::Comparison {
|
||||
literal: literal.to_scalar().ok()?,
|
||||
op,
|
||||
regex,
|
||||
regex_negative,
|
||||
})
|
||||
}
|
||||
Expr::IsNull(column) | Expr::IsNotNull(column) => {
|
||||
Self::check_column(column, column_type)?;
|
||||
Some(Self::IsNull {
|
||||
negated: matches!(expr, Expr::IsNotNull(_)),
|
||||
})
|
||||
}
|
||||
Expr::Literal(ScalarValue::Boolean(value), _) => Some(Self::Constant(*value)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_column(expr: &Expr, column_type: Option<&DataType>) -> Option<()> {
|
||||
match expr {
|
||||
Expr::Column(_) => Some(()),
|
||||
Expr::Cast(cast) if cast.field.data_type() == &DataType::Utf8 => {
|
||||
let Expr::Column(_) = &*cast.expr else {
|
||||
return None;
|
||||
};
|
||||
match column_type? {
|
||||
DataType::Utf8 => Some(()),
|
||||
DataType::Dictionary(key, value)
|
||||
if **key == DataType::UInt32 && **value == DataType::Utf8 =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn equality_literals(&self) -> Option<Vec<Scalar<ArrayRef>>> {
|
||||
match self {
|
||||
Self::Comparison {
|
||||
literal,
|
||||
op: Operator::Eq,
|
||||
..
|
||||
} => Some(vec![literal.clone()]),
|
||||
Self::OrEqChain { literals } => Some(literals.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn evaluate(&self, input: &impl Datum, len: usize) -> Result<BooleanArray> {
|
||||
match self {
|
||||
Self::Comparison {
|
||||
literal,
|
||||
op,
|
||||
regex,
|
||||
regex_negative,
|
||||
} => match op {
|
||||
Operator::Eq => cmp::eq(input, literal),
|
||||
Operator::NotEq => cmp::neq(input, literal),
|
||||
Operator::Lt => cmp::lt(input, literal),
|
||||
Operator::LtEq => cmp::lt_eq(input, literal),
|
||||
Operator::Gt => cmp::gt(input, literal),
|
||||
Operator::GtEq => cmp::gt_eq(input, literal),
|
||||
Operator::RegexMatch
|
||||
| Operator::RegexIMatch
|
||||
| Operator::RegexNotMatch
|
||||
| Operator::RegexNotIMatch => {
|
||||
Self::regex_match(input, regex.as_ref(), *regex_negative)
|
||||
}
|
||||
_ => {
|
||||
return UnsupportedOperationSnafu {
|
||||
reason: format!("{op:?}"),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
}
|
||||
.context(ArrowComputeSnafu),
|
||||
Self::OrEqChain { literals } => {
|
||||
let mut result = BooleanArray::from(vec![false; len]);
|
||||
for literal in literals {
|
||||
let rhs = cmp::eq(input, literal).context(ArrowComputeSnafu)?;
|
||||
result = or_kleene(&result, &rhs).context(ArrowComputeSnafu)?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
Self::IsNull { negated } => {
|
||||
let values = match input.get().0.logical_nulls() {
|
||||
Some(nulls) if *negated => nulls.inner().clone(),
|
||||
Some(nulls) => !nulls.inner(),
|
||||
None if *negated => BooleanBuffer::new_set(len),
|
||||
None => BooleanBuffer::new_unset(len),
|
||||
};
|
||||
Ok(BooleanArray::new(values, None))
|
||||
}
|
||||
Self::Constant(value) => Ok(BooleanArray::from(vec![*value; len])),
|
||||
Self::And(left, right) => datatypes::compute::and_kleene(
|
||||
&left.evaluate(input, len)?,
|
||||
&right.evaluate(input, len)?,
|
||||
)
|
||||
.context(ArrowComputeSnafu),
|
||||
Self::Or(left, right) => {
|
||||
or_kleene(&left.evaluate(input, len)?, &right.evaluate(input, len)?)
|
||||
.context(ArrowComputeSnafu)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a regex pattern from a scalar value and operator.
|
||||
/// Returns the `(regex, negative)` and if successful.
|
||||
///
|
||||
/// Returns `Err` if
|
||||
/// - the value is not a string
|
||||
/// - the regex pattern is invalid
|
||||
///
|
||||
/// The regex is `None` if
|
||||
/// - the operator is not a regex operator
|
||||
/// - the pattern is empty
|
||||
fn maybe_build_regex(
|
||||
operator: Operator,
|
||||
value: &ScalarValue,
|
||||
) -> Result<(Option<Regex>, bool), ArrowError> {
|
||||
let (ignore_case, negative) = match operator {
|
||||
Operator::RegexMatch => (false, false),
|
||||
Operator::RegexIMatch => (true, false),
|
||||
Operator::RegexNotMatch => (false, true),
|
||||
Operator::RegexNotIMatch => (true, true),
|
||||
_ => return Ok((None, false)),
|
||||
};
|
||||
let flag = if ignore_case { Some("i") } else { None };
|
||||
let regex = value
|
||||
.try_as_str()
|
||||
.ok_or_else(|| ArrowError::CastError(format!("Cannot cast {:?} to str", value)))?
|
||||
.ok_or_else(|| ArrowError::CastError("Regex should not be null".to_string()))?;
|
||||
let pattern = match flag {
|
||||
Some(flag) => format!("(?{flag}){regex}"),
|
||||
None => regex.to_string(),
|
||||
};
|
||||
if pattern.is_empty() {
|
||||
Ok((None, negative))
|
||||
} else {
|
||||
Regex::new(pattern.as_str())
|
||||
.map_err(|e| {
|
||||
ArrowError::ComputeError(format!("Regular expression did not compile: {e:?}"))
|
||||
})
|
||||
.map(|regex| (Some(regex), negative))
|
||||
}
|
||||
}
|
||||
|
||||
fn regex_match(
|
||||
input: &impl Datum,
|
||||
regex: Option<&Regex>,
|
||||
negative: bool,
|
||||
) -> std::result::Result<BooleanArray, ArrowError> {
|
||||
let array = input.get().0;
|
||||
|
||||
// Try to cast to StringArray first
|
||||
if let Ok(string_array) = as_string_array(array) {
|
||||
let mut result = regexp_is_match_scalar(string_array, regex)?;
|
||||
if negative {
|
||||
result = datatypes::compute::not(&result)?;
|
||||
}
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// Try to cast to StringDictionaryArray
|
||||
if let Some(dict_array) = array.as_any().downcast_ref::<DictionaryArray<UInt32Type>>() {
|
||||
let mut result = regexp_is_match_dictionary(dict_array, regex)?;
|
||||
if negative {
|
||||
result = datatypes::compute::not(&result)?;
|
||||
}
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
Err(ArrowError::CastError(format!(
|
||||
"Cannot cast {:?} to StringArray or StringDictionaryArray",
|
||||
array.data_type()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The same as arrow [regexp_is_match_scalar()](datatypes::compute::kernels::regexp::regexp_is_match_scalar())
|
||||
/// with pre-compiled regex.
|
||||
/// See <https://github.com/apache/arrow-rs/blob/54.2.0/arrow-string/src/regexp.rs#L204-L246> for the implementation details.
|
||||
pub fn regexp_is_match_scalar<'a, S>(
|
||||
array: &'a S,
|
||||
regex: Option<&Regex>,
|
||||
) -> Result<BooleanArray, ArrowError>
|
||||
where
|
||||
&'a S: StringArrayType<'a>,
|
||||
{
|
||||
let null_bit_buffer = array.nulls().map(|x| x.inner().sliced());
|
||||
let mut result = BooleanBufferBuilder::new(array.len());
|
||||
|
||||
if let Some(re) = regex {
|
||||
for i in 0..array.len() {
|
||||
let value = array.value(i);
|
||||
result.append(re.is_match(value));
|
||||
}
|
||||
} else {
|
||||
result.append_n(array.len(), true);
|
||||
}
|
||||
|
||||
let buffer = result.into();
|
||||
let data = unsafe {
|
||||
ArrayData::new_unchecked(
|
||||
DataType::Boolean,
|
||||
array.len(),
|
||||
None,
|
||||
null_bit_buffer,
|
||||
0,
|
||||
vec![buffer],
|
||||
vec![],
|
||||
)
|
||||
};
|
||||
|
||||
Ok(BooleanArray::from(data))
|
||||
}
|
||||
|
||||
/// Similar to [regexp_is_match_scalar] but for StringDictionaryArray.
|
||||
/// Iterates through dictionary keys to get string values and applies regex matching.
|
||||
pub fn regexp_is_match_dictionary(
|
||||
dict_array: &DictionaryArray<UInt32Type>,
|
||||
regex: Option<&Regex>,
|
||||
) -> Result<BooleanArray, ArrowError> {
|
||||
// Get the string values from the dictionary
|
||||
let string_values = dict_array
|
||||
.values()
|
||||
.as_any()
|
||||
.downcast_ref::<datatypes::arrow::array::StringArray>()
|
||||
.ok_or_else(|| {
|
||||
ArrowError::CastError("Dictionary values must be StringArray".to_string())
|
||||
})?;
|
||||
|
||||
// Dictionary logical nulls include both null keys and keys whose dictionary value is null.
|
||||
let logical_nulls = dict_array.logical_nulls();
|
||||
let null_bit_buffer = logical_nulls.as_ref().map(|x| x.inner().sliced());
|
||||
let mut result = BooleanBufferBuilder::new(dict_array.len());
|
||||
|
||||
if let Some(re) = regex {
|
||||
let keys = dict_array.keys().values();
|
||||
for i in 0..dict_array.len() {
|
||||
if logical_nulls.as_ref().is_some_and(|nulls| nulls.is_null(i)) {
|
||||
result.append(false);
|
||||
} else {
|
||||
let key = keys[i] as usize;
|
||||
let string_value = string_values.value(key);
|
||||
result.append(re.is_match(string_value));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result.append_n(dict_array.len(), true);
|
||||
}
|
||||
|
||||
let buffer = result.into();
|
||||
let data = unsafe {
|
||||
ArrayData::new_unchecked(
|
||||
DataType::Boolean,
|
||||
dict_array.len(),
|
||||
None,
|
||||
null_bit_buffer,
|
||||
0,
|
||||
vec![buffer],
|
||||
vec![],
|
||||
)
|
||||
};
|
||||
|
||||
Ok(BooleanArray::from(data))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::execution::context::ExecutionProps;
|
||||
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
|
||||
use datafusion::logical_expr::{BinaryExpr, Expr, Literal, Operator, col, lit};
|
||||
use datafusion::physical_expr::create_physical_expr;
|
||||
use datafusion_common::arrow::array::ArrayRef;
|
||||
use datafusion_common::arrow::buffer::BooleanBuffer;
|
||||
use datafusion_common::{Column, DFSchema, ScalarValue};
|
||||
use datatypes::arrow::array::{Array, DictionaryArray, RecordBatch};
|
||||
use datatypes::arrow::datatypes::{DataType, Field, Schema, TimeUnit, UInt32Type};
|
||||
use datatypes::value::Value;
|
||||
use regex::Regex;
|
||||
|
||||
use crate::filter::predicate::{SimplePredicate, regexp_is_match_dictionary};
|
||||
use crate::filter::{SimpleFilterEvaluator, batch_filter};
|
||||
|
||||
#[test]
|
||||
fn unsupported_filter_op() {
|
||||
// `+` is not supported
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::Column(Column::from_name("foo"))),
|
||||
op: Operator::Plus,
|
||||
right: Box::new(1.lit()),
|
||||
});
|
||||
assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
|
||||
|
||||
// two literal is not supported
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(1.lit()),
|
||||
op: Operator::Eq,
|
||||
right: Box::new(1.lit()),
|
||||
});
|
||||
assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
|
||||
|
||||
// two column is not supported
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::Column(Column::from_name("foo"))),
|
||||
op: Operator::Eq,
|
||||
right: Box::new(Expr::Column(Column::from_name("bar"))),
|
||||
});
|
||||
assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
|
||||
|
||||
// compound expr is not supported
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::Column(Column::from_name("foo"))),
|
||||
op: Operator::Eq,
|
||||
right: Box::new(1.lit()),
|
||||
})),
|
||||
op: Operator::Eq,
|
||||
right: Box::new(1.lit()),
|
||||
});
|
||||
assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
|
||||
for negated in [false, true] {
|
||||
let membership = col("label").in_list(vec![lit(""), lit("lo")], negated);
|
||||
assert!(SimpleFilterEvaluator::try_new(&membership).is_none());
|
||||
assert!(
|
||||
SimpleFilterEvaluator::try_new(&col("label").is_null().or(membership)).is_none()
|
||||
);
|
||||
}
|
||||
for expr in [
|
||||
col("other").is_null().or(col("label").not_eq(lit("lo"))),
|
||||
col("a.label")
|
||||
.is_null()
|
||||
.or(col("b.label").not_eq(lit("lo"))),
|
||||
col("label").is_null().or(col("label").eq(col("other"))),
|
||||
col("label")
|
||||
.is_null()
|
||||
.or(Expr::Cast(datafusion::logical_expr::Cast::new(
|
||||
Box::new(col("label")),
|
||||
DataType::Int64,
|
||||
))
|
||||
.eq(lit("lo"))),
|
||||
] {
|
||||
assert!(SimpleFilterEvaluator::try_new(&expr).is_none(), "{expr}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_cast_requires_matching_column_type() {
|
||||
let cast = Expr::Cast(datafusion::logical_expr::Cast::new(
|
||||
Box::new(col("label")),
|
||||
DataType::Utf8,
|
||||
));
|
||||
let expr = col("label").is_null().or(cast.not_eq(lit("lo")));
|
||||
for data_type in [
|
||||
DataType::Int64,
|
||||
DataType::Timestamp(TimeUnit::Millisecond, None),
|
||||
DataType::Binary,
|
||||
] {
|
||||
assert!(
|
||||
SimpleFilterEvaluator::try_new_with_column_type(&expr, &|_| Some(
|
||||
data_type.clone()
|
||||
))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn single_column_predicates_match_datafusion() {
|
||||
use datafusion::prelude::SessionContext;
|
||||
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
|
||||
use datatypes::arrow::array::{Int32Array, StringArray, UInt32Array};
|
||||
|
||||
let values = vec![
|
||||
None,
|
||||
Some(""),
|
||||
Some("lo"),
|
||||
Some("eth0"),
|
||||
Some("a\nb"),
|
||||
Some("服务"),
|
||||
None,
|
||||
];
|
||||
let strings: ArrayRef = Arc::new(StringArray::from(values));
|
||||
let dictionary: ArrayRef = Arc::new(DictionaryArray::<UInt32Type>::new(
|
||||
UInt32Array::from(vec![
|
||||
None,
|
||||
Some(0),
|
||||
Some(1),
|
||||
Some(2),
|
||||
Some(3),
|
||||
Some(4),
|
||||
Some(5),
|
||||
]),
|
||||
Arc::new(StringArray::from(vec![
|
||||
Some(""),
|
||||
Some("lo"),
|
||||
Some("eth0"),
|
||||
Some("a\nb"),
|
||||
Some("服务"),
|
||||
None,
|
||||
])),
|
||||
));
|
||||
let null = || lit(ScalarValue::Utf8(None));
|
||||
let mut predicates = vec![
|
||||
col("label").is_null(),
|
||||
col("label").is_not_null(),
|
||||
col("label")
|
||||
.is_null()
|
||||
.or(col("label").eq(lit("")))
|
||||
.and(col("label").is_not_null()),
|
||||
col("label")
|
||||
.not_eq(lit("lo"))
|
||||
.and(col("label").not_eq(lit("eth0"))),
|
||||
col("label")
|
||||
.eq(lit("lo"))
|
||||
.or(col("label").eq(lit("eth0")))
|
||||
.or(col("label").eq(lit(""))),
|
||||
col("label").eq(null()).or(col("label").eq(lit("eth0"))),
|
||||
col("label").gt(lit("a")).and(col("label").lt(lit("z"))),
|
||||
lit("lo").not_eq(col("label")),
|
||||
];
|
||||
for (op, literal) in [
|
||||
(Operator::Eq, ""),
|
||||
(Operator::NotEq, "lo"),
|
||||
(Operator::RegexNotMatch, "^(?:lo|vfat)$"),
|
||||
(Operator::RegexMatch, "^(?:|eth0)$"),
|
||||
] {
|
||||
let comparison = Expr::BinaryExpr(BinaryExpr::new(
|
||||
Box::new(col("label")),
|
||||
op,
|
||||
Box::new(lit(literal)),
|
||||
));
|
||||
predicates.extend([
|
||||
col("label").is_null().or(comparison.clone()),
|
||||
comparison.or(col("label").is_null()),
|
||||
]);
|
||||
}
|
||||
for input in [strings, dictionary] {
|
||||
let ctx = SessionContext::new();
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("label", input.data_type().clone(), true),
|
||||
Field::new("id", DataType::Int32, false),
|
||||
]));
|
||||
ctx.register_batch(
|
||||
"labels",
|
||||
RecordBatch::try_new(
|
||||
schema,
|
||||
vec![
|
||||
input.clone(),
|
||||
Arc::new(Int32Array::from_iter_values(0..input.len() as i32)),
|
||||
],
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
for expr in &predicates {
|
||||
let df = ctx
|
||||
.table("labels")
|
||||
.await
|
||||
.unwrap()
|
||||
.filter(expr.clone())
|
||||
.unwrap();
|
||||
let plan = df.clone().into_optimized_plan().unwrap();
|
||||
let expected = df
|
||||
.collect()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch
|
||||
.column_by_name("id")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<Int32Array>()
|
||||
.unwrap()
|
||||
.values()
|
||||
.to_vec()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let evaluate = |expr: &Expr| {
|
||||
let evaluator =
|
||||
SimpleFilterEvaluator::try_new_with_column_type(expr, &|name| {
|
||||
(name == "label").then(|| input.data_type().clone())
|
||||
})
|
||||
.unwrap_or_else(|| panic!("unsupported: {expr}"));
|
||||
let mask = evaluator.evaluate_array(&input).unwrap();
|
||||
for (i, matched) in mask.iter().enumerate() {
|
||||
let scalar = ScalarValue::try_from_array(&input, i).unwrap();
|
||||
assert_eq!(
|
||||
evaluator.evaluate_scalar(&scalar).unwrap(),
|
||||
matched,
|
||||
"{expr}, row={i}"
|
||||
);
|
||||
}
|
||||
mask
|
||||
};
|
||||
let selected = |mask: BooleanBuffer| {
|
||||
mask.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, matched)| matched.then_some(i as i32))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(selected(evaluate(expr)), expected, "{expr}");
|
||||
let mut filters = Vec::new();
|
||||
plan.apply(|plan| {
|
||||
if let datafusion::logical_expr::LogicalPlan::Filter(filter) = plan {
|
||||
filters.push(filter.predicate.clone());
|
||||
}
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
})
|
||||
.unwrap();
|
||||
if !filters.is_empty() {
|
||||
let mut mask = BooleanBuffer::new_set(input.len());
|
||||
for filter in filters {
|
||||
mask = &mask & &evaluate(&filter);
|
||||
}
|
||||
assert_eq!(selected(mask), expected, "optimized: {plan}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_filter_op() {
|
||||
// equal
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::Column(Column::from_name("foo"))),
|
||||
op: Operator::Eq,
|
||||
right: Box::new(1.lit()),
|
||||
});
|
||||
let _ = SimpleFilterEvaluator::try_new(&expr).unwrap();
|
||||
|
||||
// swap operands
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(1.lit()),
|
||||
op: Operator::Lt,
|
||||
right: Box::new(Expr::Column(Column::from_name("foo"))),
|
||||
});
|
||||
let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
|
||||
assert!(evaluator.is_gt());
|
||||
assert_eq!(evaluator.column_name, "foo".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_on_array() {
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::Column(Column::from_name("foo"))),
|
||||
op: Operator::Eq,
|
||||
right: Box::new(1i64.lit()),
|
||||
});
|
||||
let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
|
||||
|
||||
let input_1 = Arc::new(datatypes::arrow::array::Int64Array::from(vec![1, 2, 3])) as _;
|
||||
let result = evaluator.evaluate_array(&input_1).unwrap();
|
||||
assert_eq!(result, BooleanBuffer::from(vec![true, false, false]));
|
||||
|
||||
let input_2 = Arc::new(datatypes::arrow::array::Int64Array::from(vec![1, 1, 1])) as _;
|
||||
let result = evaluator.evaluate_array(&input_2).unwrap();
|
||||
assert_eq!(result, BooleanBuffer::from(vec![true, true, true]));
|
||||
|
||||
let input_3 = Arc::new(datatypes::arrow::array::Int64Array::new_null(0)) as _;
|
||||
let result = evaluator.evaluate_array(&input_3).unwrap();
|
||||
assert_eq!(result, BooleanBuffer::from(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_on_scalar() {
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::Column(Column::from_name("foo"))),
|
||||
op: Operator::Lt,
|
||||
right: Box::new(1i64.lit()),
|
||||
});
|
||||
let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
|
||||
|
||||
let input_1 = ScalarValue::Int64(Some(1));
|
||||
let result = evaluator.evaluate_scalar(&input_1).unwrap();
|
||||
assert!(!result);
|
||||
|
||||
let input_2 = ScalarValue::Int64(Some(0));
|
||||
let result = evaluator.evaluate_scalar(&input_2).unwrap();
|
||||
assert!(result);
|
||||
|
||||
let input_3 = ScalarValue::Int64(None);
|
||||
let result = evaluator.evaluate_scalar(&input_3).unwrap();
|
||||
assert!(!result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_complex_filter_expression() {
|
||||
// Create an expression tree for: col = 'B' OR col = 'C' OR col = 'D'
|
||||
let col_eq_b = col("col").eq(lit("B"));
|
||||
let col_eq_c = col("col").eq(lit("C"));
|
||||
let col_eq_d = col("col").eq(lit("D"));
|
||||
|
||||
// Build the OR chain
|
||||
let col_or_expr = col_eq_b.or(col_eq_c).or(col_eq_d);
|
||||
|
||||
// Check that SimpleFilterEvaluator can handle OR chain
|
||||
let or_evaluator = SimpleFilterEvaluator::try_new(&col_or_expr).unwrap();
|
||||
assert_eq!(or_evaluator.column_name, "col");
|
||||
assert!(or_evaluator.is_or_eq_chain());
|
||||
assert_eq!(
|
||||
or_evaluator.literal_list_values().unwrap(),
|
||||
vec![Value::from("B"), Value::from("C"), Value::from("D")]
|
||||
);
|
||||
|
||||
// Create a schema and batch for testing
|
||||
let schema = Schema::new(vec![Field::new("col", DataType::Utf8, false)]);
|
||||
let df_schema = DFSchema::try_from(schema.clone()).unwrap();
|
||||
let props = ExecutionProps::new();
|
||||
let physical_expr = create_physical_expr(
|
||||
&col_or_expr,
|
||||
&df_schema,
|
||||
&props,
|
||||
&PhysicalPlanningContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Create test data
|
||||
let col_data = Arc::new(datatypes::arrow::array::StringArray::from(vec![
|
||||
"B", "C", "E", "B", "C", "D", "F",
|
||||
]));
|
||||
let batch = RecordBatch::try_new(Arc::new(schema), vec![col_data]).unwrap();
|
||||
let expected = datatypes::arrow::array::StringArray::from(vec!["B", "C", "B", "C", "D"]);
|
||||
|
||||
// Filter the batch
|
||||
let filtered_batch = batch_filter(&batch, &physical_expr).unwrap();
|
||||
|
||||
// Expected: rows with col in ("B", "C", "D")
|
||||
// That would be rows 0, 1, 3, 4, 5
|
||||
assert_eq!(filtered_batch.num_rows(), 5);
|
||||
|
||||
let col_filtered = filtered_batch
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<datatypes::arrow::array::StringArray>()
|
||||
.unwrap();
|
||||
assert_eq!(col_filtered, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_maybe_build_regex() {
|
||||
// Test case for RegexMatch (case sensitive, non-negative)
|
||||
let (regex, negative) = SimplePredicate::maybe_build_regex(
|
||||
Operator::RegexMatch,
|
||||
&ScalarValue::Utf8(Some("a.*b".to_string())),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(regex.is_some());
|
||||
assert!(!negative);
|
||||
assert!(regex.unwrap().is_match("axxb"));
|
||||
|
||||
// Test case for RegexIMatch (case insensitive, non-negative)
|
||||
let (regex, negative) = SimplePredicate::maybe_build_regex(
|
||||
Operator::RegexIMatch,
|
||||
&ScalarValue::Utf8(Some("a.*b".to_string())),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(regex.is_some());
|
||||
assert!(!negative);
|
||||
assert!(regex.unwrap().is_match("AxxB"));
|
||||
|
||||
// Test case for RegexNotMatch (case sensitive, negative)
|
||||
let (regex, negative) = SimplePredicate::maybe_build_regex(
|
||||
Operator::RegexNotMatch,
|
||||
&ScalarValue::Utf8(Some("a.*b".to_string())),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(regex.is_some());
|
||||
assert!(negative);
|
||||
|
||||
// Test case for RegexNotIMatch (case insensitive, negative)
|
||||
let (regex, negative) = SimplePredicate::maybe_build_regex(
|
||||
Operator::RegexNotIMatch,
|
||||
&ScalarValue::Utf8(Some("a.*b".to_string())),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(regex.is_some());
|
||||
assert!(negative);
|
||||
|
||||
// Test with empty regex pattern
|
||||
let (regex, negative) = SimplePredicate::maybe_build_regex(
|
||||
Operator::RegexMatch,
|
||||
&ScalarValue::Utf8(Some("".to_string())),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(regex.is_none());
|
||||
assert!(!negative);
|
||||
|
||||
// Test with non-regex operator
|
||||
let (regex, negative) = SimplePredicate::maybe_build_regex(
|
||||
Operator::Eq,
|
||||
&ScalarValue::Utf8(Some("a.*b".to_string())),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(regex.is_none());
|
||||
assert!(!negative);
|
||||
|
||||
// Test with invalid regex pattern
|
||||
let result = SimplePredicate::maybe_build_regex(
|
||||
Operator::RegexMatch,
|
||||
&ScalarValue::Utf8(Some("a(b".to_string())),
|
||||
);
|
||||
assert!(result.is_err());
|
||||
|
||||
// Test with non-string value
|
||||
let result = SimplePredicate::maybe_build_regex(
|
||||
Operator::RegexMatch,
|
||||
&ScalarValue::Int64(Some(123)),
|
||||
);
|
||||
assert!(result.is_err());
|
||||
|
||||
// Test with null value
|
||||
let result =
|
||||
SimplePredicate::maybe_build_regex(Operator::RegexMatch, &ScalarValue::Utf8(None));
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_regex_match_dictionary_array() {
|
||||
use datatypes::arrow::array::StringDictionaryBuilder;
|
||||
|
||||
// Create a StringDictionaryArray
|
||||
let mut builder = StringDictionaryBuilder::<UInt32Type>::new();
|
||||
builder.append("apple").unwrap();
|
||||
builder.append("banana").unwrap();
|
||||
builder.append("apple").unwrap();
|
||||
builder.append("cherry").unwrap();
|
||||
let dict_array = builder.finish();
|
||||
|
||||
// Test regex that matches "apple"
|
||||
let regex = regex::Regex::new(r"app.*").unwrap();
|
||||
let result = regexp_is_match_dictionary(&dict_array, Some(®ex)).unwrap();
|
||||
|
||||
// Should match indices 0 and 2 (both "apple")
|
||||
assert_eq!(result.len(), 4);
|
||||
assert!(result.value(0)); // "apple"
|
||||
assert!(!result.value(1)); // "banana"
|
||||
assert!(result.value(2)); // "apple"
|
||||
assert!(!result.value(3)); // "cherry"
|
||||
|
||||
// Test regex that matches "banana"
|
||||
let regex2 = regex::Regex::new(r"ban.*").unwrap();
|
||||
let result2 = regexp_is_match_dictionary(&dict_array, Some(®ex2)).unwrap();
|
||||
|
||||
assert!(!result2.value(0)); // "apple"
|
||||
assert!(result2.value(1)); // "banana"
|
||||
assert!(!result2.value(2)); // "apple"
|
||||
assert!(!result2.value(3)); // "cherry"
|
||||
|
||||
// Test with no regex (should match all)
|
||||
let result3 = regexp_is_match_dictionary(&dict_array, None).unwrap();
|
||||
assert!(result3.value(0));
|
||||
assert!(result3.value(1));
|
||||
assert!(result3.value(2));
|
||||
assert!(result3.value(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_regex_scan_masks_preserve_sql_null_semantics() {
|
||||
let plain = Arc::new(datatypes::arrow::array::StringArray::from(vec![
|
||||
Some("api"),
|
||||
Some("API"),
|
||||
Some("db"),
|
||||
None,
|
||||
])) as ArrayRef;
|
||||
assert_regex_scan_masks(
|
||||
&plain,
|
||||
[
|
||||
vec![true, false, false, false],
|
||||
vec![true, true, false, false],
|
||||
vec![false, true, true, false],
|
||||
vec![false, false, true, false],
|
||||
],
|
||||
);
|
||||
|
||||
let dictionary = DictionaryArray::new(
|
||||
datatypes::arrow::array::UInt32Array::from(vec![
|
||||
Some(0),
|
||||
Some(1),
|
||||
Some(2),
|
||||
None,
|
||||
Some(3),
|
||||
]),
|
||||
Arc::new(datatypes::arrow::array::StringArray::from(vec![
|
||||
Some("api"),
|
||||
Some("API"),
|
||||
Some("db"),
|
||||
None,
|
||||
])),
|
||||
);
|
||||
let raw =
|
||||
regexp_is_match_dictionary(&dictionary, Some(&Regex::new("^api$").unwrap())).unwrap();
|
||||
assert!(raw.is_null(3)); // null dictionary key
|
||||
assert!(raw.is_null(4)); // non-null key referencing a null dictionary value
|
||||
|
||||
let dictionary = Arc::new(dictionary) as ArrayRef;
|
||||
assert_regex_scan_masks(
|
||||
&dictionary,
|
||||
[
|
||||
vec![true, false, false, false, false],
|
||||
vec![true, true, false, false, false],
|
||||
vec![false, true, true, false, false],
|
||||
vec![false, false, true, false, false],
|
||||
],
|
||||
);
|
||||
|
||||
let negative = regex_evaluator(Operator::RegexNotMatch);
|
||||
assert!(!negative.evaluate_scalar(&ScalarValue::Utf8(None)).unwrap());
|
||||
}
|
||||
|
||||
fn assert_regex_scan_masks(input: &ArrayRef, expected: [Vec<bool>; 4]) {
|
||||
for (op, expected) in [
|
||||
Operator::RegexMatch,
|
||||
Operator::RegexIMatch,
|
||||
Operator::RegexNotMatch,
|
||||
Operator::RegexNotIMatch,
|
||||
]
|
||||
.into_iter()
|
||||
.zip(expected)
|
||||
{
|
||||
assert_eq!(
|
||||
BooleanBuffer::from(expected),
|
||||
regex_evaluator(op).evaluate_array(input).unwrap(),
|
||||
"{op:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn regex_evaluator(op: Operator) -> SimpleFilterEvaluator {
|
||||
let expr = Expr::BinaryExpr(BinaryExpr {
|
||||
left: Box::new(Expr::Column(Column::from_name("host"))),
|
||||
op,
|
||||
right: Box::new("^api$".lit()),
|
||||
});
|
||||
SimpleFilterEvaluator::try_new(&expr).unwrap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::execution::context::ExecutionProps;
|
||||
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
|
||||
use datafusion::logical_expr::{col, lit};
|
||||
use datafusion::physical_expr::create_physical_expr;
|
||||
use datafusion_common::DFSchema;
|
||||
use datatypes::arrow::datatypes::{DataType, Field, Schema};
|
||||
|
||||
use datatypes::arrow::array::{BooleanArray, RecordBatch};
|
||||
|
||||
use crate::filter::{batch_filter, boolean_array_to_scan_mask};
|
||||
|
||||
#[test]
|
||||
fn batch_filter_test() {
|
||||
let expr = col("ts").gt(lit(123456u64));
|
||||
let schema = Schema::new(vec![
|
||||
Field::new("a", DataType::Int32, true),
|
||||
Field::new("ts", DataType::UInt64, false),
|
||||
]);
|
||||
let df_schema = DFSchema::try_from(schema.clone()).unwrap();
|
||||
let props = ExecutionProps::new();
|
||||
let physical_expr = create_physical_expr(
|
||||
&expr,
|
||||
&df_schema,
|
||||
&props,
|
||||
&PhysicalPlanningContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let batch = RecordBatch::try_new(
|
||||
Arc::new(schema),
|
||||
vec![
|
||||
Arc::new(datatypes::arrow::array::Int32Array::from(vec![4, 5, 6])),
|
||||
Arc::new(datatypes::arrow::array::UInt64Array::from(vec![
|
||||
123456, 123457, 123458,
|
||||
])),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let new_batch = batch_filter(&batch, &physical_expr).unwrap();
|
||||
assert_eq!(new_batch.num_rows(), 2);
|
||||
let first_column_values = new_batch
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<datatypes::arrow::array::Int32Array>()
|
||||
.unwrap();
|
||||
let expected = datatypes::arrow::array::Int32Array::from(vec![5, 6]);
|
||||
assert_eq!(first_column_values, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nullable_boolean_predicate_becomes_scan_mask() {
|
||||
let predicate = BooleanArray::from(vec![Some(true), None, Some(false)]);
|
||||
assert_eq!(
|
||||
BooleanArray::from(vec![true, false, false]),
|
||||
boolean_array_to_scan_mask(&predicate)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Timestamp-unit adaptation for predicates evaluated against historical SSTs.
|
||||
|
||||
use common_time::timestamp::div_mod_units;
|
||||
use datafusion::logical_expr::Operator;
|
||||
use datafusion_common::ScalarValue;
|
||||
use datafusion_common::arrow::array::{ArrayRef, Datum, Scalar};
|
||||
use datatypes::arrow::datatypes::TimeUnit;
|
||||
|
||||
use crate::filter::predicate::SimplePredicate;
|
||||
|
||||
/// Builds a tz-naive timestamp literal for `value` in `unit`.
|
||||
pub fn timestamp_scalar_value(value: i64, unit: TimeUnit) -> ScalarValue {
|
||||
match unit {
|
||||
TimeUnit::Second => ScalarValue::TimestampSecond(Some(value), None),
|
||||
TimeUnit::Millisecond => ScalarValue::TimestampMillisecond(Some(value), None),
|
||||
TimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(Some(value), None),
|
||||
TimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(Some(value), None),
|
||||
}
|
||||
}
|
||||
|
||||
impl SimplePredicate {
|
||||
pub(crate) fn cast_timestamp_unit(&self, target_unit: TimeUnit) -> Option<Self> {
|
||||
// Constants represent scan outcomes here. As in the public Matched/Pruned
|
||||
// result, UNKNOWN can be collapsed to false under these AND/OR-only trees.
|
||||
match self {
|
||||
Self::And(left, right) | Self::Or(left, right) => {
|
||||
let left = left.cast_timestamp_unit(target_unit)?;
|
||||
let right = right.cast_timestamp_unit(target_unit)?;
|
||||
let and = matches!(self, Self::And(..));
|
||||
Some(match (left, right) {
|
||||
(Self::Constant(Some(false)), _) | (_, Self::Constant(Some(false))) if and => {
|
||||
Self::Constant(Some(false))
|
||||
}
|
||||
(Self::Constant(Some(true)), _) | (_, Self::Constant(Some(true))) if !and => {
|
||||
Self::Constant(Some(true))
|
||||
}
|
||||
(Self::Constant(Some(true)), other) | (other, Self::Constant(Some(true)))
|
||||
if and =>
|
||||
{
|
||||
other
|
||||
}
|
||||
(Self::Constant(Some(false)), other) | (other, Self::Constant(Some(false)))
|
||||
if !and =>
|
||||
{
|
||||
other
|
||||
}
|
||||
(left, right) => {
|
||||
if and {
|
||||
Self::And(Box::new(left), Box::new(right))
|
||||
} else {
|
||||
Self::Or(Box::new(left), Box::new(right))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
Self::IsNull { .. } => Some(self.clone()),
|
||||
Self::Constant(value) => Some(Self::Constant(Some(value.unwrap_or(false)))),
|
||||
Self::OrEqChain { literals } => {
|
||||
let mut converted = Vec::with_capacity(literals.len());
|
||||
for literal in literals {
|
||||
let scalar = ScalarValue::try_from_array(literal.get().0, 0).ok()?;
|
||||
let (value, unit) = timestamp_scalar_parts(&scalar)?;
|
||||
let Some(value) = value else {
|
||||
continue;
|
||||
};
|
||||
let cast = div_mod_units(value, unit.into(), target_unit.into())?;
|
||||
if cast.remainder == 0 {
|
||||
converted.push(timestamp_scalar(cast.quotient, target_unit)?);
|
||||
}
|
||||
}
|
||||
if converted.is_empty() {
|
||||
return Some(Self::Constant(Some(false)));
|
||||
}
|
||||
Some(Self::OrEqChain {
|
||||
literals: converted,
|
||||
})
|
||||
}
|
||||
Self::Comparison { literal, op, .. } => {
|
||||
let scalar = ScalarValue::try_from_array(literal.get().0, 0).ok()?;
|
||||
let (value, unit) = timestamp_scalar_parts(&scalar)?;
|
||||
let Some(value) = value else {
|
||||
return Some(Self::Constant(Some(false)));
|
||||
};
|
||||
if unit == target_unit {
|
||||
return Some(self.clone());
|
||||
}
|
||||
let cast = div_mod_units(value, unit.into(), target_unit.into())?;
|
||||
let divisible = cast.remainder == 0;
|
||||
let literal = timestamp_scalar(cast.quotient, target_unit)?;
|
||||
let filter = |op| Self::Comparison {
|
||||
literal: literal.clone(),
|
||||
op,
|
||||
regex: None,
|
||||
regex_negative: false,
|
||||
};
|
||||
Some(match op {
|
||||
Operator::Eq if divisible => filter(Operator::Eq),
|
||||
Operator::Eq => Self::Constant(Some(false)),
|
||||
Operator::NotEq if divisible => filter(Operator::NotEq),
|
||||
Operator::NotEq => Self::Constant(Some(true)),
|
||||
// The quotient is floor(L), including negative timestamps.
|
||||
// v > L is v > quotient whether or not L is representable.
|
||||
Operator::Gt => filter(Operator::Gt),
|
||||
Operator::GtEq if divisible => filter(Operator::GtEq),
|
||||
// Between target values, v >= L is v > quotient.
|
||||
Operator::GtEq => filter(Operator::Gt),
|
||||
Operator::Lt if divisible => filter(Operator::Lt),
|
||||
// Between target values, v < L is v <= quotient.
|
||||
Operator::Lt => filter(Operator::LtEq),
|
||||
Operator::LtEq => filter(Operator::LtEq),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts the value and unit from a tz-naive timestamp scalar.
|
||||
fn timestamp_scalar_parts(scalar: &ScalarValue) -> Option<(Option<i64>, TimeUnit)> {
|
||||
let (value, unit, timezone) = match scalar {
|
||||
ScalarValue::TimestampSecond(v, tz) => (*v, TimeUnit::Second, tz),
|
||||
ScalarValue::TimestampMillisecond(v, tz) => (*v, TimeUnit::Millisecond, tz),
|
||||
ScalarValue::TimestampMicrosecond(v, tz) => (*v, TimeUnit::Microsecond, tz),
|
||||
ScalarValue::TimestampNanosecond(v, tz) => (*v, TimeUnit::Nanosecond, tz),
|
||||
_ => return None,
|
||||
};
|
||||
// A timezone-aware literal doesn't compare against a tz-naive column;
|
||||
// leave it to the caller instead of guessing the intended semantics.
|
||||
(timezone.is_none()).then_some((value, unit))
|
||||
}
|
||||
|
||||
/// Builds a one-element scalar array holding `value` in `unit`.
|
||||
fn timestamp_scalar(value: i64, unit: TimeUnit) -> Option<Scalar<ArrayRef>> {
|
||||
timestamp_scalar_value(value, unit).to_scalar().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::execution::context::ExecutionProps;
|
||||
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
|
||||
use datafusion::logical_expr::{Expr, col, lit};
|
||||
use datafusion::physical_expr::create_physical_expr;
|
||||
use datafusion_common::arrow::array::ArrayRef;
|
||||
use datafusion_common::arrow::buffer::BooleanBuffer;
|
||||
use datafusion_common::cast::as_boolean_array;
|
||||
use datafusion_common::{DFSchema, ScalarValue};
|
||||
use datatypes::arrow::array::{
|
||||
RecordBatch, TimestampMillisecondArray, TimestampNanosecondArray,
|
||||
};
|
||||
use datatypes::arrow::datatypes::{Field, Schema};
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
|
||||
use crate::filter::{SimpleFilterEvaluator, TimestampUnitCast, boolean_array_to_scan_mask};
|
||||
|
||||
#[test]
|
||||
fn compound_timestamp_filters_preserve_unit_conversion() {
|
||||
use datatypes::arrow::array::TimestampMicrosecondArray;
|
||||
|
||||
let null = || lit(ScalarValue::TimestampMicrosecond(None, None));
|
||||
let predicates = [
|
||||
col("ts")
|
||||
.gt(lit(ts_us(-1500)))
|
||||
.and(col("ts").lt(lit(ts_us(500)))),
|
||||
col("ts")
|
||||
.eq(lit(ts_us(500)))
|
||||
.or(col("ts").gt_eq(lit(ts_us(1500)))),
|
||||
col("ts")
|
||||
.is_not_null()
|
||||
.and(col("ts").not_eq(lit(ts_us(500)))),
|
||||
col("ts").eq(null()).or(col("ts").eq(lit(ts_us(-1000)))),
|
||||
col("ts")
|
||||
.eq(lit(ts_us(500)))
|
||||
.and(col("ts").gt(lit(ts_us(0)))),
|
||||
col("ts")
|
||||
.not_eq(lit(ts_us(500)))
|
||||
.or(col("ts").lt(lit(ts_us(0)))),
|
||||
];
|
||||
let native: ArrayRef = Arc::new(TimestampMicrosecondArray::from(vec![
|
||||
-2000, -1000, 0, 1000, 2000,
|
||||
]));
|
||||
let old: ArrayRef = Arc::new(TimestampMillisecondArray::from(vec![-2, -1, 0, 1, 2]));
|
||||
let schema = Arc::new(Schema::new(vec![Field::new(
|
||||
"ts",
|
||||
native.data_type().clone(),
|
||||
false,
|
||||
)]));
|
||||
let batch = RecordBatch::try_new(schema.clone(), vec![native]).unwrap();
|
||||
for expr in predicates {
|
||||
let physical = create_physical_expr(
|
||||
&expr,
|
||||
&DFSchema::try_from(schema.as_ref().clone()).unwrap(),
|
||||
&ExecutionProps::new(),
|
||||
&PhysicalPlanningContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let result = physical
|
||||
.evaluate(&batch)
|
||||
.unwrap()
|
||||
.into_array(batch.num_rows())
|
||||
.unwrap();
|
||||
let expected = boolean_array_to_scan_mask(as_boolean_array(&result).unwrap())
|
||||
.values()
|
||||
.clone();
|
||||
let actual = match cast_to_ms(&expr).unwrap() {
|
||||
TimestampUnitCast::Matched => BooleanBuffer::new_set(old.len()),
|
||||
TimestampUnitCast::Pruned => BooleanBuffer::new_unset(old.len()),
|
||||
TimestampUnitCast::Filter(filter) => filter.evaluate_array(&old).unwrap(),
|
||||
};
|
||||
assert_eq!(actual, expected, "{expr}");
|
||||
}
|
||||
}
|
||||
|
||||
fn ts_us(v: i64) -> ScalarValue {
|
||||
ScalarValue::TimestampMicrosecond(Some(v), None)
|
||||
}
|
||||
|
||||
fn cast_to_ms(expr: &Expr) -> Option<TimestampUnitCast> {
|
||||
SimpleFilterEvaluator::try_new(expr)
|
||||
.unwrap()
|
||||
.cast_timestamp_unit(&ConcreteDataType::timestamp_millisecond_datatype())
|
||||
}
|
||||
|
||||
/// Evaluates a cast `Filter` outcome against millisecond values and
|
||||
/// returns the mask.
|
||||
fn eval_ms_mask(cast: Option<TimestampUnitCast>, values: &[i64]) -> Vec<bool> {
|
||||
let filter = match cast.expect("cast must apply") {
|
||||
TimestampUnitCast::Filter(filter) => filter,
|
||||
other => panic!("expected Filter outcome, got {other:?}"),
|
||||
};
|
||||
let array = Arc::new(TimestampMillisecondArray::from(values.to_vec())) as ArrayRef;
|
||||
filter.evaluate_array(&array).unwrap().iter().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_converts_representable_literal() {
|
||||
// ts = 7_000_000us evaluated against a ms column becomes ts = 7000ms.
|
||||
assert_eq!(
|
||||
vec![false, true, false],
|
||||
eval_ms_mask(
|
||||
cast_to_ms(&col("ts").eq(lit(ts_us(7_000_000)))),
|
||||
&[6_999, 7_000, 7_001]
|
||||
)
|
||||
);
|
||||
// != complements =.
|
||||
assert_eq!(
|
||||
vec![true, false, true],
|
||||
eval_ms_mask(
|
||||
cast_to_ms(&col("ts").not_eq(lit(ts_us(7_000_000)))),
|
||||
&[6_999, 7_000, 7_001]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_prunes_non_representable_equality() {
|
||||
// 7_000_500us is not a whole millisecond: no ms row can equal it,
|
||||
// and every ms row satisfies `!=`.
|
||||
assert!(matches!(
|
||||
cast_to_ms(&col("ts").eq(lit(ts_us(7_000_500)))),
|
||||
Some(TimestampUnitCast::Pruned)
|
||||
));
|
||||
assert!(matches!(
|
||||
cast_to_ms(&col("ts").not_eq(lit(ts_us(7_000_500)))),
|
||||
Some(TimestampUnitCast::Matched)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_strengthens_inequalities() {
|
||||
// 2_500_500us is strictly between 2500ms and 2501ms: the cast must
|
||||
// not round the literal to a boundary the original predicate
|
||||
// excludes (>= 2500ms would wrongly match 2500ms).
|
||||
let values = vec![2_499, 2_500, 2_501];
|
||||
assert_eq!(
|
||||
vec![false, false, true],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").gt(lit(ts_us(2_500_500)))), &values)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![false, false, true],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").gt_eq(lit(ts_us(2_500_500)))), &values)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![true, true, false],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").lt(lit(ts_us(2_500_500)))), &values)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![true, true, false],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").lt_eq(lit(ts_us(2_500_500)))), &values)
|
||||
);
|
||||
|
||||
// Representable boundary keeps the original operator.
|
||||
let values = vec![2_499, 2_500, 2_501];
|
||||
assert_eq!(
|
||||
vec![false, false, true],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").gt(lit(ts_us(2_500_000)))), &values)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![false, true, true],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").gt_eq(lit(ts_us(2_500_000)))), &values)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![true, false, false],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").lt(lit(ts_us(2_500_000)))), &values)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![true, true, false],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").lt_eq(lit(ts_us(2_500_000)))), &values)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_handles_negative_instants() {
|
||||
// -2_500_500us floors to -2501ms with remainder 500us: only rows
|
||||
// with instant >= -2.5005ms may match >= / >.
|
||||
let values = vec![-2_502, -2_501, -2_500];
|
||||
assert_eq!(
|
||||
vec![false, false, true],
|
||||
eval_ms_mask(
|
||||
cast_to_ms(&col("ts").gt_eq(lit(ts_us(-2_500_500)))),
|
||||
&values
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![false, false, true],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").gt(lit(ts_us(-2_500_500)))), &values)
|
||||
);
|
||||
assert_eq!(
|
||||
vec![true, true, false],
|
||||
eval_ms_mask(
|
||||
cast_to_ms(&col("ts").lt_eq(lit(ts_us(-2_500_500)))),
|
||||
&values
|
||||
)
|
||||
);
|
||||
// Exactly representable negative literal: -2_500_000us == -2500ms.
|
||||
assert_eq!(
|
||||
vec![false, false, true],
|
||||
eval_ms_mask(cast_to_ms(&col("ts").eq(lit(ts_us(-2_500_000)))), &values)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_or_chain_drops_unrepresentable_literals() {
|
||||
// Only 7_000_000us is a whole millisecond; 7_000_500us cannot match.
|
||||
let expr = col("ts")
|
||||
.eq(lit(ts_us(7_000_500)))
|
||||
.or(col("ts").eq(lit(ts_us(7_000_000))));
|
||||
assert_eq!(
|
||||
vec![false, true],
|
||||
eval_ms_mask(cast_to_ms(&expr), &[6_999, 7_000])
|
||||
);
|
||||
|
||||
// A chain where no literal is representable matches nothing.
|
||||
let expr = col("ts")
|
||||
.eq(lit(ts_us(7_000_500)))
|
||||
.or(col("ts").eq(lit(ts_us(6_000_500))));
|
||||
assert!(matches!(cast_to_ms(&expr), Some(TimestampUnitCast::Pruned)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_null_literal_prunes() {
|
||||
// A NULL literal never compares true.
|
||||
assert!(matches!(
|
||||
cast_to_ms(&col("ts").eq(lit(ScalarValue::TimestampMicrosecond(None, None)))),
|
||||
Some(TimestampUnitCast::Pruned)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_same_unit_returns_filter_directly() {
|
||||
// A literal already in the target unit is returned unchanged.
|
||||
let expr = col("ts").eq(lit(ts_us(7_000_000)));
|
||||
let filter = SimpleFilterEvaluator::try_new(&expr).unwrap();
|
||||
let cast = filter
|
||||
.cast_timestamp_unit(&ConcreteDataType::timestamp_microsecond_datatype())
|
||||
.unwrap();
|
||||
let TimestampUnitCast::Filter(f) = cast else {
|
||||
panic!("expected Filter, got {cast:?}")
|
||||
};
|
||||
assert!(filter.is_eq() && f.is_eq());
|
||||
assert_eq!(filter.column_name(), f.column_name());
|
||||
assert_eq!(filter.literal_value(), f.literal_value());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_rejects_non_timestamps() {
|
||||
// Non-timestamp target type.
|
||||
assert!(
|
||||
SimpleFilterEvaluator::try_new(&col("ts").gt(lit(ts_us(1))))
|
||||
.unwrap()
|
||||
.cast_timestamp_unit(&ConcreteDataType::int64_datatype())
|
||||
.is_none()
|
||||
);
|
||||
// Non-timestamp literal against a timestamp target.
|
||||
assert!(cast_to_ms(&col("ts").gt(lit(42_i64))).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_timestamp_unit_to_finer_unit() {
|
||||
// 5 seconds against a nanosecond column becomes 5_000_000_000ns.
|
||||
let filter = SimpleFilterEvaluator::try_new(
|
||||
&col("ts").eq(lit(ScalarValue::TimestampSecond(Some(5), None))),
|
||||
)
|
||||
.unwrap()
|
||||
.cast_timestamp_unit(&ConcreteDataType::timestamp_nanosecond_datatype())
|
||||
.and_then(|cast| match cast {
|
||||
TimestampUnitCast::Filter(filter) => Some(filter),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let array = Arc::new(TimestampNanosecondArray::from(vec![
|
||||
4_999_999_999,
|
||||
5_000_000_000,
|
||||
])) as ArrayRef;
|
||||
assert_eq!(
|
||||
vec![false, true],
|
||||
filter
|
||||
.evaluate_array(&array)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -30,12 +30,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
println!("cargo:rerun-if-env-changed=RUSTC");
|
||||
println!("cargo:rerun-if-env-changed=GREPTIME_PRODUCT_NAME");
|
||||
println!("cargo:rerun-if-env-changed=CARGO_WORKSPACE_DIR");
|
||||
|
||||
// The "CARGO_WORKSPACE_DIR" is set manually (not by Rust itself) in Cargo config file, to
|
||||
// solve the problem where the "CARGO_MANIFEST_DIR" is not what we want when this repo is
|
||||
// made as a submodule in another repo.
|
||||
let workspace_dir =
|
||||
env::var("CARGO_WORKSPACE_DIR").or_else(|_| env::var("CARGO_MANIFEST_DIR"))?;
|
||||
// Resolve the workspace root from CARGO_MANIFEST_DIR (this crate is
|
||||
// src/common/version, three levels below the root). The path remains absolute
|
||||
// and is used at build time. CARGO_WORKSPACE_DIR remains an explicit override
|
||||
// for submodule builds; see https://github.com/rust-lang/cargo/issues/3946.
|
||||
let workspace_dir = match env::var("CARGO_WORKSPACE_DIR") {
|
||||
Ok(dir) if !dir.is_empty() => dir,
|
||||
_ => env::var("CARGO_MANIFEST_DIR").map(|dir| {
|
||||
PathBuf::from(dir)
|
||||
.join("../../..")
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})?,
|
||||
};
|
||||
let workspace_root = PathBuf::from(&workspace_dir);
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
|
||||
Reference in New Issue
Block a user