Commit Graph
6853 Commits
Author SHA1 Message Date
discord9 4a1c8340a0 test(frontend): cover TTL rollup cache and perf (#10799)
* test(frontend): cover TTL rollup cache and perf

Signed-off-by: discord9 <discord9@163.com>

* test(integration): drop the rollup cache reset token

#10570 removed RollupCacheOptions::reset_token: the reset is the debug
endpoint behind the existing auth, and no test here read the token. The
field made tests-integration fail to compile against the current cache.

Signed-off-by: discord9 <discord9@163.com>

* test(frontend): follow the promql_rollup_cache rename

Adapt the rollup cache E2E tests and the perf harness to the parent's
promql_rollup_cache rename, including the rendered [promql_rollup_cache]
configuration table: a case that rendered [rollup_cache] would have measured
two uncached frontends while presenting itself as a cache measurement.

The parent's twenty-step chunk floor also changes the geometry the tests and
the case describe, so the E2E data window moves to 20..65 minutes to still hold
a whole canonical chunk, and the perf case comment now states the three
100-minute chunks and thirteen direct points. Every asserted value and every
latency threshold is unchanged.

Signed-off-by: discord9 <discord9@163.com>

* perf(test): render only the rollup cache fields a case sets

Signed-off-by: discord9 <discord9@163.com>

* test(integration): drop the redundant rollup cache expiry test

Signed-off-by: discord9 <discord9@163.com>

* docs(test): trim rollup cache perf prose

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-03 03:58:41 +00:00
dennis zhuang de1414bf77 refactor(servers): share numeric and type-mismatch handling in PostgreSQL parameter conversion (#10844)
* test(servers): pin PostgreSQL parameter conversion for every client type

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(servers): share numeric, list and type-mismatch handling in PostgreSQL parameter conversion

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(servers): fold PostgreSQL parameter tests into one compact table

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(servers): restore the INT8 array parameter case and assert the SQLSTATE

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-03 02:56:39 +00:00
dennis zhuang 442188319c test(promql): make planner test assertions able to fail (#10846)
* test(promql): make planner test assertions able to fail

- Replace 14 #[should_panic] planner tests that passed on any outcome
  (empty plan name, mismatched output type) with full plan assertions.
- Assert the published value column's type instead of finding a column
  by that type and re-checking it; drop the observer assertions in
  http.rs that re-check the name the observer already filtered on.
- Tighten a `contains("false")` check to `Boolean(false)`.
- Format the plan in panic messages that used literal braces in expect().
- Align test names and docs with what they assert for label rewrites
  and native histogram aggregates.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): keep expect with plain messages and drop observer name checks

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-03 02:33:57 +00:00
dennis zhuang 3a99741c29 refactor(query): remove dead code, duplicate tests and stale comments in dist_plan (#10845)
- Make TransformedCommutative's transformer non-optional and drop
  StepTransformAction and partial_commutative_transformer.
- Remove the unused original_column_for and the test-only copy of
  remove_if_dropped_registry.
- Drop an ignored test and tests duplicated by stronger ones; fold the
  ScheduledTimeExtension-without-time case into the now() test.
- Keep the MergeSortExec opacity rationale once and drop change-history
  comments.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 18:28:29 +00:00
Yingwen a6ca1de729 feat(mito2)!: add short-series IPC storage for Narthex (#10814)
* feat(mito2): store short Narthex series in Arrow IPC pages

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito2): share inline tails across Narthex sample layouts

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito2): key sample tails by region file ID

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito2): narrow IPC scope and consolidate artifact metadata

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito2): read sample sizes from the SST inventory

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito2): keep memory sample tails with their bytes

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): use crate-qualified imports in sample IPC codec

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): compile sample key helper only in unit tests

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): bound Narthex IPC pages and reads

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito-codec)!: cap sparse primary keys at 16 MiB

BREAKING CHANGE: Newly encoded sparse primary keys omit the first label that exceeds the key budget and all following labels. Oversized pre-encoded keys are rejected at write admission.

