Commit Graph
5568 Commits
Author SHA1 Message Date
Samarth Jaiswal f4ff272f37 fix: keep exact DECIMAL and BIGINT UNSIGNED values in COPY FROM csv and json (#10560)
* fix: keep exact DECIMAL and UInt64 values in COPY FROM csv and json

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* style: format the reader schema test

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* test: add the expected output of the exact numbers case

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* fix: round decimals with extra fractional digits in COPY FROM

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* fix: parse decimals from text in COPY FROM csv and json

Arrow's decimal decoding is wrong for some numbers in scientific
notation and drops the digits beyond the scale. Read a decimal column
as a string and parse it, so that every digit is used and the value is
rounded as the cast from a float did.

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* fix: read unsigned integers from text and reject empty strings in COPY FROM json

Arrow's json reader parses an integer in scientific notation through a
Float64, so 9007199254740993e0 lost its last digit in a BIGINT UNSIGNED
column. Such a column is now read as text and parsed from every digit,
like a DECIMAL column.

An empty json string loaded into a DECIMAL column as NULL. It is an
error again, and only an empty csv field is read as NULL.

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

---------

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>
2026-11-24 18:18:35 +00:00
fys 93ddb89ffc fix(query): correct filtering and ordering for file engine scans (#10547)
* fix(query): retain row filters for file engine scans

Signed-off-by: fys <fengys1996@gmail.com>

* fix(query): skip time-series scan hints for file regions

Signed-off-by: fys <fengys1996@gmail.com>

---------

Signed-off-by: fys <fengys1996@gmail.com>
2026-11-24 18:18:30 +00:00
jeremyhi 0dfd6e70cf feat: hand a region over to the object store WAL during catchup (#10589)
* feat(log-store): hand a region over to the object store WAL

Add LogStore::handoff, called before a region becomes writable on a log
store. Once it returns, every id the log store assigns the region is
above the given entry id and every id it assigned the region before,
also after a restart; no entry became obsolete, and check_region_history
accepts the region. The default does nothing.

The object store WAL raises its next object sequence above the object
holding that id, sealing the open batch first if it holds ids under the
current sequence, and keeps a release record of the region's current
watermark for the next sealed batch. It answers once that object is
durable and indexed, in both acknowledgement modes, and then records
that the region's history starts in the store. Hand-offs within one
flush interval share the object.

A store that is failing or lacks I/O permission keeps the floor and the
record and fails the call with a retryable error. If the open batch
cannot be sealed, a durable store has rolled it back and applies both at
once; an enqueued store keeps the batch and applies the largest deferred
floor of each region once it is sealed, unless the store stops first. A
hand-off handled after stop began fails as stopped and keeps nothing.

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

* feat(mito2): hand a region over and claim the next manifest version in catchup

A catchup that makes a region writable and carries the entry id its
source reported hands the region over to the log store before the WAL
history check. The hand-off covers the reported id, the flushed entry id
and every pending tail's upto. A catchup that still has to replay entries
above where its replay starts hands nothing over, so if it cannot reach
them it leaves nothing behind; on the object store WAL it cannot read
them from this node's prefix.

Before the region is promoted, the catchup commits an empty edit as the
version after the manifest the region holds. It runs only under
conditional manifest publication and requires a Follower with no pending
reload and not stopped. It skips the Leader deadline check, starts no
checkpoint and applies only if no checkpoint covers its version. A
writer that committed other content at that version conflicts with it;
the conflict fails the catchup with a retryable error and leaves the
region a Follower that is not fenced. Two catchups that start from the
same manifest version are not told apart.

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

* fix(log-store): prune cancelled hand-off waiters and correct the hand-off docs

A hand-off whose caller stopped waiting left its closed response in the
actor until the record's object was sealed, so repeated cancelled
hand-offs during a long outage accumulated one dead waiter each. Prune
closed responses on admission, as the durability waiters do.

Document that errors other than a failing store or a missing I/O permit
keep the retry hint the object store reports, and that a hand-off pending
when stop begins fails as stopped in the durable mode when its object's
create had not started. Add a test for an issued id in the open batch.

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

* test(log-store): describe what a hand-off after stop keeps

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

* fix(mito2): hand over and commit a region caught up again before its swap

A catchup again replays into an unregistered replacement. It now hands the
region over in that replay and makes the catchup commit of the replacement in
handle_caught_up_again, after the checks of the old instance and under its
manifest lock, so no refusal follows the commit.

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

* fix(mito2): fire the catchup commit's manifest hook without manifest locks

commit_catchup returns the receipt of its manifest hook. A catchup again fires
it once it no longer holds the old instance's manifest lock, so a hook that
reads the manifest cannot queue behind a writer waiting for that lock.

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

* docs(log-store): say which object answers a hand-off pending at stop

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

* docs(mito2): note when the catchup commit's manifest hook fires

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

* test(log-store): cover a hand-off in the open batch when stop begins

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

* refactor(log-store): return the hand-off bound and tidy its docs and tests

LogStore::handoff returns the bound it raised the region above; the default
returns the entry id. The object store WAL defers a hand-off only when the
open batch it cannot seal is not empty. The two open-batch seal tests are one
test now, which also checks the returned bound.

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

* docs(mito2): describe the catchup commit's cost and hook, and guard the hand-off gate

Documents the worker stall of a catchup again's commit, the writable catchup
in the region hook coverage, and the replacement's commit in catch_up_again.
Logs a failed catchup commit. Adds cases for a catchup that does not make the
region writable and for a region that skips the WAL.

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

* fix(mito2): keep Leader leases off a caught-up replacement while its hook runs

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

* docs(mito2): tie the replacement's fence to set_writable and tidy the catchup docs and tests

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

* docs(store-api): say which assigned ids the hand-off bound covers

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

* docs: describe the replacement's lease fence and the hand-off bound precisely

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

* fix(mito2): skip the hand-off for a region without a WAL provider

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

* docs(mito2): name the catchup commit as the exception to the manifest fencing rule

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

* test(mito2): cover the hand-off of a region without a WAL provider

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-24 16:22:18 +00:00
Lei, HUANG 9ecd84f622 fix(mito2): decouple table compaction upload and Arrow budgets (#10607)
* fix(mito2): decouple table compaction upload and Arrow budgets

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* test(mito2): prune redundant table compaction checks

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* fix(mito2): cap GCS compaction objects at 5 TiB

Apply the GCS service limit even when the operator omits its object limit. Keep stricter advertised limits and the multipart part-count limit, and cover all three with geometry tests that perform no uploads.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* test(mito2): require an SST part before its final input batch

Gate the payload of the last source row group on the first Parquet part from its target. A writer that buffers until close can no longer pass the lossless multipart regression.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* refactor(mito2): isolate enterprise buffered uploads

Move the bounded SST and Puffin upload adapter and its regression test behind one gated module declaration. Leave the shared chunk transfer in the Apache-licensed parent and register the new enterprise source in both license lists.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* docs(mito2): describe ObjectStoreWriter bytes as accepted for upload

Bounded uploads stage bytes in a local part buffer before they reach the object store, so output_bytes counts accepted bytes rather than bytes already submitted. The only reader takes the value after a successful close, when both counts agree.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* refactor(mito2): rename the compaction compute estimate

MemoryLimits::compute_bytes returned the estimated working set that admit()
compares against the compute budget, while UploadBudget::compute_bytes holds
that budget. Rename the method to estimate_compute_bytes and name the
admission local accordingly so the estimate and the budget are not read as
the same quantity. The budget field keeps its visibility because source
admission still bounds footer memory by it.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* test(mito2): rename the source-less table compaction fixture

Rename `Fixture::empty` to `Fixture::without_source`. The constructor still creates the scheduler environment, access layer and config and only skips writing the input SST, so the old name suggested a state-less fixture. The new name mirrors `with_source`; both call sites are updated.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* fix(mito2): check the upload object limit inside the bounded writer

Move the object-limit check from the Parquet SST writer into UploadBuffer::write so every caller of the bounded buffer is covered and the remaining-allowance subtraction cannot underflow. Make check_size private; the Puffin adapter keeps its own check and the limit error still surfaces as MultiRegionCompactionResource. Cover writes accepted up to the limit and the rejected next write.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* docs(mito2): document index writer upload policies

IndexWriteBuffer variants select different object-store writers: the default writer, exact-size parts, or a serial upload buffered through the enterprise adapter. Document each policy and explain that IndexObjectWriter boxes the bounded side because that adapter is returned as an opaque type.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

---------

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
2026-11-24 15:33:23 +00:00
Yingwen 21d6a25dfb refactor(mito2): share SST reading with multi-region compaction (#10583)
* refactor(mito2): share SST reading with multi-region compaction

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

* fix(mito2): charge only materialized routing columns

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

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
2026-11-24 10:35:40 +00:00
dennis zhuang 890540f248 fix(table): keep the primary key order when adding columns (#10591)
TableMeta::add_columns rebuilt primary_key_indices from column positions,
so ADD COLUMN on a table whose key is not in column order (or with a key
column added FIRST/AFTER) rewrote the table key, while regions keep their
key and append new tags at the end. Keep the existing key order and append
new key columns in request order.

Refs #10248

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-24 10:28:33 +00:00
Weny Xu 044e659b2d fix(meta): persist segmented procedure checkpoints atomically on RDS (#10604)
* fix(meta): persist segmented procedure checkpoints atomically on RDS

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

* fix(meta): fall back when MySQL packet limit lookup fails

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

* fix(meta): use atomic checkpoint batches on memory and raft backends

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

* fix(meta): preserve large KV writes when batching on RDS

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-24 09:18:56 +00:00
discord9 a6cc055e83 refactor(promql): fold legacy histogram aggregates through the native accumulator (#10483)
* refactor(promql): fold legacy histogram aggregates through the native accumulator

The legacy prom_native_histogram_agg_sum/_avg accumulators kept their own sum, weighted
mean, incompatibility flag and reset evidence beside the native HistogramAccumulator that
10199 added, so the two could answer the same aggregate differently. The legacy
accumulator now holds that fold and delegates push, merge, state and size to it; only the
state frame still differs, and its layout, field names and order are unchanged.

The legacy frame declares neither a compensation component nor a mean mode, so a state
carries the fold's answer: the running sum with its compensation folded in, or the running
mean of its samples. That is what a reader of the frame adds or weights, and it keeps the
residual of samples already folded into one position. It is not a lossless Kahan state --
folding the compensation back into one f64 rounds again, so a partition holding [1e16, 1]
still exports 1e16 and merging it with [-1e16] answers 0.

An exponential sample meeting custom buckets poisons the whole position, as the legacy
reconcile() returning None did: the position answers null and the evidence says why,
rather than skipping the sample or failing the query. Reset evidence is OR-ed from the
state's two booleans instead of re-observing the merged histogram's hint, which the fold
already accounted for.

Signed-off-by: discord9 <discord9@163.com>
(cherry picked from commit 8fc9c00671)

* fix(promql): read a legacy sum's start timestamp from the fold it exports

The two tests #10420 wrote read `accumulator.value`, which this refactor replaced with the
native fold, so the crate did not build. They read `state_histogram()` now.

That path answers a derived histogram: `finished_histogram` compacts it, which clears the start
timestamp along with the empty buckets. So a single-sample sum no longer republishes the sample's
own timestamp - the timestamp is still inside the fold, but the answer is a derived one and says
so. The test that required the timestamp to survive is renamed and asserts the export instead.

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

* fix(promql): drop a position whose histogram cannot be read

A histogram whose spans and buckets disagree is one this crate cannot read. The accumulator this
refactor replaced met that disagreement through `legacy_bridge::add`'s `None` and dropped the
position with a warning; delegating to the native fold turned it into an error for the whole query,
so a table holding one went from answering with the group removed to failing.

The fold now records the position as incompatible and drops it, which is the answer the legacy path
gave. `an_illegally_shaped_histogram_drops_its_position_rather_than_failing_the_query` pins it for
both kinds: the push answers `Ok`, the position's state is empty, and the warning names the
incompatible schemas.

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

* fix(promql): drop a state frame whose histogram cannot be read

`merge_batch` reads a partition's exported histogram the same way `push_histogram` reads a sample,
and made the same change: a state frame whose spans and buckets disagree became an error for the
whole statement, where the legacy path recorded the position as incompatible and dropped it. The
merge half now records it the same way, so a partition this crate cannot read is dropped rather
than failing the query.

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

* test(promql): pin what a one-sample fold does to an explicit empty bucket

The fold answers through `finished_histogram`, which compacts an explicit zero bucket away, so a
`sum` or `avg` over a single sample answers `[1]` where that sample carried `[1, 0]`. The legacy
accumulator kept the bucket before this refactor, because it handed a one-sample group's histogram
back untouched; the native `Aggregate` node has always answered the compacted form, so the two
paths agree now.

`promql_eq` tells an explicit zero bucket from an absent one, so `sum(h)` is no longer equal to the
single sample `h` it folded. Both tests document that, and the second one takes the answer through
a partial state round trip - `state()` into a fresh accumulator's `merge_batch()` - to show the
boundary does not re-introduce the bucket.

The comments on the three places that drop an unreadable layout now say what the code does rather
than how it differs from the accumulator this replaced: a layout this crate cannot read drops the
position as a whole, with the warning below, instead of failing the query.

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

---------

Signed-off-by: discord9 <discord9@163.com>
2026-11-24 09:16:36 +00:00
jeremyhi 82bdd7fd27 fix(mito2): keep a caught-up region writable on candidate leases (#10590)
* fix(mito2): keep a caught-up region writable on candidate leases

A region that a catchup made writable waits for its Leader lease until the
route switch. Meanwhile the metasrv keeps granting it Follower leases that
carry a candidate_lease_id, and each of them demoted the region, so the next
upgrade attempt had to catch it up again.

A Follower lease that carries a candidate_lease_id now leaves a region that
awaits its Leader lease alone. It checks the wait under the promotion fence,
so a concurrent catchup promotion is either seen or happens after the
demotion. Other Follower leases, and candidate leases to a region that does
not wait, demote it as before.

The store-api contract now says an engine may use the presence of the id
this way; it still must not interpret its value.

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

* docs(mito2): clarify the candidate lease wait and its tests

Describe the condition demote_candidate checks, name both lease kinds that
end the wait in the store-api contract, and check that a candidate lease
keeps a waiting physical region a leader that is not confirmed.

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

* fix: address review comments on candidate leases

Log the expected role mismatch of a migration target that a catchup promoted
before the route switch at debug, and explain the candidate-lease branch at
its call site.

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

* test(meta-srv): check the log level of an operating region's role mismatch

Also say that a candidate lease leaves a waiting region's state unchanged,
rather than writable, since a catchup again keeps such a region a follower.

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

* test(meta-srv): drop a redundant comment

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

* test(mito2): check that a candidate lease counts as applied

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

* fix: tighten the candidate lease log and comment

Choose the log level only for a role mismatch, say from the engine side why
the candidate branch stays out of MitoRegion::set_role, and tidy the test
helper.

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

* test(meta-srv): cover a matching Leader with a candidate lease id

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-24 08:22:02 +00:00
discord9 8e885bfed5 feat(promql): read the quantile parameter at every grid point (#10509)
`quantile(scalar(foo), v)` and `quantile(time()/2400, v)` were refused by the native compiler, which
bound the quantile with `constant_argument`. Prometheus reads an aggregate's parameter at every step,
and the kernel already does: `aggregate_quantile(schema, input, q: &Series, grouping)` looks the
quantile up per grid point and answers nothing where the parameter has no sample.

A scalar the statement evaluates now binds as a parameter subtree, in the shape `topk` already uses:
`NativeExpr::ParameterizedAggregate { input, op, parameter }` is appended to the enum (wire index 18;
the enum is append-only), so no field is added to `Aggregate` and the envelope version is unchanged.
`op` keeps its constant quantile unused, exactly as `ParameterizedTopK` ignores the `k` it carries.

A parameter the statement itself decides stays on the constant path - `quantile(0.25 + 0.1 + 0.15, v)`
is one number - and a vector argument keeps the refusal it always had, which the parser now states
first: `quantile(x, y)` is refused at type check before this compiler sees it.

The fold drains the parameter whole before its input, bills the held series in `QuantileInput`'s
bytes and settles what it no longer holds, so the pool is empty at the end. Validation accepts the
node only for a `Complete` quantile whose parameter is a scalar on the output grid, and a split still
declines a quantile, so no `Partial` or `Final` state can exist for it.

Signed-off-by: discord9 <discord9@163.com>
2026-11-24 07:35:34 +00:00
discord9 883ae6eaf7 fix(promql): answer a named selector over a missing table with the empty vector (#10472)
A selector that names a metric whose table does not exist made the native route decline the whole
statement, so the existing planner answered it. The route already has that answer when the selector
names no metric: a nameless selector that matches no table is planned as the typed empty input and
answers the empty vector. `setup_context` reports a missing table by returning the `EmptyMetric`
plan, which a native tree cannot bind, and the named path read that as "cannot plan" rather than as
"no rows".

The named path now pushes the same typed empty input the zero-match nameless path pushes, so
Prometheus' answers follow from the ordinary empty-input handling: a bare selector answers no rows,
`rate`/`sum`/`count`/`topk`/`sum by (__name__)` answer no rows (`sum` of nothing is empty, not 0),
`absent` answers one row holding 1 with a null name, `absent` over equality matchers carries those
labels, `absent_over_time` answers the same, and `or`, `and` and `unless` keep, drop or ignore what
the other side holds. A `__field__` matcher still declines, exactly as it does over a table that
exists: the matcher names the field layout a scan would have decided, so the route's boundary does
not depend on whether the table happens to exist.

A missing table whose metric is named after a column of the rows layout now answers instead of
failing: the free synthetic time-name rule the data-free route already used is shared, so `time`
publishes its grid as `native_time_0` beside its own `time` value column, and a value column that
would collide with the mandatory row-name column (`__name__`) declines and keeps the existing plan's
empty answer.

A pointwise chain above an evaluated-input subquery is deliberately NOT admitted here. Cutting a
segment replaces the window under the chain with a boundary, and a window that would have collected
one label set's contributions stops collecting them once its input is a leaf; a window-local proof
cannot establish whole-query uniqueness either, because the outer wrapper drops the metric name
again and the duplicate guard is partition-local. Chains keep the plan they had. #10531 tracks the
cut defect, and the identity enforcement that a future admission would need.

A `__field__` matcher no longer changes the answer for a missing table: a field selection over a
table with no rows is empty either way, so the statement answers the empty vector natively, exactly
as the existing planner does - it returns the `EmptyMetric` plan before any matcher projection runs.
Over a table that exists the matcher still declines this route, because there it narrows a real
scan's field set, which a raw-series scan cannot report.

The nameless zero-match branch no longer declines a `__field__` matcher either: a selector that
matched no table has no field set to narrow, so both spellings answer the empty vector.

The synthetic grid name is now chosen before the segmented root is built. `absent(missing{time="x"})`
publishes a label named `time` while the route would name its grid column `time` too, and choosing the
free name only on the single-input path meant schema construction failed first and the statement left
the route; it now answers one sample of 1 carrying the matcher's label.

Signed-off-by: discord9 <discord9@163.com>
2026-11-24 07:30:45 +00:00
dennis zhuang f51d01b185 fix(datatypes): bounds-check Vector::get and get_ref (#10594)
The indexed accessors checked is_valid() and then called
value_unchecked(), but is_valid() is not a bounds check: it returns true
for any index when the array has no null buffer. An out-of-range index
read past the array buffers instead of panicking.

Use the bounds-checked value() accessors. This also covers
DictionaryVector, whose lookups go through the item vector's get().

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-24 06:53:16 +00:00
dennis zhuang a7693d52b6 fix(servers): require authentication for debug endpoints (#10592)
* fix(servers): require authentication for debug endpoints

The /debug routes are added after the HTTP middleware stack, so they did
not go through the auth layer, and need_auth() only covered /v1/.

Apply the auth middleware to the /debug routes and treat the /debug
namespace as requiring authentication when a user provider is
configured.

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

* docs: pass credentials to debug endpoints in profiling guides

Let dump.sh read curl credentials from the config file in
GREPTIME_CURL_CONFIG, and document authentication for the /debug
endpoints in the profiling and log level guides.

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-24 06:32:07 +00:00
discord9 c2a15bdebf perf(promql): return a fixed plan-metrics set instead of cloning the live one (#10525)
Signed-off-by: discord9 <discord9@163.com>
2026-11-24 06:25:01 +00:00
Yingwen 216135381b feat(mito): integrate opt-in authoritative Narthex storage (#10526)
* feat(mito): integrate opt-in authoritative Narthex storage

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

* fix(mito): restrict Narthex storage to one value field

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

* fix(cmd): handle Narthex in direct SST fixture writer

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

* refactor(mito): clarify Narthex encoded bulk part support

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

* refactor(mito): type Parquet bulk iterator inputs explicitly

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

* refactor(mito): route Narthex storage by region format

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

* fix(mito): address authoritative Narthex review findings

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

* docs: remove implementation notes from samples format spec

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

* fix(mito): rely on canonical metric write keys

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

* fix(mito): refine Narthex scan and copy semantics

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

* fix(mito): reject raw sparse writes and exclude series scans from windowed sort

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

* fix(mito): allow sparse bulk companion tags and simplify manifest admission

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

* refactor(mito): make Narthex scan preparation optional

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

* fix(mito): prune Narthex samples in stored time units and share bulk blocks

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

* test: track sparse exemplar write failures

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

* test: track remaining observed sparse exemplar failures

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

* test: isolate sparse write regressions across ingestion paths

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

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
2026-11-24 06:15:03 +00:00
Ning Sun f796889bbd feat(postgres): jsonl COPY FROM STDIN via the arrow-json engine (#10109)
* 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>

* feat(postgres): address jsonl COPY review — codec names, nullable-aware errors, docs and tests

- `TableBoundCodec::name()` drives the codec name `CopyInState` logs
  instead of the hardcoded "csv"; `table_bound_state` reuses the query
  context `begin_copy_in` created; the csv/jsonl trait impls hold their
  bodies and share one supported-type check.
- jsonl: the decode schema marks every field nullable, so a NULL in a
  non-nullable column is reported by column name instead of arrow-json's
  "unmasked nulls in non-nullable StructArray child" error; errors map
  to 22P02/22P04 by semantics (field value vs. syntax), never XX000; the
  no-op `decode(&[])` EOF signal is gone; a top-level JSON array under
  `FORMAT json` fails with a specific hint instead of `expected { got [`.
- Module docs describe what arrow-json really accepts: numeric strings
  for numeric columns, numeric timestamps taken in the column's unit,
  unknown keys ignored (strict mode stays off so column subsets work).
- Tests: multi-batch sweep through the mid-stream flush path, trailing
  and truncated records, column subset/reorder with extra keys, missing
  and null ts, the `json` alias, error classes.

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

---------

Signed-off-by: Ning Sun <sunning@greptime.com>
2026-11-24 03:53:00 +00:00
fys 5072612b77 chore: fix cargo-shear warnings in common-telemetry and session (#10595)
Signed-off-by: fys <fengys1996@gmail.com>
2026-11-24 03:06:23 +00:00
dennis zhuang 3b2b67212a fix(servers)!: validate UTF-8 in unchecked Prometheus validation mode (#10593)
fix(servers): validate UTF-8 in unchecked Prometheus validation mode

prom_validation_mode = "unchecked" built Strings from request bytes with
String::from_utf8_unchecked. Invalid UTF-8 in label values produced
invalid Strings, and the rows were written to WAL entries that fail to
decode on replay.

Make unchecked behave like lossy: invalid sequences are replaced with
U+FFFD. The config value is kept for compatibility.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-24 03:05:39 +00:00
boaz2026andBoaz Shuster 8863133d88 fix(function): align INSERT negative len handling with MySQL (#10519)
Signed-off-by: Boaz Shuster <boaz.shuster.github@gmail.com>
Co-authored-by: Boaz Shuster <boaz.shuster.github@gmail.com>
2026-11-23 21:01:14 +00:00
dayan02devanddennis zhuang f1b4dc695e fix(query): stop reporting CTEs as missing tables in range queries (#10397)
* test(query): cover range queries over derived inputs without a time index

A range query over a CTE or an aliased subquery whose columns carry no
time index fails with `Table not found: greptime.public.<alias>` (#5839),
while the same input without an alias reports `Cannot find time index
column`. Plan all three shapes in a planner test and expect the time
index error, and add the CTE case to the `range/error` sqlness case.

Signed-off-by: dayan02dev <pawarudayan92@gmail.com>

* fix(query): report missing time index for range queries over CTEs

`RangePlanRewriter::get_index_by` resolves each field qualifier of the
range input as a table. A CTE or subquery alias is not a table, and the
resulting `TableNotExist` was skipped only when some field still carried
time index metadata. Without that metadata it was returned as is, so a
range query over such a CTE failed with `Table not found:
greptime.public.<cte>` (#5839).

Skip qualifiers that are not tables in every case. The input then falls
through to the existing time index metadata fallback or to
`TimeIndexNotFound`, which the same input already gets without an alias.

Signed-off-by: dayan02dev <pawarudayan92@gmail.com>

* test(query): drop derived-input time index unit test covered by sqlness

Signed-off-by: dayan02dev <pawarudayan92@gmail.com>

---------

Signed-off-by: dayan02dev <pawarudayan92@gmail.com>
Co-authored-by: dennis zhuang <killme2008@gmail.com>
2026-11-23 20:20:51 +00:00
dayan02dev f15fd9a706 fix: reject JSON integers outside the u64/i64 range instead of rounding them (#10481)
* test: reject JSON integers outside the u64/i64 range

Signed-off-by: dayan02dev <pawarudayan92@gmail.com>

* fix: bump jsonb to reject integers outside the u64/i64 range

Signed-off-by: dayan02dev <pawarudayan92@gmail.com>

---------

Signed-off-by: dayan02dev <pawarudayan92@gmail.com>
2026-11-23 20:19:08 +00:00
dennis zhuang b26b87f914 perf(mito2): split seq scan ranges of files with disjoint primary keys (#10561)
* perf(mito2): split seq scan ranges of files with disjoint primary keys

Seq scan merged every SST whose time range overlapped another into one
partition range. Compaction outputs split by max_output_file_size cover
the same time range with disjoint primary keys, so a compacted window was
read and deduplicated by a single partition.

Ranges are now merged only when both their time ranges and their
primary key ranges overlap. Memtables and files without key statistics
still overlap every key.

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

* perf(mito2): index open seq scan groups by primary key

Grouping compared each range with every open group, so n files with
disjoint keys in one time window took n(n-1) checks. Open groups now
sit in a BTreeMap keyed by their min primary key; their key ranges are
disjoint, so one range lookup finds every group to merge. Groups that
ended before the current range are closed when a lookup reaches them.

Per-series scans keep grouping ranges by time only.

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

* perf(mito2): merge the smaller seq scan range into the larger one

A range that joined many groups, such as a memtable overlapping many
files with disjoint keys, was appended to each group in turn and copied
its growing index lists every time. Merges now append the smaller range
to the larger one, so each index is copied O(log n) times.

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

* docs(mito2): clarify the seq scan grouping invariant and lookup cutoff

State that grouping keeps every version of a (primary key, timestamp)
pair together, instead of "ranges in different groups never share a
key", which read as if one key could not appear in two groups. Explain
why the reverse BTreeMap walk can stop early: disjoint key ranges order
their upper bounds the same as their lower bounds.

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

* fix(mito2): split seq scan ranges by primary key only without a distribution

TimeWindowed scans advertise (ts, primary key) ordering. Key-disjoint
ranges that partition assignment reorders inside one partition would not
keep it, so scans with any distribution keep grouping ranges by time.

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

* docs(mito2): state that SeqScan does not keep the TimeWindowed ordering today

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

* fix(mito2): locate the primary key column by its top-level path

A nested field such as a JSON child named __primary_key has the same leaf name and comes first, so the bounds and the primary key projection could read the wrong column.

Closes #10582

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

* refactor(mito2): rename files_time_range_pruned to files_manifest_pruned

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-23 12:48:21 +00:00
discord9 cdc1ec6b16 fix(table): restore dynamic statistics pruning for nullable keys (#10502)
* fix: restore dynamic statistics pruning for nullable sort keys

Checkpoint: requires the complete DataFusion #25579 producer fix before integration. Local validation uses upstream-backport commit 92d537be1ee8395311daa4dce61d6e13fd0a458f; dependency pin is intentionally unchanged pending final acceptance.
Signed-off-by: discord9 <discord9@163.com>

* docs(table): remove empty line after dyn filter doc

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

* fix(table): keep PhysicalBinaryExpr import

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

---------

Signed-off-by: discord9 <discord9@163.com>
2026-11-23 10:05:42 +00:00
discord9 b948fb78b1 fix(promql): plan absent_over_time over a nameless multi-metric selector (#10512)
`absent_over_time({job="x"}[20m])` was declined by the native route, and the plan it fell back to
answers with an error, so the shape produced no answer at all: the existing planner needs one
`__name__` equality matcher to read a table from (`Expect a metric matcher, but not found`).

The guard that declined it assumed that a nameless selector's tree declares `__name__` while binding
no metric name, and that the fused node refuses such a tree. That is not the shape: a discovered
selector's prepared input is the `Union` of one `RawSeriesSource` per metric, so the node is handed
explicit-label frames, and only its bare-region-scan arm reads the binding's name - an arm a nameless
selector never reaches, because a successful scan always binds one metric. A statement such as
`sum by (__name__) ({tag_0="x"})` over discovered metrics already builds and runs exactly this
combination.

The guard now declines only a nameless input that is not already sourced, which keeps the bare-scan
arm closed if that invariant ever regresses. The presence fold keeps the metric name, so two metrics
sharing ordinary labels stay two series and `absent` answers the empty vector, as Prometheus does;
a fold that dropped the name would have folded them into one series and answered wrongly.

`is_sourced_plan` is the existing predicate factored out of the child mapping, so the guard and the
mapping ask the same question. `FusedSeriesBinding::metric_name`'s doc no longer claims the logical
node requires a name whenever `tags` declares `__name__`; the requirement belongs to the bare-scan
arm of the physical planner.

A statement that mixes a multi-metric discovery with a single-metric selector was admitted and then
failed at physical planning: `build_inner_segment`'s multi-source arm wrapped every prepared plan in
a new `RawSeriesSource`, including plans that were already sources, and built
`RawSeriesSource(RawSeriesSource(TableScan))`, which the physical planner refuses after the statement
has been committed to this route. The arm now hands an already-sourced plan to the segment as it is
and wraps only real table scans (`is_sourced_plan`).

Regression: `absent_over_time({job="api"}[5m]) or ({probe_label="y"} + on(job) absent_a)` was
unanswerable before that fix and now runs a `FusedSeriesExec` and answers
`(120000, {job="api"}, 7.0)` and `(400000, {job="api"}, 1.0)`.

Not changed: a statement whose discovered table is partitioned still declines, because
`remote_raw_boundary` skips this builder and the alternative does not recognise a `Union`.

Signed-off-by: discord9 <discord9@163.com>
2026-11-23 08:59:55 +00:00
dennis zhuang 71cdb4bccc perf(mito2): bound row group bytes and skip statistics for large field values (#10528)
* perf(mito2): bound row group bytes and skip statistics for large field values

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

* fix(mito2): size row groups by decoded value bytes

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

* refactor(mito2): import helpers instead of using qualified paths

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

* fix(mito2): skip statistics for large view values and empty first batches

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

* fix(mito2): record decoded value bytes per row group in the footer

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

* refactor(mito2): keep only the largest row group value bytes in the footer

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

* fix(mito2): size read batches by recorded decoded value bytes

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

* fix(mito2): record the widest row group row width for read batch sizing

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

* refactor(mito2): pick the widest row group statistic for read batches

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

* fix(mito2): keep row group size metadata compatible and index segments aligned

FileMeta::max_row_group_uncompressed_size held the decoded value bytes,
which older table compaction verifiers reject because they recompute it
from the column chunk sizes of the footer. The field keeps its original
meaning again. Compaction now sizes output row groups from the decoded
value bytes recorded in the input footers, once it has read them.

Row group sizes below the configured value are rounded down to a
multiple of the default inverted index segment. A row group size that
is not a multiple of the segment makes the index use whole row groups as
segments.

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

* fix(mito2): size compaction from decoded bytes and keep index segments

Both compaction paths now size output row groups from the decoded value
bytes recorded in the input footers. Regular compaction reads them with
the input footers; multi-region compaction computes them once from its
source footers. The FileMeta based estimate is removed.

FileMeta gains max_row_group_decoded_size, written by flush, compaction,
bulk parts and multi-region outputs and omitted from manifests when
unknown. Compaction memory admission uses the larger of it and the
uncompressed size, and multi-region admission counts decoded bytes from
footers. Table compaction verifies the field when it is set.

The inverted index keeps the configured segment size instead of widening
segments to the row group size. Readers since v1.2.0 split segments at
row group boundaries; earlier readers cannot read such files correctly.

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

* refactor(mito2): destructure the compaction reader and row group size in place

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

* fix(cmd): recompute row group value sizes when rewriting parquet files

parquet-rewrite copies the input footer metadata, but it can change the
row group row count, which makes the recorded decoded value sizes stale.
Drop them from the copied metadata and recompute them for the output row
groups.

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-23 08:58:33 +00:00
jeremyhi 946e599d81 fix: catch up a writable region that still awaits its Leader lease (#10559)
* feat(store-api): ask an engine whether a region is a confirmed leader

Add RegionEngine::is_confirmed_leader. It answers None for a region the
engine does not find, Some(false) for a follower or, on a node that
requires leases to confirm its leaders, for a leader that a catchup
promoted and that no Leader or StagingLeader lease has confirmed since,
and Some(true) otherwise. The default answers from the role alone, with
the mapping RegionServer::is_region_leader uses.

Document that set_region_role_with_lease also returns false while a
catchup runs on the region or it waits for a reload, and that a catchup
also applies to a leader that is not confirmed.

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

* fix(mito2): catch a writable region awaiting its Leader lease up again

A migration that rolls back after its catchup can leave the target
region writable but waiting for a Leader lease that never comes, while
the source keeps acknowledging writes. A later upgrade must catch it up
again instead of treating it as ready.

- MitoEngine::is_confirmed_leader reads the role and the lease wait of
  one instance together under the promotion fence lock.
- begin_catchup checks, under that lock, whether the region still awaits
  its lease; if it does, it demotes the region, raises the downgrade
  time so earlier Leader leases are ignored, and marks the catchup. The
  handler then cancels the region's tail replay and reopens it if its
  memtable is not empty or its manifest changed. A catchup in progress
  or a pending reload answers RegionBusy before any demotion.
- Before a remote WAL replay the catchup waits until the entries the
  region acknowledged on this node are durable. If the wait fails, the
  catchup fails and the region stays a follower.
- While a catchup runs, a Leader or StagingLeader lease is still recorded
  and still extends the deadline, but neither promotes the region nor
  ends its wait; the catchup promotes it when it ends with set_writable.
  A catchup that fails or does not set the region writable lets the next
  lease promote it.
- MitoRegion::stop marks the fence stopped, and remove_region stops the
  region before it leaves the region map, so neither a catchup nor a
  Leader lease promotes a closed instance; such a catchup answers
  RegionNotFound.
- MitoEngine::extend_leader_deadline lets an engine that groups regions
  extend the deadline of a region that was not handed a lease.

Every catchup uses the source's replay checkpoint as before.

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

* fix(metric-engine): confirm a physical region only with both its regions

A physical region is a confirmed leader only if both its metadata and its
data region are, since a catchup may have promoted one without the
other.

A Leader lease that the metadata region ignores, for example while it
catches up, is still not handed to the data region, but it is now
recorded for the data region and extends its deadline, as mito does for
a lease it ignores.

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

* fix(datanode): catch up an upgraded region that is not a confirmed leader

The upgrade handler asks the engine once whether the region is a
confirmed leader and reports only such a region ready without a
catchup. A writable region that still awaits its Leader lease is sent a
catchup with set_writable, which catches it up again.

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

* refactor(mito2): share the end of a successful catchup

Move the part of a successful catchup that finalizes the leadership of a
promoted region, ends the catchup and replies into CatchupFinish, so
another catchup path can end the same way. No behaviour change.

Also fold two doc comment lines in region.rs that ran past 100 columns.

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

* fix(mito2): replace a region caught up again only if its replay succeeds

A catchup of a region that awaits its Leader lease opened its replacement,
registered it at once and dropped the old memtable before the replay. If
the durability wait or the replay then failed, the next Leader lease could
promote the empty or partial replacement, and a retry read the smaller
last entry id of the replacement, so it no longer waited for the entries
the region had acknowledged.

Now the old instance stays registered while an unregistered replacement
opened from its manifest waits for durability and replays the WAL outside
the worker. The worker registers and promotes the replacement only if the
replay succeeded and the old instance is still registered, does not wait
for a reload or a flush, and neither committed nor took a write meanwhile,
with or without the WAL. The catchup demotes the old instance unless it
is in a transient leader state, so a failed edit can make it writable
again. Otherwise the old instance ends its catchup, so a later Leader
lease can promote it with its memtable. A region that a failed catchup
again demoted still awaits its lease, so a retry takes the same path.

Every catchup from a remote WAL now also fails if its replay ends below
the last entry the region acknowledged on this node. A manifest sync of a
follower that awaits its Leader lease is refused, since it would replace
the memtable the region keeps.

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

* chore(mito2): log a refused manifest sync and drop two restating comments

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

* test: consolidate the catch-up-again tests

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

* test(mito2): cover rows dropped by a catchup again and fix review nits

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-23 08:51:02 +00:00
Weny Xu 52aaf87d83 fix(repartition): pause metadata compaction and clean up copied SSTs during sync (#10541)
* fix(metric-engine): pause target compaction during metadata sync

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

* fix(metric-engine): identify compaction pause failures during metadata sync

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

* test(mito2): cover concurrent compaction pause waiters on cancellation and failure

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

* docs(mito2): clarify compaction admission after a pause

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

* test(mito2): verify pause initiates local compaction cancellation

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

* fix(metric-engine): remove residual source metadata on sync retry

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

* fix(repartition): pause source metadata compaction while syncing targets

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

* refactor(repartition): share metadata compaction pauses per source region

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

* refactor(repartition): release source compaction pauses by region

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

* fix(metric-engine): clean up imported SSTs when metadata transform fails

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

* fix(repartition): retry metadata sync when copied files disappear

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

* fix(metric-engine): clean up residual source metadata after sync retries

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

* fix(mito2): release compaction pauses when requesters stop waiting

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-23 08:34:17 +00:00
discord9 82ed828ded perf(promql): hand series chunks between native operators in process (#10506)
* perf(promql): introduce the in-process series plan and chunk handover

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

* feat(promql): hand aggregate state between native operators as chunks too

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

* feat(promql): read children as chunks and hand fused outputs over in process

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

* fix(promql): keep the chunk handover's checks and accounting honest

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

* fix(promql): hold a handed-over state to the checks the frame path makes

A router that reads chunks applied none of what a router that reads batches
applies: it routed state of any kind, layout or grid, and it released the
child's charge for a publication while the groups cut from it were still
queued, so a retained row was charged for its slice and not for the batch it
slices.

The chunk path now holds a publication to the declared state - kind, ordered
components, grid, field count - and refuses one that differs, with the error
the frame path raises for a mismatching batch. The child's charge moves onto
every group cut from the publication and travels with the handed value, so a
retained row keeps the parent batch charged.

State rows gain one constructor for their layout: `StateRowLayout` resolves the
field struct, the field count and the grid once per publication and `row`
builds the row against them, so a group costs its own encoding, and the grid
and no-contribution checks that `state_row_from_frame_row` made now hold for
every row rather than being deferred to the consumer.

Tests: a held state group outlives the export that produced it; a chunk-fed
router keeps the parent batch charged until its row is dropped; a chunk of
another state is refused and a duplicated input survives the chunk path as it
does the frame path; a state row refuses positions on another grid and a
position no field carries.

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

---------

Signed-off-by: discord9 <discord9@163.com>
2026-11-23 08:26:22 +00:00
dennis zhuang 0ab8dcb866 fix(sql): keep column options in ALTER TABLE ADD COLUMN (#10556)
* fix(sql): keep column COMPRESSION options in ALTER TABLE ADD COLUMN

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

* fix(sql): build ADD COLUMN definitions through the CREATE TABLE conversion

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

* fix(sql): keep added columns out of the time index and drop unused arrow-schema

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

* docs(sql): describe the shared column schema conversion

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

* test(sql): write, flush and read back columns added with options

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-23 08:05:17 +00:00
dennis zhuang 2effff48d5 perf(mito2): prune files by their primary key range before reading footers (#10564)
* perf(mito2): prune files by their primary key range before reading footers

File-level pruning used only the manifest time range, so a scan read the footer of every file in the time range even when the file's primary key range excludes the predicate. The file-level pruning statistics now include the min and max of the first primary key column, decoded from FileMeta's primary key range, so such files are skipped without a footer read. For metric engine physical regions the first column is the table id.

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

* test(mito2): cover file pruning by primary key range end to end

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

* perf(mito2): decode the file primary key range only when pruning uses it

Predicates on the time index or fields never ask for the first primary
key column, so they no longer build a codec and two arrays per file.

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

* fix(mito2): prune files by primary key ranges loaded from footers

Region open can fill a file handle's key range from the SST footer when
the manifest has none. Let the handle decide whether bounds are known,
so those files are pruned too.

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

* test: check file pruning by primary key range with EXPLAIN ANALYZE

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-23 08:04:54 +00:00
discord9 0ce4799e48 feat(query): opt-in experimental factorized join aggregation rewrite (WIP) (#9546)
* feat(query): opt-in experimental factorized join aggregation rewrite

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

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

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

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

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

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

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

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

Address the blind review of PR 9546:

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

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

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

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

Address the post-fix review of PR 9546:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Address the post-ready review of PR 9546:

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

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

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

---------

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
2026-11-23 07:27:14 +00:00
shuiyisong 517a1376e2 fix(otlp): reject malformed cumulative histogram points (#10552)
* fix(otlp): reject malformed cumulative histogram points

Signed-off-by: shuiyisong <xixing.sys@gmail.com>

* refactor(otlp): check bucket sum overflow once

Signed-off-by: shuiyisong <xixing.sys@gmail.com>

---------

Signed-off-by: shuiyisong <xixing.sys@gmail.com>
2026-11-23 06:31:37 +00:00
discord9 b6d9debf55 refactor(promql): fold the legacy histogram aggregate through the native kernel (#10505)
* refactor(promql): fold the legacy histogram aggregate through the native kernel

`aggregate_histograms` was the last caller of a hand-rolled histogram fold: it walked a
group's series point by point, dropped a point where a member held a float, and answered the
rest. #10199's `HistogramAccumulator` does the same fold for the native `Aggregate` node, and
`range_eval`'s `sum_over_time`/`avg_over_time` already reach it through `sum_or_avg`, so the
entry point had no production caller left.

Its golden coverage moves onto `aggregate_float`, which is the kernel the native node runs:
the 241 Prometheus v3.15.0 aggregate cases, the mixed-layout and invalid-layout verdicts, and
the shape test that names only the runs a sparse input produces, all assert the same output as
before.

Two differences come with the kernel and are recorded rather than hidden. A group that mixes
float and histogram samples is refused by the fold where the old walk dropped the points a float
sat on; no Prometheus fixture answers a histogram at a step that also carries a float, and a
GreptimeDB field column is single-typed, so the two kinds are planned as two aggregates. And a
fold that added nothing now answers `+0.0` where the old path kept the seed sample's `-0.0`,
because the accumulator always adds its compensation; one of the 241 cases has such a point and
the comparison canonicalises a zero's sign.

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

* refactor(promql): fold the legacy histogram aggregate through the native kernel

`aggregate_histograms` was the last caller of a hand-rolled histogram fold: it walked a group's
series point by point, dropped a point where a member held a float, and answered the rest.
#10199's `HistogramAccumulator` does that fold for the native `Aggregate` node, so the entry point
had no production caller left. The range functions are not that caller and not that fold:
`range_eval`'s `sum_over_time`/`avg_over_time` fold a window through `sum_or_avg`, a second fold
(`histogram_eval/aggregate.rs:44-120`) whose first item only seeds the value and leaves the
compensation `None`, while the aggregate node runs `HistogramAccumulator` and answers through
`finished_histogram`.

Its golden coverage moves onto `aggregate_float`, which is the kernel the native node runs: the
241 Prometheus v3.15.0 aggregate cases, the mixed-layout and invalid-layout verdicts, and the
shape test that names only the runs a sparse input produces. A group whose samples are all
histograms asserts the same output as before. A group that carries both a float and a histogram is
asserted to be refused, on its raw input rather than with the mixed steps taken out first: 138
such groups are refused, and the 140 fixture answers that sit on them -- a fixture only answers such
a group's unmixed steps -- are no longer compared.

The comparison reads every series the kernel answers. A group it returned but the fixture does not
expect fails, whether the group is missing, duplicated, or carries a row of the wrong kind; a group
the fixture expects but the kernel left out fails too. That is what keeps a group the fixture
expects nothing from apart from a group the assertion quietly discarded, which the retired shape of
this test could not tell apart. An input with no comparable group is still evaluated and checked
against its own case, so an empty case cannot borrow the verdict of the one before it.

Two differences come with the kernel and are recorded rather than hidden. A group that mixes float
and histogram samples is refused whole, not step by step: `Group::accumulate` rejects a column that
holds both, and `finish_histogram_group` rejects a group that folded a float anywhere. The planner
does not split the query per kind to accommodate that -- a `sum(h)` over scans whose field kinds
disagree has no native plan at all (`planner/native.rs:358-368` takes `uniform_field_kind` and
returns `Ok(None)`; `native/plan.rs:508-524` accepts only a uniform `Float64` or a uniform
histogram struct, and `native_compile.rs:1009-1031` binds the aggregate's `field_kind` from its
input's kind) -- and a GreptimeDB field column is single-typed. And a fold that added nothing
answers `+0.0` where Prometheus hands the seed sample's own `-0.0` back, because this accumulator
always seeds a compensation and always adds it; five fixtures hold such a sum
(`native_cases.txt:4305,4410,4464,4513,4569`), the three in a compared group pin `+0.0` here
against `-0.0` there, and no other field or position shrugs a sign off.

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

---------

Signed-off-by: discord9 <discord9@163.com>
2026-11-23 04:31:59 +00:00
dennis zhuang 94e0af6850 perf(mito2): box file range streams to reduce state copies (#10235)
perf(mito2): prototype boxing file range scan streams

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-23 02:36:05 +00:00
sun 8787551393 feat: update dashboard to v0.14.7 (#10551) 2026-11-21 04:06:42 +00:00
jeremyhi 83bf74193f refactor: reuse the backend for packed database exports (#10482)
* refactor: reuse packed export destination backend

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

* test: cover managed packed routing and update CLI writer caller

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

* fix: reuse packed backend for logical table exports

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

* refactor: reuse the owned file path in managed exports

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-20 13:12:54 +00:00
Weny Xu b4ce259859 refactor(meta): make coordinated invalidation the default for metadata caches (#10550)
* refactor(meta): make coordinated invalidation the default for metadata caches

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

* refactor(meta): avoid boxing key invalidation futures

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

* fix(meta): allow borrowed cache invalidation tokens

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-20 13:06:36 +00:00
jeremyhi 5952a49e2f fix(mito2): wait for a Leader lease before committing after a catchup (#10544)
* fix(mito2): wait for a Leader lease before committing after a catchup

On a datanode whose writes need a lease, a catchup makes a migration
target writable before the route points to it. Until a Leader or
StagingLeader lease of a heartbeat sent after the catchup applies, such
a region commits to its manifest only replayed WAL tails and what it
commits while downgrading; any other commit fails with the retryable
RegionLeaseNotReceived in ManifestContext::update_locked. No flush or
compaction trigger starts work for it, a write over its own write buffer
is rejected as for a staging region, and a close that must flush
downgrades it first.

The lease that ends the wait tells the region's worker once. The worker
schedules the engine-full and region-full flushes and, if the region is
then a writable leader, starts a compaction, builds missing indexes in
async index mode and persists the metadata the opener backfilled.

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

* test(mito2): refuse a discard of pending tails while awaiting the Leader lease

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

* fix(mito2): keep extension indexes in the lease-end index pass

The index pass at the end of a wait for the Leader lease is a flush
build of every file, which builds no extension index, so it replaced
the index of a compacted file whose sketch the compaction built. It now
skips files that have an extension index, as the background build after
a compaction does, through the same check.

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

* fix(mito2): drop the FileMeta import the moved check left unused

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

* test(mito2): share the sketch region setup of the index build tests

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

* test(mito2): check the lease-end index candidates where they are chosen

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

* test(mito2): select and test the whole-region index builds in one function

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

* fix(mito2): start no checkpoint while awaiting the Leader lease in every publication mode

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

* fix(mito2): pin no memtable while persisting backfilled metadata

The backfilled metadata save keeps only the region metadata and SST
format across its manifest write instead of the whole version, so a
flush applied meanwhile frees its memtable. Test that a save the end of
a lease wait spawns asks the worker to reload the region it fences, and
describe update_locked as the lease check around the shared write that
a tail replay makes directly.

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

* test(mito2): test the backfill save's reload request on the task itself

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

* refactor(mito2): address the review of the lease wait carve

Name the spawned backfill task for both of its steps, select the
whole-region index builds from file handles, reuse promote_with_lease
in the new tail replay tests, and make the docs, AGENTS.md and comments
say what the code does: the hook entry points, the discard that the
lease check refuses, the background flush triggers and the region write
buffer threshold of a waiting region.

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

* docs(mito2): describe the hook entry point as the write behind update_locked

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

* test(mito2): check the deferred compaction as it is scheduled

The replay's commit clears the pending tails before the worker decides on its compaction, so a count read after the replay could miss a compaction scheduled during the wait. The listener now checks the wait whenever a compaction is scheduled.

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

* fix(mito2): build index retries refused while awaiting the Leader lease after it

A retry of an index build whose publication found the schema changed has no caller to try again. When the region awaits its Leader lease the worker refused it, and the lease-end pass does not cover files with an extension index or build types other than flush. The worker now keeps such retries per region and re-issues them through the normal handler when the lease ends the wait with the region a writable leader. Closing or dropping the region clears them.

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

* test(mito2): gate the deferred compaction check on the end of the replay

The worker reports the replay's end after it handled the replay's commit and its compaction decision, so the check no longer needs to watch the region. The retry test needs no WAL listener.

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

* test(mito2): publish the end of a tail replay with release ordering

A test that observes the end of a replay then reads counts the worker's earlier callbacks set, so the end is stored with release and read with acquire.

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

* fix(mito2): forget kept index build retries when the worker cleans up

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-20 13:05:34 +00:00
shuiyisong 3d52f9f640 perf(auth): skip unnecessary catalog lookups for table permissions (#10539)
* perf(auth): skip unnecessary catalog lookups for table permissions

Signed-off-by: shuiyisong <xixing.sys@gmail.com>

* docs(auth): clarify what precheck Allow authorizes

Signed-off-by: shuiyisong <xixing.sys@gmail.com>

---------

Signed-off-by: shuiyisong <xixing.sys@gmail.com>
2026-11-20 07:36:45 +00:00
discord9 dd4845c38a perf(table): compile a regex predicate once per scan instead of once per batch (#10517)
* perf(table): compile a regex predicate once per scan instead of once per batch

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

* perf(recordbatch): borrow a regex cache once per array instead of per row

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

* perf(recordbatch): borrow a regex cache from a pool and defer its compilation

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

* perf(table): keep the regex rewrite off the pruning path

`prune_with_stats` folds a predicate into column statistics and never evaluates
it, so the precompiled-regex rewrite bought nothing there: the pruning
predicate builder replaces nodes it does not recognize with `true`, and the
rewrite ran per file (manifest pruning) and per batch (bulk memtable pruning).

Split the two conversions: `to_physical_expr` stays the evaluating entry point
and keeps `PrecompiledRegexExpr`; the new `to_pruning_physical_exprs` builds
what `create_physical_expr` builds, with the `DFSchema` built once per call
instead of once per expression.

Also pin the pool's concurrency property without a clock: eight cache guards
held and used at once, asserting eight acquisitions over one compilation.

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

---------

Signed-off-by: discord9 <discord9@163.com>
2026-11-20 06:39:47 +00:00
jeremyhi 5dec7b1986 feat(meta-srv): check pending WAL tails before a repartition starts (#10504)
* feat(meta-srv): check pending WAL tails of source regions before a repartition starts

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

* test(common-meta): freeze the region statistic encodings before the pending tails flag

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

* fix(meta-srv): clarify the repartition pending tails errors and pin the flag encoding

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

* fix(meta-srv): retry repartitions over pending WAL tails and pass sources without a report

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

* docs(meta-srv): note the retained leader report in the repartition pre-check

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

* fix(meta-srv): report pending repartition tails as region not ready and share is_false

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

* style(meta-srv): order the repartition pre-check test imports

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-20 05:16:35 +00:00
Weny Xu 1ba656e345 perf(catalog): batch cached metadata reads for information schema scans (#10542)
* feat(meta): support cached batch lookups for flows and views

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

* feat(partition): batch-load cached routes for partition scans

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

* perf(meta): bound marker reads when listing dropped tables

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

* perf(catalog): stream information schema scans through metadata caches

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

* fix(catalog): gate the recycle bin metadata accessor

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

* fix(meta): coordinate schema, view, and flow cache updates

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

* perf(operator): bound concurrent flow lookups for multi-table writes

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

* refactor(meta): reuse cache key and batch value conversions

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

* refactor(catalog): extract metadata loaders from information schema scans

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

* fix(catalog): remove unused scan dependencies

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

* chore: align metadata cache visibility and API documentation

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

* refactor(meta): share physical routes across logical table lookups

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

* refactor(catalog): share metadata loaders across scan paths

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

* test: verify cache batch reads and information schema options

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

* test(sqlness): order information schema table rows before comparison

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

* fix(catalog): finish partition lookups before loading the next table batch

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

* fix(meta): load all source table flows on a cold lookup after create

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-20 04:58:15 +00:00
discord9 4eca3194bb test(query): skip the far-future overflow test when SystemTime cannot represent it (#10545)
Windows SystemTime and 32-bit time_t targets cannot represent the 5e18 ms statement start, so checked_add returns None before the planner sees the query. Skip the high-level shape there; the platform-independent native_tree_supported_declines_the_instants_that_overflow test still covers the admission predicate.

Signed-off-by: discord9 <discord9@163.com>
2026-11-20 04:44:51 +00:00
Weny Xu 6458142398 fix(mito-codec): align sparse metric rows with physical region fields (#10543)
* fix(mito-codec): align sparse metric rows with physical region fields

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

* test(mito-codec): cover sparse rows in single-field regions

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-20 04:12:28 +00:00
Weny Xu 47e066aad8 perf(metric-engine): stream metadata copies during repartition (#10535)
* fix(metric-engine): stream metadata copies during repartition

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

* fix(metric-engine): tune copy batches and report invalid source metadata

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

* refactor(metric-engine): express metadata copy payload limit with ReadableSize

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

* test(metric-engine): cover metadata batch limits and marker replay

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

* test(metric-engine): verify multi-batch metadata copies from SST

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-20 04:07:31 +00:00
Weny Xu 7fa5dc5f54 perf(metric-engine): share logical column metadata by physical table (#10536)
* perf(metric-engine): share logical column metadata by physical table

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

* refactor(metric-engine): reuse physical schema lookups across DDL and reads

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-20 04:05:36 +00:00
jeremyhi 006cae6283 fix(meta-srv): skip upgraded regions on retry and recheck routes in region migration (#10498)
* fix(meta-srv): retry only unready regions and recheck routes in region migration

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

* fix(meta-srv): check the whole batch before aborting a recovered migration

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

* test(meta-srv): cover the invalidation of a retried route switch

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

* test(meta-srv): share the moved-leader fixture and cover replies with errors

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

* fix(meta-srv): recover migrations without parsing the persisted state

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

* fix(meta-srv): keep promoting a target that holds a follower replica

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

* fix(meta-srv): broadcast the routes a migration rollback clears

The rollback that clears the Downgrading marks of a batch now broadcasts
the table cache invalidation, so clients that cached the marked routes
refresh them. Also call the infallible broadcast directly at the start
check, bind the pending regions before borrowing them, and document why
the upgrade failure test repeats its attempt.

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

* fix(meta-srv): broadcast cleared marks when a later table of a rollback fails

The rollback broadcasts the table cache invalidation whenever it cleared
a Downgrading mark, also when a later table of the batch then fails: a
retry finds those marks gone and would broadcast nothing.

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-19 16:09:39 +00:00
dennis zhuang 27182bdd69 perf(query): fill TopK heaps early over filtered region scans (#10515)
* perf(query): let a TopK over a filtered scan publish its dynamic filter early

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

* perf(query): share the global TopK conditions and flush filters per batch

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

* test(query): pin unsplit filter output at batch size 1

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

* perf(query): balance rows when assigning ranges in time order

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

* perf(query): leave TopK on other sort keys unchanged

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

* perf(query): spread ranges of unknown size and test the scan wiring

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

* test(query): share TopK test helpers and merge assignment cases

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

* fix(query): leave fetch-limited filters alone under a TopK

A FilterExec with a fetch keeps the first rows that pass, so changing
when the TopK threshold arrives or the order ranges are read changes
which rows it keeps. Both rules now stop at such a filter.

Also use replace_children instead of the deprecated with_new_children,
and document the coalescer behavior that batch size 1 relies on.

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

* fix(query): rewrite only TopKs bounded by a SortPreservingMergeExec

A partitioned TopK keeps up to fetch rows per partition, which equals
the global result only because the merge above it takes the first rows
of all partitions. Match from that merge, through projections, and
require the TopK's fetch to cover the merge's, so a TopK whose
per-partition rows are part of the result is never rewritten.

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

* docs(query): state what the global TopK fetch cap does and does not bound

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

* perf(query): keep per-partition TopK heaps when no range can be skipped

With no more ranges than partitions each partition reads at most one
range, so the TopK threshold leaves no later range to skip and one heap
only adds a single consumer. filtered_scan_below_topk now requires more
ranges than partitions; both callers pass the partition count they plan
for.

The small sqlness tables in order_by and windowed_sort fall under the
guard, so a new windowed_sort case with six files covers the rewrite
end to end.

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

* test(perf): add a query regression case for time-index TopK over a selective filter

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

* test(sqlness): say what the one-heap windowed_sort case pins

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-19 15:55:49 +00:00
Weny Xu ce7153de26 fix(metasrv): reserve repartition region numbers before creating regions (#10524)
* fix(metasrv): reserve repartition region numbers before creating regions

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

* fix(metasrv): limit repartition changes to region number reservation

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

* refactor: share repartition allocation targets

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

* fix: reserve region numbers when resuming repartition after upgrade

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

* test: bound waits for repartition create requests

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-19 15:42:30 +00:00
Weny Xu 66719b648f feat(meta): add shared batch lookups for table metadata caches (#10527)
* feat(meta): add shared batch lookups for table metadata caches

Signed-off-by: WenyXu <wenymedia@gmail.com>
(cherry picked from commit 3422005e77)
Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(meta): coalesce overlapping metadata batch loads

Queue a key for batch loading only when Moka polls its initializer. Drive the request-local queue alongside the reads so another batch can share an active load or take it over after cancellation.

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

* refactor(cache): extract request-local batching from paged reads

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

* refactor(meta): reuse common-cache batching for metadata reads

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

* fix(catalog): skip cache lookup for fully resolved batches

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

* test(cache): cover request-local batch delivery and cancellation

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

* test(meta): cover batch lookup fallback and clarify miss semantics

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

* fix: coordinate metadata cache publication with invalidation

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-19 14:37:32 +00:00