Signed-off-by: evenyag <realevenyag@gmail.com>

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
2026-12-02 18:28:16 +00:00
discord9 6d38bd32d0 refactor(promql): drop a dead split gate and narrow two sub-millisecond histogram refusals (#10813)
* refactor(promql): drop a dead split gate and narrow two sub-millisecond histogram refusals

- Remove `split_aggregate_folds_float_state_only`. The refused shape
  (histogram root over a cut that exports float state) is unreachable:
  the compiler binds `BoundAggregate.field_kind` from the aggregate's
  direct input, only `Sum`/`Avg × Histogram` yields a histogram state,
  and a successful split cuts exactly one aggregate, so a float cut
  can never sit under a histogram root.
- Move `histogram_over_a_sub_millisecond_time_index` from selector
  preparation to the Window node. The old check refused every native
  histogram read over a microsecond/nanosecond time index, including
  pure instant queries (`avg(h)`, `count(h)`, `h @ 5`) that the Instant
  node answers correctly. It now refuses only a Window whose direct
  input is a raw histogram sample stream: raw ingest keeps no window
  time beside a histogram payload, which `RangeEvaluator::ingest` needs.
  Keyed on the units bound into the tree, so it covers mito raw scans
  and file-engine row sources alike.
- Rename `range_modifier_over_a_sub_millisecond_time_index` to
  `experimental_range_modifier_over_a_sub_millisecond_time_index`: it
  refuses `anchored`/`smoothed` windows, not `@`/`offset`, which are
  applied on raw ticks before payloads are formed.

Add planner tests for the narrowed gate: `avg(h)` over a microsecond
histogram is admitted; `count_over_time(h[5m])` is still refused.

Signed-off-by: discord9 <discord9@163.com>

* test(promql): execute a microsecond native histogram avg against the existing plan

The planner test only checks that `avg(h)` over a microsecond native
histogram column is admitted; the shape moved from a planning-time
decline to native execution, and nothing executed it. Add it to the
sub-millisecond execution parity test: two series, two steps, the
answer's `count`/`sum` asserted against hand-computed means for both
routes, and the native run verified to carry a fused node.

On main the query is refused with `histogram_over_a_sub_millisecond_time_index`
(the old selector-stage gate), so the case is red there.

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-02 18:28:12 +00:00
discord9 47f526e9bf feat(promql): narrow a __field__ scan, and declare the kind a broadcast answers (#10655)
* feat(promql): answer __field__ selectors and same-metric `or` groups natively

Let the native route plan three shapes it used to hand back:

- `__field__` selection (`m{__field__="f"}`) on mito raw scans, metric
  logical scans and file-engine row sources: the scan is narrowed to the
  selected fields (`field_first_projection`) so `RawSeriesSource` still
  sees exactly the canonical frame, text columns are refused as value
  kinds, and a matcher naming a column the selection drops is refused
  (`row_matchers_need_a_dropped_column`) instead of degrading to a
  literal `"" = …` that silently answers nothing.
- `or` groups within one metric (`m{host="a" or host="b"}`) as one scan
  with one `Filter`: `AlternativeFilters` merges the groups' conjuncts,
  groups that select different fields or tables are refused, and
  `discovers_metric_name` learns the alternative groups so the
  authorization layer and the planner agree on what a selector
  discovers.
- A scalar operand in a composed binary (`(hist * on(job) floats) * 2`):
  `native_scalar_operand` binds a scalar side that the composed path
  previously required to be a frame.

`field_columns_selected_by` is extracted in `planner.rs` so the legacy
and native routes select the same columns; as a side effect the legacy
route's value-column order for a multi-field `__field__` selection goes
from HashSet order to table order.

Signed-off-by: discord9 <discord9@163.com>

* refactor(promql): share the scalar-binary binder and refuse a histogram over a dynamic scalar

- Fold the composed path's `bind_evaluated_broadcast` into a single
  `bind_scalar_binary` shared with `binary_operation`'s scalar tail;
  both carry the same modifier refusal and `broadcast(...)` call.
- In `try_plan_native_composed_binary`, decline a histogram frame met
  by a *dynamic* scalar (`(hist * on(job) floats) / time()`) with
  `histogram_over_a_dynamic_scalar`: the runtime refuses non-float
  samples on that branch instead of dropping them. A constant scalar
  (`* 2`) keeps planning natively. The refusal can go once the
  histogram-aware dynamic kernel lands separately.
- Adapt the tests to the rebased base (#10701): a decline is now an
  error carrying its cause, so the `plan_or_refusal` sites assert
  `native_decline_reason(..)` and the integration rows that used to
  unwrap a declined output assert the cause.

Signed-off-by: discord9 <discord9@163.com>

* refactor(promql): say a refusal is an error and drop the dead pre-or matcher loop

Review follow-ups:

- `histogram_over_a_dynamic_scalar` refused because the dynamic-scalar
  kernel on main errors on a non-float sample (#10812), not because
  Prometheus lacks a per-point histogram scale — it has one (`h / time()`).
  Comment and the three test docs now say so and reference #10812.
- Since #10701 a decline is a planning error with its cause; nothing
  falls back to the existing plan. Reword the doc comments and test
  docs that still described a fallback.
- `native_promql_or_matchers_narrow_the_scan` asserted the existing
  plan's rows for `{host="a" or host="b"}`, which answers `c`: the
  parser moves the pre-`or` matchers into the first group and
  `matchers_to_expr` reads `matchers.matchers` only, so the existing
  plan applies none of them. That is the existing plan's bug, filed
  separately; the test no longer states it as an expectation and keeps
  only the route check.
- `AlternativeFilters::of_selector` looped over `selector.matchers.matchers`
  before the group loop; with any `or` that list is empty, and if it
  were not the loop would silently drop every non-selection matcher.
  Removed.

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-02 18:27:50 +00:00
dennis zhuang cd3406a0db refactor(promql): read evaluated and raw repartition chains with one loop (#10841)
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 15:20:21 +00:00
dennis zhuang 42e96e5bd9 fix(servers): spell Prometheus infinities as +Inf and keep Jaeger tags per trace (#10823)
* fix(servers): spell infinite Prometheus samples as +Inf and keep Jaeger process tags per trace

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* perf(servers): serialize non-finite Prometheus samples from static strings

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 13:06:18 +00:00
dennis zhuang 99784fe803 fix(mito2): count written bytes of single-part bulk inserts (#10824)
* fix(mito2): count written bytes of single-part bulk inserts

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(mito2): assert the exact written bytes of a single-part bulk insert

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 13:05:43 +00:00
dennis zhuang 587677371c fix(promql): report a zero subquery step inside range functions as such (#10828)
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 12:38:40 +00:00
dennis zhuang 0f6a9b3d6e chore: catch unused snafu variants shadowed by other crates and remove them (#10826)
* chore: catch unused snafu variants shadowed by other crates and remove them

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix: count shorthand variant constructions in error files as uses

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix: parse nested expressions and literals when telling variant constructions from patterns

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 12:18:45 +00:00
discord9 76209d6179 feat(frontend): add TTL-based PromQL range cache (#10798)
* feat(frontend): add TTL-based PromQL range cache

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): add rollup cache reset endpoint

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): honor nocache for rollup cache

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): key rollup cache by table id and invalidate on DDL

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): set transitional rollup cache bounds

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): trim rollup cache to ttl and reset

Remove the reset token and all DDL/heartbeat invalidation so the
transitional cache has one freshness rule (ttl) and one manual escape
(reset). Charge variable-sized keys, honor POST-form nocache, fail on
schema changes instead of falling back, and drop duplicate TTL/dead
checks.

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): drop stale invalidation wording

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): bound rollup cache key and weight

Share one QueryIdentity across a plan's chunk keys, refuse chunks whose
weight does not fit a u32, and reject ttl values longer than moka accepts.
Clarify schema-mismatch and wall-clock tail docs.

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): regenerate config.md for rollup_cache tail

config/config.md was hand-updated and kept the previous wording of the
rollup_cache.tail comment. Run make config-docs so it matches the example
TOMLs, which is what CI checks.

Signed-off-by: discord9 <discord9@163.com>

* test(integration): expect rollup_cache in the /config snapshot

test_config_api compares the whole TOML the /config endpoint returns with a
hardcoded expectation. The rollup cache adds a [rollup_cache] section, so
append it with the values the frontend defaults serialize to.

Signed-off-by: discord9 <discord9@163.com>

* refactor(frontend): rename rollup cache to promql_rollup_cache

Rename the config key, the options and config types, the cache itself,
the instance accessors, the reset endpoint and the session hint so the
name says what is cached. query_cache becomes promql_query_cache for the
same reason: it holds PromQL range-query chunks only.

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): log the promql rollup cache config when enabled

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): size the promql rollup cache from system memory by default

Derive max_bytes from total memory like the OTLP trace aux cache
(1/128, floor 32MiB, cap 8GiB) instead of a fixed 256MiB, so a small
frontend does not give up a quarter of its memory and a large host gets
a useful budget. An explicit max_bytes still wins.

Signed-off-by: discord9 <discord9@163.com>

* refactor(frontend): move the promql rollup cache wiring out of instance.rs

Signed-off-by: discord9 <discord9@163.com>

* refactor(query): expose plan_is_native from the native planner

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): key promql rollup cache chunks on the output schema

The metric engine auto-alters a logical table when a new label arrives,
which keeps the table id but changes the schema. Keying on the id alone
let one request meet an old-schema hit with a new-schema fill and fail
until the ttl. The output schema of the built plan is now a key
dimension, so a schema change misses; a disagreement left after that is
a race with an ALTER, and the request bypasses to its original plan
instead of failing.

Signed-off-by: discord9 <discord9@163.com>

* perf(frontend): execute consecutive promql rollup cache misses as one window

A cold request executed every missed chunk as its own subwindow, each
re-reading the range its first point folds. Consecutive misses now run
as one window and the rows are split back into chunks before insert.

Signed-off-by: discord9 <discord9@163.com>

* perf(frontend): size promql rollup cache chunks in steps and drop empty-chunk guards

A fixed-time chunk holds chunk/step points and degrades to one point at
a large step: a 7d panel at a 10m step became 1008 single-point chunks
that all had to be looked up and merged even when warm. A chunk is now
at least MIN_CHUNK_STEPS points wide, so the chunk count tracks points
rather than range (7d at 10m: 50 chunks).

plan_chunks never emits an empty chunk, so the guards in lookup and
insert, the EmptyChunk bypass, Lookup::Bypass and Insert::Bypassed are
gone along with the two tests that built an empty key by hand.

Also applies the reviewer's doc suggestions and dedupes the tests that
asserted one behavior at three layers.

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): regenerate config.md for promql_rollup_cache

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): copy split promql rollup cache chunks before storing them

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): store empty promql rollup cache chunks as complete answers

Signed-off-by: discord9 <discord9@163.com>

* refactor(frontend): key the promql rollup cache on the arrow schema directly

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): only bypass the promql rollup cache for a set nocache hint

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): record that rollup cache annotations belong to the read

Signed-off-by: discord9 <discord9@163.com>

* perf(frontend): read contiguous direct spans as one window

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): fix stale rollup cache comments and pin lookback_ms

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-02 12:05:25 +00:00
Vishal Kotakanddennis zhuang d5ad08c1e3 fix: use local midnight as the default range ALIGN TO origin (#10795)
Signed-off-by: Vishal Kotak <vishal.sanjiv.kotak@gmail.com>
Co-authored-by: dennis zhuang <killme2008@gmail.com>
2026-12-02 10:56:20 +00:00
Aum ea7e61e82a feat: count exact files from metadata in partial COUNT scans (#10140)
* feat(mito2): split metadata counts from residual scans

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): preserve dedup ranges for metadata count residuals

Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito): set TWCS type for metadata count fixtures

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): record SST counts once per scan

Signed-off-by: aumnertic <aumnertic@gmail.com>

---------

Signed-off-by: aumnertic <aumnertic@gmail.com>
2026-12-02 10:48:38 +00:00
dennis zhuang dcf4d246c4 test(promql): trim kernel golden fixtures and share their parser (#10788)
* test(promql): trim three oversized golden fixtures

native_cases.txt, info/prometheus_cases.txt and vector_match/histogram_cases.txt
repeated the same structural shapes on random data. Each now keeps the cases
that cover every input class seen in the original (plus every fixed case
appended after the seeded batch, and every info error case), topped up with a
small seeded random sample. The cases are deleted from the generated files,
not regenerated, and the pinned counts follow the new files.

A set of 24 hand mutations across the covered kernels was run against the
original and trimmed fixtures; every mutation the original killed is still
killed.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): parse every golden fixture with one block parser

Six tests each carried a parser for the same `case`/`grid`/`<kind> <labels> ;
<points>`/`error`/`end` format. golden.rs now splits a fixture into raw blocks
and lines, and each test interprets its own kinds and header. The two
almost.Equal copies are reduced to the one in grid_series::reference.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): drop builder and merge tests the random tests already cover

grid_series: `an_all_missing_push_holds_no_row`,
`skipped_and_all_missing_positions_are_the_same_series` and
`an_ordinary_nan_is_a_present_value_and_not_a_hole` are states that
`the_series_of_one_push_sequence_matches_the_pushed_rows` reaches on every run
(all-missing rows pushed and skipped inside, before and after a series' values;
NaN rows between holes) and checks position by position. The nested
`acceptance` module uses the file's `grid_schema` instead of its own copy.

vector_match: the inline `merge_shape_tests` module compared the one-field merge
with the multi-field merge on hand-built results. The value checks are covered
by `binary_vectors_match_prometheus_reference` (single- and two-field operands,
including fully and partly filtered label sets) and
`histogram_operators_match_prometheus` (histogram rows through the one-field
merge). The billing and reservation-refusal tests move to vector_match/tests.rs.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): name golden outcome counters for what they count

The `failed` counters summed cases whose expected outcome was an error, which
the kernel matched, not failures. They are now `errors` (and `answers` for the
compared results), and every loose lower bound is pinned to the exact count.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): keep the empty-input golden cases and refuse unread error blocks

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): refuse error blocks in the remaining golden consumers

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): restore the custom-bucket avg and info switch golden cases

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): keep golden coordinates as written and require them to ascend

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 10:39:17 +00:00
dennis zhuang b59b1c0a23 refactor(promql): type FusedSeries output modes and drop redundant checks (#10785)
- FusedSeriesExec picks its output kind (rows, evaluated, state) once;
  each stream pulls its own output from one shared driver, removing the
  mode bools, FusedOutput and the "cannot happen" adapter arms.
- The evidence claim alone tracks completion; drop the duplicated flag,
  the extra Drop impl and the second Arc.
- Remove the unused FusedSeriesExec::try_new, write-only
  matching_parallelism, and exec checks the logical node already makes
  (canonical producer format is now checked on decode).
- Share router helpers in to_execution_plan, the plain-row
  classification, and the aggregate-state schema conversions.
- split: compute the state binding at the cut so into_trees cannot
  return None or a missing-grid error.
- Trim restating comments.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 10:37:55 +00:00
dennis zhuang 97f7db3dec test(promql): share the repartition and fused series test fixtures (#10787)
* test(promql): consolidate series repartition test children

Replace the seven copies of the scripted child plan with one TestChild
whose partitions are opened by a closure, and give RawPartition
constructors for its three shapes. Merge the identical output/output_of
helpers and drop the unused raw late-failure path.

The output queues are unbounded, so comments and fixture sizes that
assumed a full queue were wrong; restate those tests by what they
exercise and remove TEST_FIXTURE_VOLUME. Rename tests whose names
contradicted their assertions and trim narrating comments.

Remove three tests whose path is covered elsewhere:
- same_canonical_key_chains_merge_into_one_series, covered by
  multiple_producers_and_owners_merge_exact_full_label_identities
- a_child_partition_that_fails_mid_stream_ends_every_output_with_its_error,
  folded into a_child_failure_is_terminal_on_every_output
- dropping_a_raw_destination_releases_its_partial_chain, the one-chunk
  case of dropping_a_raw_open_chain_cancels_and_releases_its_reservation

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): trim fused series test setup and dead checks

Add frame_node, state_export_node, final_node, explicit and
decode_frames helpers for the node builds, input tuples and frame
decodes repeated across the file; move frame_decode up so both test
modules share it.

binding_of ignored its schema argument, so drop it, and drop the
equality check that compared two bindings built the same way. The
state-export decode test serializes the node directly: serialize
refuses nothing, so the payload rewrite it worked around is not needed.

empty_first_source_does_not_end_gather_early could not fail, since a
one-to-one match with an empty left side answers nothing either way.
Give the left side fill(0) so an early end changes the answer.

Remove two tests whose path is covered elsewhere:
- a_single_consumer_keeps_the_empty_closing_chunk_in_its_frame,
  same fixture and assertions as
  a_frame_carries_the_closing_chunk_a_row_table_drops
- series_frame_rate_matches_plain_rows_bitwise, covered by
  frame_output::abs_rate_frame_matches_plain_rows_with_exact_values_and_labels

Also fix a comment cut mid-sentence and drop comments that narrate
review history.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): name two repartition tests for what they pin

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): restore the checks the merged exchange tests dropped

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): compare frame and plain rows for a bare rate root too

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 10:36:53 +00:00
dennis zhuang 6a3ad83333 refactor(datatypes): share series frame decoding and pack streams (#10786)
* refactor(datatypes): share series frame label and payload decoding

Decode raw and evaluated frames through one label helper and one
per-field payload helper, and drop the test-only row-list raw decoder
with its differential tests. Cases only those tests covered (nullable
parent declaration, keyless explicit raw row, payload/axis length
mismatch, defect precedence) are kept as direct tests. The in-file
aggregate-state contribution test is folded into frame/tests.rs, and
canonicalize/validate_batch comments are trimmed.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(common-query): share the evaluated and aggregate-state pack streams

Run both grid-addressed pack streams through one generic stream that
differs only in how a chunk is validated and columnarised, publish the
final flush of every pack stream through one helper, and reuse
unpack_error and one empty-batch yield helper in the unpack streams.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(common-query): build plain float chunks through chunk_with

Also rename explicit_mode_rejects_key_payload to what it tests; the
primary-key half is primary_key_mode_rejects_explicit_metric_payload.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* docs(common-query): drop an inaccurate alias claim

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* docs(datatypes): say who checks the schema before decode_aggregate_state_labels

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 09:00:30 +00:00
dennis zhuang fd6392691b refactor(promql): always budget vector kernels and panic on a misread cursor row (#10784)
* refactor(promql): always budget the vector matching and info kernels

Unbudgeted entry points now forward a no-op reserve, as the aggregate kernel does, so the kernels take a plain &mut Budget instead of an Option and drop the inner layer.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(datatypes): make RowCursor::at panic on a contract violation

Every caller that read through RowCursor::at expected the row, so at now returns the sample and panics on a backwards or out-of-range row. try_at keeps the Option for the callers that turn it into an error or a missing sample.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(promql): name the caller of a misread cursor row

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* docs(datatypes): say RowCursor::at needs a strictly later row

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 08:55:43 +00:00
Ning Sun fae5368d81 fix(postgres): check the COPY FROM STDIN payload bound first and make it configurable (#10632)
* fix(postgres): check the COPY FROM STDIN payload bound first and make it configurable

The 64 MiB bound on a table-less COPY FROM STDIN payload (influxdb line
protocol, OTLP, Prometheus Remote Write) was checked only after the chunk
had been charged against the shared request-memory limiter, so a chunk the
bound rejects could first stall on the limiter's Wait policy until its
timeout and then surface a misleading "Timeout waiting for memory quota"
(53000) instead of the bound's own error. The bound is now checked before
the charge: a rejected chunk neither waits for nor takes permits.

The bound also becomes `postgres.max_copy_in_payload` (default 64MB, 0
disables it), mirroring `http.body_limit`, and the error names it as a
human-readable size (`64.0MiB`) instead of a raw byte count.

Tests: unit tests for the bound; servers-crate tests driving it end to end
against the OTLP double (default, configured, unbounded, and bound before
quota); tests-integration coverage through the real line-protocol pipeline;
config-loading assertions and the regenerated config docs.

Signed-off-by: Ning Sun <sunning@greptime.com>

* test(integration): add max_copy_in_payload to the config dump snapshot

GET /config serializes the new postgres.max_copy_in_payload option, so
test_config_api's expected TOML needs its line (ReadableSize renders in
binary units: 64MiB).

Signed-off-by: Ning Sun <sunning@greptime.com>

* fix(postgres): require explicit zero to disable COPY payload limit

Signed-off-by: Ning Sun <sunning@greptime.com>

---------

Signed-off-by: Ning Sun <sunning@greptime.com>
2026-12-02 08:33:45 +00:00
jeremyhi 6aea2171bc fix(mito2): hand over a region awaiting the Leader lease of another migration (#10796)
* fix(mito2): hand over a region awaiting the Leader lease of another migration

A region that a catchup promoted awaits its Leader lease. A catchup that
reached it was always caught up again from this node's WAL with an empty
commit, as a repeat of the promoting migration. After a rolled-back
migration, the catchup of the next one then recorded none of the source's
later entries.

The region now records the candidate lease id of the catchup that
promoted it. Only a catchup with that id is a repeat; any other catchup,
or one without an id, takes the path of a region that awaits nothing,
after asking the earlier promotion's tail replay to end. The metric
engine passes the candidate lease id to the metadata region too.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(mito2): keep the promoting catchup's id in the promotion fence

The id of the catchup that promoted a region is kept in the promotion
fence and set by the promotion itself. The tests hold the replay commits
they read, wait for the earlier replay to be registered, pin the cancel
of a replay held in a listing, the record on a caught-up-again
replacement, and the catchups of a region not published conditionally.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* docs(mito2): word the record and the close of a refused catchup plainly

Text only: the begin_catchup and promoted_by docs, the close comment on
a Follower a refused catchup leaves, the test docs and AGENTS.md.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(mito2): catch an awaiting region up again unless the catchup promotes it

Only a catchup with set_writable of another migration takes the path of
a region that awaits no Leader lease. A catchup that does not make the
region writable is caught up again whatever its id, so a replay that
falls short keeps the region with its rows, as before.

Word the replay-position check and the close of a refused Follower
precisely, carry the migration's id in the remaining test catchups that
model an upgrade, and check that each promotion replaces the record.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(mito2): reject competing promotions during leader transitions

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* docs(mito2): clarify catchup routing while awaiting a leader lease

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-12-02 07:45:23 +00:00
dennis zhuang c878342db4 fix(servers): mask internal errors in Prometheus HTTP API responses (#10793)
* fix(servers): mask internal errors in Prometheus HTTP API responses

Several Prometheus API error paths rendered errors with to_string(), so
Internal and Unknown errors returned their full message to the client. They
now use output_msg(), like the other Prometheus handlers.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(servers): report the catalog error status for Prometheus metadata lookups

retrieve_metric_metadata only fails on catalog lookups, but the handler
reported every failure as InvalidArguments (HTTP 400). It now uses the
error's own status code, so a masked internal error is no longer a 400.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 07:08:57 +00:00
Weny Xu 6ccf4d9341 fix(meta): honor user providers for admin endpoints (#10774)
* fix(meta): honor user providers for admin endpoints

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta): authorize admin operations through permission checker

Signed-off-by: WenyXu <wenymedia@gmail.com>

* test(meta): cover admin HTTP authentication from configuration

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta): enforce admin authorization on matched plugin routes

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix: reject unregistered metasrv user providers

Signed-off-by: WenyXu <wenymedia@gmail.com>

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-12-02 07:07:52 +00:00
Ning Sun 464ccc3abd fix(postgres): account CSV and JSONL COPY memory (#10493)
* feat(postgres): Prometheus Remote Write protobuf ingest via COPY FROM STDIN

COPY FROM STDIN WITH (FORMAT promwrite [, version 2] [, <options>])
ingests one Prometheus Remote Write request body over the postgres wire
protocol — a GreptimeDB-specific, binary COPY format (wire format code
1). The payload is byte-for-byte the body a remote-write client POSTs
to /v1/prometheus/write, compression included: buffered until CopyDone
and completed through the exact ingestion core that endpoint runs.

To share that core, the HTTP handlers' ingestion bodies are extracted
into axum-free functions (ingest_remote_write_v1/v2 plus the context
extension stamping), and the HTTP routes become thin wrappers — their
behavior is unchanged, and the copy layer runs the identical decode,
validation, conversion, batched/prepared write paths, per-batch
write-progress accounting and context extensions, under the
connection's regular postgres context.

The WITH options carry what the HTTP endpoint takes as its
content-type/-encoding and query parameters; session-provided values
(database, user) are not repeated:
- version 1|2 (default 1), matching the content-type's proto
- zstd, matching Content-Encoding: zstd (snappy by default)
- physical_table, matching the ?physical_table= parameter
- pipeline_name/pipeline_version, matching the pipeline headers
  (v1 only; for v2 they are accepted and ignored, exactly like the
  HTTP route ignores them)

Table-less like the other ingestion formats; one COPY statement is one
bounded request (shared 64 MiB limit); the row count reports written
rows (v1) or written samples plus histograms (v2). The flush enforces
the frontend's shared request-memory quota (max_in_flight_write_bytes)
— the same limiter the HTTP ingestion protocols use, so COPY cannot
bypass the aggregate budget. Wiring: PostgresServer::with_prom_remote_write
carries the handler, metric-engine flag, validation mode and shared
memory limiter.

e2e: v1 body chunked across CopyData boundaries; v2 samples with
readback; physical_table option routing; garbage-body decode failure
with connection reuse; a tiny-quota regression where a compressed body
whose decompressed size exceeds the budget fails like the HTTP route.

Signed-off-by: Ning Sun <sunning@greptime.com>

* feat(postgres): jsonl COPY FROM STDIN via the arrow-json engine

COPY tbl [(cols)] FROM STDIN WITH (FORMAT jsonl) ingests
newline-delimited JSON objects through arrow-json's incremental
Decoder — the same engine behind file-based COPY ... FROM 'file.json' —
so both COPY routes accept identical data. One JSON object per record;
keys address the targeted columns by name, absent keys become NULL,
and offset-free timestamp strings parse in the session timezone (the
same schema substitution the csv codec makes), like SQL INSERT.

The streaming contract mirrors arrow-csv's exactly (decode returns
consumed bytes; a short read means a full batch), so the parser is a
twin of the csv one: objects may span CopyData chunk boundaries,
records surface in COPY_IN_FLUSH_ROWS batches, and a trailing object
without its newline is accepted. Table-bound like csv (a named table
is required; the column list fixes the target order); no options (the
file format's layout options are writer-side; the reader parses
date-times natively).

The two table-bound codecs share the table path through a small
TableBoundCodec trait (check_column_type + create_parser); csv's
behavior is unchanged.

e2e: chunked object-boundary ingest with absent-key NULLs;
session-timezone parity against SQL INSERT; malformed JSON failure
with table-left-clean and connection recovery.

Signed-off-by: Ning Sun <sunning@greptime.com>

* fix(postgres): account CSV and JSONL COPY memory

Signed-off-by: Ning Sun <sunning@greptime.com>

* fix(postgres): keep table COPY progressing within its memory quota

Signed-off-by: Ning Sun <sunning@greptime.com>

* fix(servers): preserve COPY headroom across admissions and batch boundaries

Signed-off-by: Ning Sun <sunning@greptime.com>

* fix(servers): admit first streamed body frame without counting wait probes

Signed-off-by: Ning Sun <sunning@greptime.com>

---------

Signed-off-by: Ning Sun <sunning@greptime.com>
2026-12-02 07:03:57 +00:00
discord9 10b6cf9477 feat(query): add windowed PromQL evaluation (#10797)
* feat(query): add windowed PromQL evaluation

Signed-off-by: discord9 <discord9@163.com>

* docs(query): clarify window allowlist and drop unused grid bound

The public end_ms_exclusive duplicated point_ms(points) without a caller.
max_input_range_ms stays public for the stacked sequence-probe cache.

Signed-off-by: discord9 <discord9@163.com>

* refactor(query): trim window docs and merge overlapping allowlist tests

Apply review: state the allowlist in a few lines instead of arguing for
it, drop doc that restates the code or another item's doc, and make
max_input_range_ms private since nothing outside window.rs calls it.

Collapse the allowlist tests into one positive table that asserts the
source table and the input range per row, and one negative table that
asserts NotEligible once per shape. The grid tests keep the
point_ms(points) continuation the frontend cache relies on and gain the
negative-start phase case. The differential test drops asserts implied
by full == merged and the SumRate arm that re-derived the aggregate.

Signed-off-by: discord9 <discord9@163.com>

* docs(query): shorten window docs and cover sum(selector) in the differential

Apply review: state the grid rule and the caller's duty in a few lines,
point the selector helper at windowed_source_table instead of repeating
its reasoning, and drop the doc that restates the GridSpec bound.

Add sum(window_diff) as a fourth differential shape so the aggregate the
allowlist admits over a bare selector is compared on both routes too.

Make max_input_range_ms public again: the sequence-probe cache reads the
input range to bound what a chunk depends on, and WindowGrid::of alone
does not expose it.

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-02 06:30:59 +00:00
dennis zhuang c3a79cba98 fix(servers): reject out-of-range MySQL integer params and fix TIME param unit (#10791)
* fix(servers): reject out-of-range MySQL integer params and fix TIME param unit

Binary-protocol integer parameters were narrowed with `as`, so a value outside
the target column type wrapped silently. They now fail with InvalidParameter.
TIME parameters stored milliseconds in a Time64Nanosecond scalar; they now
store nanoseconds.

Also share the parameter replacement loop between protocol and CLI params,
run the federated shortcut check once, and remove the test-only
replace_placeholders.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(servers): cover out-of-range MySQL binary-protocol integer params

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(servers): cover MySQL binary-protocol TIME params

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 06:19:43 +00:00
dennis zhuang 4db1d9f656 fix(servers): reject out-of-range PG timestamp params and multi-statement parse (#10792)
* fix(servers): reject out-of-range PG timestamp params and multi-statement parse

Scalar TIMESTAMP and TIMESTAMPTZ parameters, and TIMESTAMPTZ arrays, became
NULL when a value did not fit a nanosecond column; only TIMESTAMP arrays
reported the overflow. The four conversions now share one helper that rejects
the value with numeric_value_out_of_range.

An extended-protocol Parse with several statements prepared the first one and
dropped the rest; it now fails with invalid_prepared_statement_definition.

Cancelled and DeadlineExceeded map to SQLSTATE 57014 (query_canceled) instead
of 57000.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(servers): reuse TimeUnit::as_arrow_time_unit for PG timestamp params

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(servers): reject multi-statement Parse before fixture shortcuts with 42601

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(servers): answer PG fixtures per statement in multi-statement queries

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(servers): match PG fixtures against whole commands only

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(servers): drop per-statement PG fixture handling; reject unsupported mixes

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(servers): answer PG transaction fixtures per statement in simple queries

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 06:17:24 +00:00
dennis zhuang 8ea60a155c fix(promql): keep NULL rows of native instant selectors (#10762)
* fix(promql): keep NULL rows of native instant selectors

A selector at the statement root dropped a selected row whose fields are
all NULL, so native TQL answered nothing where the existing planner
answers a NULL row, and an all-NULL series disappeared. The root
selection now reports stored rows (InstantValue::Row); selections that
feed functions, aggregations and binary operands keep dropping them.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* style: format the merge and document root selection precedence

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 05:44:11 +00:00
dennis zhuang 37ea3a614f fix(servers): map NaN OTLP log attributes to null and clamp v0 span durations (#10789)
An OTLP log attribute holding a NaN double panicked the pipeline conversion,
and a v0 trace span whose end precedes its start underflowed duration_nano.

Also remove the duplicated new-column conversion in the log path, reuse the
v1 fixed trace column indexes in v2, drop the uncalled v1::write_span_to_row,
and fix stale comments.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 04:58:34 +00:00
dennis zhuang 4d44909217 feat(promql): read sub-millisecond file-engine time indexes natively (#10703)
* feat(promql): read second, microsecond and nanosecond time indexes natively

The native route declined every selector over a time index that is not
in milliseconds. The existing plan wraps such a scan in a cast
projection, so the decline surfaced as selector_plan_is_not_a_table_scan,
and the region's raw series preflight refused the unit as well.

The raw series path now hands ticks over in the stored unit, and each
raw input of the native tree records that unit. Evaluation keeps the
existing plan's semantics: windows and lookbacks are decided on the
stored ticks, a kernel reads the time truncated toward zero to
milliseconds after the offset, and samples less than a millisecond
apart remain distinct samples. Since every bound is a whole
millisecond, deciding membership on ceil(tick) in milliseconds is
exact, so the evaluators keep a window time beside the payload only for
microsecond and nanosecond inputs. Scan filters are built in the
stored unit.

Histogram fields and range modifiers over a sub-millisecond time index
still decline. The append-mode decline is kept and renamed to
append_mode_table.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): decline a discovered selector over mixed time index units

Logical metrics on different physical tables can store their time
index in different units, while the union a nameless selector reads is
one native input bound to one unit. The union took the first source's
unit and read the other sources' ticks in it, so a series stored in
microseconds next to one in milliseconds dropped out of its windows.
Such a selector now declines.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): run native PromQL over file-engine tables

File-engine tables have no raw series scanner, so the native route
declined them and they fell back to the legacy planner.

Read such a table through a new RowSeriesSource node: an ordinary scan,
filtered by the selector's matchers and time range, hash-partitioned by
tags and sorted by (tags, time index, fields), then cut into
explicit-label raw series chunks with Float64 values. The node declares
its input distribution and ordering, so the physical optimizer inserts
the repartition and a spillable SortExec. It stays above the merge scan,
so it runs on the frontend in both standalone and distributed mode.

Rows sharing labels and a timestamp keep one sample, as Prometheus
storage does: the row whose field values sort lowest (nulls last).
Non-string tags and histogram fields keep the existing plan.

The cluster test builder can now pass the local file sandbox to
datanodes and install frontend-only plugins, so the distributed case is
covered.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read file-engine tags as Prometheus label values

A row source now reads every tag column as text with NULL read as '',
so a NULL and an empty tag are one series from the start and an empty
value carries no label, as in Prometheus. Rows of that series at one
timestamp keep one sample by the existing rule. Matchers apply to the
text form above the scan, so an integer tag matches "200" but not
"0200". This drops the row_source_tag_is_not_a_string decline.

The legacy planner fails on such a table with "Unsupported tag column
type: Int64".

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read native histogram fields from file-engine tables

A row source passes a native histogram field on as histogram samples,
converted with the same histogram_samples_from_arrow the mito raw scan
uses, instead of casting every field to Float64. This drops the
row_source_reads_floats_only decline, so the fixture of the sqlness
case promql/delta_exponential_histogram runs natively; the integration
test mirrors its statements and answers.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read second-precision file-engine time indexes natively

The existing scan plan already promotes a second-precision time index to
milliseconds through a projection, which is exact. A row source now
reads that projection instead of declining, and pushes the time range
into the scan only when the scan's time index is in milliseconds.
Microsecond and nanosecond time indexes still keep the existing plan.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): decline file-engine tables with a `__name__` tag column

A row source dropped a tag column named `__name__` from its labels, sort
key and partition key, so rows that differed only in that column merged
into one series and lost samples. Mito's raw scan refuses such a tag.
Decline it at planning time instead, and make RowSeriesSource reject the
tag rather than filter it out.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): dedupe file-engine samples per field

A row source reduced rows sharing labels and a timestamp to one whole
row picked by the first field, so a NULL in another field of that row
dropped the value a discarded row held there. Each field is its own
value series: at a duplicated timestamp every field now keeps its own
lowest non-null value (NaN above numbers, histograms by struct order).

The sort key drops the fields, and the rows of the last timestamp of a
batch are held back until the next batch, so every duplicated timestamp
is reduced within one batch.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): read microsecond and nanosecond file-engine time indexes natively

A row source read its time index through the existing plan's cast to
milliseconds, which truncates a finer one, so it declined microsecond
and nanosecond time indexes.

It now reads the column as stored, as the raw series scan does, and the
input it feeds is bound to the time index's unit. Evaluation then
follows the rules mito tables already have: windows and lookbacks are
decided on the stored ticks, a kernel reads the time truncated to
milliseconds, and samples less than a millisecond apart stay distinct.
Histogram fields and range modifiers over such a time index decline as
they do for mito. The time range is pushed into the scan in the stored
unit for pruning. A second-precision time index takes the same path.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): decline every table with a `__name__` tag column

The native route names each series it reads by its table and has no
label to read a tag column named `__name__` as. Only file-engine tables
were declined; a mito table with such a column ran natively and lost
the column: two series that differ only in it came back as two rows
with one label set, and `sum by (__name__)` folded them into one. The
existing plan reads the column's values as the metric name instead.

Such a schema has no Prometheus reading: a series has one `__name__`,
and the table name already is the metric name. Decline it on every
engine so the statement keeps the existing plan's answer.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): keep a window open until its last millisecond has been read

A sample finer than a millisecond is placed in the window ending at the
millisecond above it. A chunk that ends on such a sample has not read
the rest of that millisecond, so treating that millisecond as settled
closed the window before a later sample in the same millisecond arrived
in the next chunk. Settle only up to the millisecond the last sample lies
in, rounded down.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): select only an exact sample under a zero lookback

A zero lookback admits only a sample exactly at the instant. The window
time of a sample less than a millisecond before the instant rounds up to
the instant, so the native selection picked it where the existing route
returns nothing. Compare the stored tick with the instant when the
lookback is zero, on the grid and anchored paths.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): cover zero lookback on microsecond and nanosecond file-engine tables

A zero lookback selects only a sample stored exactly at the instant. A
row source hands its time index over as stored, so a sample 0.5ms before
the instant shares that instant's window time and was selected. The
exact-match rule from the time index precision branch covers the row
source as well; these cases pin it for file-engine tables in both
precisions and check that legacy gives the same answer.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): cover a stale marker in the second field of a wide file-engine table

A Parquet file-engine table with a microsecond time index and two DOUBLE
fields: a row whose first field is valid and whose second holds a stale
marker is selected on both routes, and a row stale in the first field is
dropped on both, as the existing plan reads staleness from the first field
only.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 04:32:09 +00:00
dennis zhuang 66ef0e3d67 fix(servers): reject repeated and reserved label names in remote write v1 (#10790)
* fix(servers): reject repeated and reserved label names in remote write v1

Remote write v1 wrote a label named greptime_value or greptime_timestamp into
the value or timestamp slot, where the sample then overwrote it, and a repeated
label name (including __name__ and the database and physical table labels)
kept the last value. Both now fail the request, as v2 already does.

Also share the PromCtx to ContextOpt conversion between v1 and v2, reuse
TableData::into_rows for v2 row padding, and remove two uncalled label
helpers from prom_store.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(servers): reject reserved label names before the pipeline branch

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 04:12:45 +00:00
dennis zhuang 2916062cc4 feat(promql): answer an instant query of a range selector natively (#10672)
* feat(promql): answer an instant query of a range selector natively

An instant query whose root is a range selector, such as `x[5m]`,
declined with matrix_root_without_a_grid. Prometheus and the existing
plan answer it with the samples of the window, keeping their own
timestamps and dropping stale markers.

Those samples are exactly the points of a one-millisecond subquery over
the same window at which the bare selector, read with no lookback,
finds a sample. The planner now compiles such a root that way, reusing
the subquery-root path, so `offset` and `@` place the window as they
do for a subquery. A range query with a range-vector root still
declines and fails as before.

A zero-lookback instant selection now walks the samples instead of the
grid points, and bounds its workspace by the sample count, so the fine
grid costs no more than the samples it answers.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): cover the HTTP matrix of a native range selector root

The instant query API now answers `x[5m]` on both routes with the same
matrix, and a series with no sample in the window is omitted. The
range selector finder also gets its own doc comment back.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): keep a range selector root's null rows and leave sub-millisecond windows to the existing plan

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): drop a range selector root's rows stale in any field

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): leave histogram range selector roots with an offset to the existing plan

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(promql): keep any-field staleness specific to range selector roots

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): answer histogram range selector roots with an offset natively

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): leave range selector roots over sub-millisecond time indexes to the existing plan

A range selector root runs as a one-millisecond subquery with no
lookback. On a microsecond or nanosecond time index, a zero lookback
selects only a sample exactly on a millisecond, so a sample between two
grid points would be missing from the window. Decline the rewrite there.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* style(promql): format the range selector root time unit decline

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 04:10:20 +00:00
Yingwen 5e5b2166f1 feat(mito2): support direct flush of encoded Narthex parts (#10731)
* feat(mito2): support direct flush of encoded Narthex parts

Signed-off-by: evenyag <realevenyag@gmail.com>

* test(mito2): exercise direct flush retries and manifest write failures

Signed-off-by: evenyag <realevenyag@gmail.com>

* style(mito2): move direct flush imports to module scope

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): align encoded Narthex flush with Parquet

Signed-off-by: evenyag <realevenyag@gmail.com>

* docs(mito2): clarify logical offsets for framed sample keys

Signed-off-by: evenyag <realevenyag@gmail.com>

* test(mito2): check resident keys across Narthex parts

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): compile sample codec test helpers only for tests

Signed-off-by: evenyag <realevenyag@gmail.com>

* test(mito2): cover direct flush of grouped Narthex samples

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): cache direct Narthex flush uploads

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): reuse flush task cancellation for Narthex

Signed-off-by: evenyag <realevenyag@gmail.com>

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
2026-12-02 00:47:43 +00:00
discord9 5d3e22ce93 refactor(promql): report a declined shape instead of planning it the old way (#10701)
* refactor(promql): refuse with the recorded cause

A native decline fails the offer instead of silently planning the statement again with the existing planner. Preserve upstream statement, alias and time-index shapes.

Signed-off-by: discord9 <discord9@163.com>

* refactor(promql): remove the dist-planner replan and the stale gates that fed it

A statement the native route was asked for is planned once. The second planning pass with the route off, the gate that decided it, the histogram-aggregate refusal that cannot trigger, and the fallback option veto are gone; an unknown statement extension is refused by name.

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-01 14:46:16 +00:00
dennis zhuang fe01aeec89 feat(promql): run native PromQL over metric-engine physical tables (#10678)
* feat(promql): merge raw series that share a label set

Add SeriesRouting::RawLabelSet: a raw router that routes by Prometheus
label set and merges every stored series of one label set into one series,
samples chained by timestamp like Prometheus' ChainedSeriesMerge. At a
timestamp several stored series hold, the sample of the smallest primary
key wins; pieces of one stored key must still agree there.

A RawSeriesSource can ask for this merge. The flag is frontend-only: the
router is placed where the source's frames arrive, above the region scan
without a distributed planner and above the MergeScan with one.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* feat(promql): run native PromQL over metric-engine physical tables

A selector naming a physical table used to keep the existing plan. The
logical tables on it key their series by __table_id and __tsid, so two of
them with equal labels store two series that Prometheus reads as one. The
selector now reads through a RawSeriesSource that merges equal label sets,
in standalone and across regions.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): merge physical-table label sets only above the merge scan

Standalone hands the region the logical plan without serializing it, so the
label-set flag reached the region and plan_raw_series_source added a second
RawLabelSet router there. That buffered every region's answer twice, and a
region could resolve a shared timestamp from its own share of the keys.

The dist planner now gives MergeScanExec the source with the flag cleared
and keeps the router above the merge scan. Planners without a dist planner
still merge above the region scan. A single-chunk label set also skips the
merge workspace.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): let a live sample win over a stale marker in label-set merges

At one timestamp, the label-set merge now keeps the first sample that is
not a stale marker in primary-key order, so a stale marker from one
logical table no longer hides another table's sample. This matches the
legacy plan, which drops stale markers before collapsing timestamps.

The same-key conflict check now covers every key at the timestamp, not
only the key that sorts first.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(promql): skip the stale check for single-row timestamp groups

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-01 13:41:05 +00:00
dennis zhuang 8d9de93e61 refactor(promql): share the repeated checks of native tree validation (#10780)
* refactor(promql): share the repeated checks of native tree validation

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(promql): name each parameterized node in its validation errors

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): pin that a parameterized histogram declares samples

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-01 13:38:04 +00:00
dennis zhuang 9ec4ad4d2a refactor(promql): build native runtime nodes through one tree builder (#10779)
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-01 13:37:18 +00:00
dennis zhuang 029ecd8ecf fix(promql): pull native input while a dynamic scalar is pending (#10755)
* refactor(promql): walk native runtime children through one accessor

Eight recursive passes over RuntimeNode each matched all twenty RuntimeOp
variants to reach the same four child shapes. They now go through
children()/children_mut(), and each pass keeps only its node-specific logic.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): pull native input while a dynamic scalar is pending

Broadcast, ParameterizedMap, ParameterizedTopK and ParameterizedHistogram
returned without pulling their vector input until their scalar parameter
arrived. The input then stayed queued at the source, where each slice is
billed its whole allocation, so the pool could refuse a query that fits.
They now pull it meanwhile: the streaming nodes hold it billing each
allocation once, the whole-input ones retain it, as ParameterizedAggregate
already folds it.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): release a held allocation once its last chunk is handed on

HeldInput billed every held allocation until the whole queue emptied, so while
a broadcast drained it, the inputs it had already handed on stayed billed beside
the downstream copy of their output. sort(x * scalar(y)) over 32 separately
allocated series needed 620,168 bytes instead of 349,006. Each allocation is
now counted by the held chunks referencing it and released with the last one.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-01 12:33:13 +00:00
sunanddennis zhuang d41bf69add feat: update dashboard to v0.14.8 (#10778)
Co-authored-by: dennis zhuang <killme2008@gmail.com>
2026-12-01 12:18:07 +00:00
dennis zhuang e736a2ee9e refactor(promql): drop dead native code and gate test-only entry points (#10756)
* refactor(promql): drop dead native code and gate test-only entry points

- Drop NodeMetrics::record_state and the always-zero groups and
  state_entries gauges every native node registered.
- Drop map_pi and NativeHistogram::divide_by, neither of which has a
  caller.
- Remove the stale allow(dead_code) on float_histogram.
- Gate the unbudgeted entry points that only tests call behind
  cfg(test): aggregate_float, FloatAggregator::{try_new, update, finish},
  set_vectors, finish_partial, merge_count_values, compile_statement,
  is_node_metric and NativeHistogram::fraction.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* refactor(promql): drop the unused canonical producer locality probe

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-01 11:36:22 +00:00
jeremyhi c63f9e42c4 fix(mito2): hand over WAL tails even when skip_wal is set (#10781)
* fix(mito2): hand over WAL tails even when skip_wal is set

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* test(mito2): verify recovery across skip_wal changes during takeover

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-12-01 11:23:38 +00:00
Weny Xu b46be9e640 feat(meta-srv): add follower migration hooks for the migrate RPC and datanode drain (#10770)
* feat(meta-srv): support plugin-backed follower migration

Signed-off-by: WenyXu <wenymedia@gmail.com>

* feat(meta-srv): drain followers through migration factory trait

Signed-off-by: WenyXu <wenymedia@gmail.com>

* refactor(meta-srv): isolate and batch follower migration

Signed-off-by: WenyXu <wenymedia@gmail.com>

* refactor(meta-srv): filter drain candidates by region role

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta-srv): guard migration route checks and retry drain placement

Acquire migration guards before validating source and destination peers and pass them to the follower procedure. Drain retries when another source is migrating the region and reselects an automatic target that has become occupied.

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta-srv): skip running migrations and count drained regions by role

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta-srv): revisit busy regions and isolate drain batch failures

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta-srv): bound drain retries for busy regions

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta-srv): reconcile drain failures by supported region role

Signed-off-by: WenyXu <wenymedia@gmail.com>

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-12-01 11:21:06 +00:00
Lei, HUANG c0dc0cb55b perf(query): prune iceberg_hash buckets across timestamp ranges (#10766)
perf(query): retain hash pruning when partition bounds cannot normalize

Use scan-local iceberg_hash equalities to exclude routes even when another partition dimension prevents constraint normalization. Preserve NULL and unmatched-write destinations, and cover the fallback in a mixed timestamp/hash SQLNESS case.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
2026-12-01 11:17:54 +00:00
Weny Xu 0be5ae25e5 refactor: extract shared sketch states (#10773)
Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-12-01 10:40:47 +00:00
discord9 d5f4d711ad test(fuzz): make a duplicated repartition row observable (#10753)
* test(fuzz): make a duplicated repartition row observable

The target validated with COUNT(1) on a table that was not append-mode, so the scan's
last-row dedup collapsed two copies of the same (primary key, time index) before the
count ran: a duplicate was invisible even when the data held it.

Create the table in append mode and add a group-by over the key and time-index columns
with HAVING COUNT(1) > 1, which fails naming the duplicated key. The pre-merge
strict-window compaction stays: it is what makes a second copy reachable.

Signed-off-by: discord9 <discord9@163.com>

* test(fuzz): name the duplicate before the counts panic

The duplicate-row assertion ran after COUNT(1) and COUNT(DISTINCT ts); a duplicate
trips those first, so the query that names the offending key never ran. Move it ahead of
both.

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-01 10:08:12 +00:00
Yingwen ba53f68f0c perf(mito): share SST caches with Narthex series and samples (#10659)
* perf(mito): share SST caches with Narthex series and samples

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito): address Narthex cache review findings

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito): scope sample pages to their physical owner and exercise cold reads

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito): account for cached predicate memory and preserve manifest refills

Signed-off-by: evenyag <realevenyag@gmail.com>

* test(mito): exercise shared preload imports when enabled

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito): group local Narthex cache files by artifact UUID

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito): remove empty local artifact directories after eviction

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito): flatten the local artifact directory name

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito): drop cleanup for earlier Narthex cache layouts

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito): leave UUID-only Narthex cache cleanup to eviction

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito): use single-range slices in cache tests

Signed-off-by: evenyag <realevenyag@gmail.com>

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
2026-12-01 09:58:49 +00:00
discord9 dca65604a9 feat(promql): answer an append-mode table, and any k for limitk (#10650)
* feat(promql): answer append-mode tables and any k for limitk

The append-mode collapse compares raw ticks, so two distinct ticks inside one
millisecond both survive and a same-tick tie keeps the last write. limitk picks
its members by a hash of the label set with the label set as tie-break, so the
membership no longer follows the order the inputs arrive in.

Signed-off-by: discord9 <discord9@163.com>

* test(promql): compare the golden limit cases by membership, not by pick

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
2026-12-01 09:35:02 +00:00
jeremyhi 7f367720f6 feat(mito2): take a region over from a source that reported no entry (#10761)
* feat(mito2): take a region over from a source that reported no entry

On a region whose manifest is published conditionally, a catchup that
makes the region writable and names its source but no reported entry (a
takeover) hands the region over without replaying, as a handover does.

The engine prepares the takeovers of a batch: it reads the latest
manifest version of each, asks for one heartbeat, and lists the WAL of
each source once for a bound. The log store hands the region over while
the catchup waits for a lease of the migration's candidate from a
heartbeat sent after the version read. Under the manifest lock the lease
and the version are checked again, and the commit records this node's
handoff floor and, if the bound is above where the manifest recovers the
source's WAL from, a listed tail up to the bound. The region worker
applies the edit and promotes the region. A region that skips the WAL
commits an empty edit after the same wait.

A takeover of a region that awaits its Leader lease is caught up again as
on main, and commits only after the prepared version while the latest
lease is the candidate's. RegionCatchupRequest gains candidate_lease_id,
passed from the upgrade instruction to the data region. The datanode
sends a requested heartbeat a millisecond after the request; one already
due sooner is kept and another follows it, and the scheduled time is kept
during its reconnect backoff.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(mito2): keep the status of a failed source WAL listing

A takeover whose listing of the source's WAL fails now reports that
listing's status and retry hint: the error is shared across the takeovers
of a batch as an Arc<BoxedError> instead of a message and a status, so a
transient failure stays retryable and an empty WAL is not.

Document what the candidate-lease wait returns, how the worker answers a
takeover it was or was not prepared for, and what an abandoned hand-off
leaves. Cover a manifest that moves during the candidate-lease wait and
a takeover whose reopen fails.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* docs(mito2): clarify takeover preparation error doc

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-12-01 08:31:24 +00:00
Ning Sunanddennis zhuang 768834c465 ci: scope GITHUB_TOKEN permissions in workflows and fix ReDoS in compat updater (#10739)
Add a top-level `permissions: contents: read` to the 15 workflows that had
no default, so every job runs with a least-privilege token instead of the
repository's read/write default. Jobs that need more grant it explicitly:
`publish-github-release` (creates the release), the `update-compat-versions`
caller (a caller's permissions are the ceiling for the reusable workflow),
`apidoc` (deploys gh-pages), and nightly-ci `notification` (opens an issue).

Also rewrite the two array-capturing regexes in
`.github/scripts/update-compat-versions.py` from `(?:[^\]]|\n)*?` to
`[^\]]*?`; the alternation was redundant and backtracked exponentially on
newline-heavy input.

Resolves CodeQL `actions/missing-workflow-permissions` (79 alerts) and
`py/redos` (2 alerts).

Signed-off-by: Ning Sun <sunning@greptime.com>
Co-authored-by: dennis zhuang <killme2008@gmail.com>
2026-12-01 07:29:14 +00:00