Commit Graph
6713 Commits
Author SHA1 Message Date
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
fys 3016f33d26 fix(deps): upgrade url to 2.5.9 (#10596)
fix(deps): upgrade url to 2.5.9 for RUSTSEC-2026-0592

Signed-off-by: fys <fengys1996@gmail.com>
2026-11-24 04:02:20 +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
Jingbo ChaiandClaude Opus 5.5 cf48c7587e docs: correct when Rust CI runs the Windows compilation check (#10458)
.github/heavy-ci.md said that Rust CI keeps the Windows compilation
check on PRs and merge groups. Since #10043, the check-windows job in
rust.yml only runs on the weekday schedule or a manual dispatch, so
PRs and merge groups skip it.

Signed-off-by: shuxiachai <shuxiachai@163.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 20:20:34 +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>
v1.4.0-nightly-20261123
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
jeremyhi 0ae7c1826b feat: add an admin function to discard pending WAL tails (#10477)
* feat: add an admin function that discards a datanode's pending WAL tails

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

* fix: refuse a tail discard over an unconfirmed manifest update and address review

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

* test: drop the integration test that repeats the admin function's region form

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

* fix: refuse a tail discard while a tail replay's update is uncertain

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

* build: pin greptime-proto to the branch that adds the pending tails truncate kind

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

* test: record the region id case of the discard_pending_tails sqlness test

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

* fix: track the uncertain replay update only without conditional publication and pin the truncate wire format

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

* test: simplify the truncate wire test

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

* test: cover the discard requests sent to regions and the metric data region

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

* test(mito2): pin the WAL history a discard relies on after a crash

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

* test(common-function): describe the mock pending tails discard

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

* fix(operator): report discard failures per region and clarify pending tails docs

Log each failed region of a by-table pending tails discard with its region id
and the tails the other regions discarded, derive the unsupported message from
the truncate kind, drop the unused feature parameter, document that a discard
raises the flushed entry id to the tail bound, and test discarding a kept tail
after a replay commit with an uncertain result.

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

* fix(operator): warn with the partial discard count and state the WAL history check precisely

Format request.rs, log the tails discarded by the regions that succeeded at
warn level when another region fails, state in the docs that an open checks WAL
history through the flushed entry id where the log store checks history and
that whoever adds a tail ensures it for every node that may lead the region,
and rename two tests after the outcomes they assert.

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

* docs(mito2): note that accepting missing WAL history opens a region past a discarded bound

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

* docs(mito2): rewrap the pending tails discard handler doc

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

* refactor(store-api): discard pending WAL tails with a dedicated region request

Carry the discard as RegionRequest::DiscardPendingTails, decoded from the
DiscardPendingTailsRequest body, instead of a truncate kind. Mito handles it as
a worker control request, so the truncate path no longer special-cases it;
the Metric Engine forwards it to a physical region's data region; the
frontend builds it for a region or for every region of a table, sharing the
table lookup with the discard of unflushed data. The wire fixture now pins the
new request body.

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

* refactor(metric-engine): give the pending tails discard its own error context

Report a failed discard as a pending tails discard rather than a truncate in
the Metric Engine, pin that Mito handles the discard as a worker control
request, state that physical_region_ids returns a logical table's physical
regions, and drop leftovers from the truncate kind in the tests.

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

* build: pin greptime-proto to the dedicated pending tails discard request

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

* build: pin greptime-proto to the merged pending tails discard request

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-19 10:50:58 +00:00
dennis zhuang fcdae107e1 fix(auth): enforce COPY export read and database table permissions (#10375)
* fix(frontend): authorize expanded COPY DATABASE table targets

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

* test(frontend): cover authorized database copy paths

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

* fix(frontend): require read permission for COPY TO

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

* fix(auth): register the COPY TO permission action

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

* test(frontend): group database copy authorization coverage

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

* test(frontend): assert COPY read action targets

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

* fix(frontend): unify expanded COPY export authorization

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

* fix(frontend): defer database COPY target checks

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

* fix(frontend): avoid empty database COPY authorization

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

* test(frontend): check export authorization error status

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

* test(frontend): check database COPY prerequisite assertions

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

* test(frontend): use the registered COPY fixture name

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

* test(frontend): align physical COPY fixture registration

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-19 07:52:10 +00:00
Weny Xu 788df5849b fix(metric): route logical table writes by internal table id (#10366)
* fix(metric): pass logical table identity to partition evaluation

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

* test(metric): cover table-id repartition routing across storage formats

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

* fix(partition): validate logical routing inputs

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

* fix(metric): retain table ids for physical batch routing

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

* refactor(partition): simplify table-id routing paths

Separate context dispatch, routing input construction and column conversion
into private methods while preserving the scalar payload path. Reuse the
existing table-id constant and shared IPC decoding in tests.

Keep correctly routed requests intact when their partition version is
unchanged. Update existing retry coverage to use stale versions for rerouting
and verify unchanged bulk requests preserve alignment and ownership.

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

* fix(servers): validate table-id column row count

Report mismatched logical table identities before Arrow column construction, document batch and row ordering requirements, and remove the unreachable batch skip. Extend the existing conversion test and clarify the partition evaluation context contract.

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-19 07:07:17 +00:00
Yingwen c7baa4115d feat(mito): track authoritative Narthex metadata and artifact lifetimes (#10507)
* feat(mito): model authoritative Narthex artifact inventories

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

* feat(mito): track authoritative series indexes through manifest replay and SST versions

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

* feat(mito): reclaim Narthex artifacts through file references and GC

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

* refactor(mito): append format to FileMeta

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

* refactor(mito): store canonical Narthex part sizes inline

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

* refactor(mito): put format last in SST metadata constructors

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

* refactor(mito): centralize region edit file change detection

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

* refactor(mito): represent Narthex parts as metadata records

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

* refactor(mito): defer Narthex coverage validation at publication

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

* refactor(mito): decouple series index removal from sample edits

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

* fix(mito): support Narthex region edits and simplify cleanup

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

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
2026-11-19 06:37:29 +00:00
Weny Xu d21322e222 fix: chunk RDS batch operations within parameter limits (#10489)
* fix: chunk RDS batch operations within parameter limits

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

* fix: deduplicate MySQL batch reads and use a regular CI database

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

* fix: preserve consistency across RDS batch reads

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

* refactor: use sqlx begin_with for MySQL transactions

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

* fix: use read-only snapshots for RDS batch reads

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

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
2026-11-19 01:54:37 +00:00
916acb1267 fix(operator): apply metric ingest TTL hints to physical tables (#9057)
* fix(operator): apply metric ingest TTL to physical tables

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* fix(operator): preserve instant TTL on logical tables and add remote write TTL hint integration test

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* fix(operator): preserve instant TTL on logical tables and add remote write TTL hint integration test

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* test(sqlness): regenerate logical table TTL expectation

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* refactor(operator): centralize metric logical table TTL checks

Share retention-vs-instant TTL helpers between DDL validation, auto-create
option filling, and ingest rejection messages so batch and SQL paths stay aligned.

Signed-off-by: Tyagiquamar <Tyagiquamar@users.noreply.github.com>

* fix(operator): borrow physical table name for TTL hint error

Signed-off-by: Tyagiquamar <Tyagiquamar@users.noreply.github.com>

* test(sqlness): expect InvalidArguments for logical retention TTL

Align table_semantics with alter_table retention rejection and rustfmt
the TTL hint error helper call.

Signed-off-by: Tyagiquamar <Tyagiquamar@users.noreply.github.com>

* feat(operator): apply retention ttl hint only on physical table creation and ignore on subsequent writes

Signed-off-by: Mohd Quamar Tyagi <104281681+Tyagiquamar@users.noreply.github.com>

* fix(operator): legacy logical TTL on create and restore ddl.rs LF

Strip retention ttl from metric logical CREATE options with a warning so
import_v2 can replay older snapshots. Narrow alter TTL checks, reduce
helper visibility, and convert ddl.rs back to LF line endings.

Co-authored-by: Cursor <cursoragent@cursor.com>
Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* fix(cli): clippy in import_v2 legacy ttl test

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* docs(operator): clarify logical metric ttl alter handling

Co-authored-by: Cursor <cursoragent@cursor.com>
Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* test(sqlness): add server-side coverage for legacy logical-table TTL

Replace the mock import_v2 unit test with sqlness cases verifying:
- SHOW CREATE TABLE omits database retention TTL on logical tables.
- Legacy logical CREATE TABLE with retention TTL strips the retention option from create_options.
- Explicit instant TTL remains preserved on logical tables.

Group TTL_KEY import in ddl.rs and verify create_options in HTTP test.

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* refactor(operator): strip logical retention ttl in one place

Every logical-table create path ends in StatementExecutor::create_logical_tables,
so strip retention ttl there instead of in fill_table_options_for_create and
validate_logical_create. validate_logical_create no longer mutates its input.

Classify ttl by parsing it once: only a valid non-instant ttl counts as
retention. Invalid values now fail normal option validation instead of being
silently stripped on create or reported as retention on ALTER.

Drop unit tests covered by the sqlness and HTTP integration cases.

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

---------

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>
Signed-off-by: Tyagiquamar <Tyagiquamar@users.noreply.github.com>
Signed-off-by: Mohd Quamar Tyagi <104281681+Tyagiquamar@users.noreply.github.com>
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
Co-authored-by: Tyagiquamar <Tyagiquamar@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Dennis Zhuang <killme2008@gmail.com>
2026-11-18 23:46:22 +00:00
Floris Smit 9543ef06d7 perf(table): prune by time range for filters on date_bin of the time index (#10345)
* perf: prune by time range for filters on date_bin of the time index

A filter on a view's date_bin(...) bucket column reaches the region scan
as date_bin(stride, ts) <op> literal. The time range extractor only
understood ts <op> literal, so such scans read every file.

date_bin floors to the bucket start, so date_bin(ts) <= ts <
date_bin(ts) + stride for any fixed-width stride and origin. Derive a
conservative time range from that for >, >=, <, <=, = and BETWEEN.

Signed-off-by: Floris Smit <florissmit10@gmail.com>

* fix(table): keep rows that date_bin truncates on coarse time indexes

DataFusion computes the date_bin bucket start in nanoseconds and truncates
it to the column unit, so on a TIMESTAMP(0|3|6) column the returned bucket
can be up to one unit below the true start. Widen the derived upper bound
by one unit on such columns.

Keep date_bin filters unsupported in extract_time_range_strict: a range
derived from them is up to a bucket wider than the filter, so timestamps
synthesized at its bounds may not satisfy it.

Signed-off-by: Floris Smit <florissmit10@gmail.com>

---------

Signed-off-by: Floris Smit <florissmit10@gmail.com>
2026-11-18 18:07:10 +00:00
Ning Sun 9cf76e20ad feat(postgres): support COPY targets for OTLP logs and traces (#10449)
* feat(postgres): support COPY targets for OTLP logs and traces

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

* fix(postgres): guard OTLP COPY targets with catalog restriction and denial observability

Address review findings on the OTLP COPY target feature:

- Enforce the `disallow_cross_catalog_query` restriction for qualified
  OTLP COPY targets through the new `CopyInHandler::copy_in_validate_scope`,
  mirroring SQL INSERT and the csv format; it runs against the original
  session context before any data is transferred and before the
  user-provider scope check.
- Meter and log `authorize_database` denials like startup authorization
  (`METRIC_AUTH_FAILURE` plus a scoped warn/error log).
- Add an end-to-end denial test through COPY with a scoped user provider:
  cross-schema, cross-catalog, and `table_name`-override targets are
  rejected before ingestion, the OTLP handler is never reached, and the
  session scope stays usable afterwards.
- Check the server's OTLP wiring before target errors, reword the metrics
  target rejection (no false 'with signal metrics' claim for the default
  signal), and avoid the second `OtlpOptions` clone in `new_otlp`.

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

* fix(postgres): surface OTLP COPY target denials as insufficient privilege

Address review feedback: wrap the authorize_database failure with
convert_err instead of PgWireError::ApiError, so a denied qualified COPY
target returns SQLSTATE 42501 (insufficient privilege) rather than XX000
(internal error). The end-to-end authorization test now expects
INSUFFICIENT_PRIVILEGE.

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

---------

Signed-off-by: Ning Sun <sunning@greptime.com>
2026-11-18 16:40:34 +00:00
zhaiAohan 47f6805189 feat: infer remote table schema for relational external tables (#10200)
* feat: infer remote table schema for relational external tables

Signed-off-by: tian1220A <1573612521@qq.com>

* fix: factor complex tuple into type alias to silence clippy

The 6-tuple returned by INFORMATION_SCHEMA.COLUMNS triggers
clippy::type_complexity under -D warnings. Alias it as RawColumnRow so
the driver's FromRow impl for tuples is preserved.

Signed-off-by: tian1220A <1573612521@qq.com>

* refactor: map only selected columns in declared relational external tables

Separate raw remote column metadata fetching from type mapping. The declared form maps only the columns the user lists, while the inferred form maps every remote column.

Signed-off-by: tian1220A <1573612521@qq.com>

* fix: skip DNS resolution for unix-socket MySQL connections

fetch_mysql_columns unconditionally resolved the host via DNS and forced
resolved_ips, which is TCP-only. When the connection DSN carries an explicit
Unix socket (?socket=/path), mysql_async dials the socket path directly, so the
host is a placeholder and an unresolvable hostname should not block the DDL.
Parse the opts first and skip resolution when a socket is configured.

Signed-off-by: tian1220A <1573612521@qq.com>

* fix: use is_none_or to silence clippy::unnecessary_map_or

Signed-off-by: tian1220A <1573612521@qq.com>

* fix: redact relational connection DSNs in debug logs, parser errors and SHOW CREATE TABLE
Signed-off-by: tian1220A <1573612521@qq.com>

* fix: redact sqlparser debug logs leaking connection DSNs

sqlparser logs raw SQL at debug level, which carries the connection DSN
and its password. Wrap the fmt layer with a RedactingFormatter that
redacts DSNs in events whose real target is sqlparser. tracing_log
hard-codes the event target to log, so recover the real target via
NormalizeEvent::normalized_metadata.

Move redact_connection_in_text from table down to common-telemetry so the
logging layer can reuse it; table re-exports it for existing callers.

Signed-off-by: tian1220A <1573612521@qq.com>

* fix: use explicit clone to silence clippy::implicit_clone

Signed-off-by: tian1220A <1573612521@qq.com>

* fix: address review feedback on relational external tables

Reject MySQL TIME, accept a synthetic greptime_timestamp, unify credential redaction via REDACTED_OPTION_VALUE, and add unit tests.

Signed-off-by: tian1220A <1573612521@qq.com>

* fix(telemetry): redact DSN passwords correctly with the url crate

The hand-rolled scanner split username/password at the last colon and treated comma/semicolon/parens as DSN terminators, leaking passwords containing them (e.g. mysql://user:abc:def@host left abc visible). Extract the DSN span and parse it with the url crate, which splits userinfo at the first colon and host at the last @, then rewrite it with the password replaced.

Signed-off-by: tian1220A <1573612521@qq.com>

* refactor: drop generic DSN redaction, keep structured credential redaction

Address review feedback: check table existence before remote schema inference for IF NOT EXISTS; return Option from redact_option_value to avoid redundant allocation.

Signed-off-by: tian1220A <1573612521@qq.com>

---------

Signed-off-by: tian1220A <1573612521@qq.com>
2026-11-18 13:41:19 +00:00
jeremyhi c58e143a08 fix(meta-srv): treat a missing region in the downgrade reply as a failure (#10485)
* fix(meta-srv): treat a missing region in the downgrade reply as a failure

A closing region is no longer found on the datanode while its in-flight
manifest updates may still be written, so a reply saying the region does
not exist does not prove that the leader has stopped. Handle it as a
retryable downgrade failure: retry, then wait until the leader region
lease deadline before upgrading the candidate.

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

* test(meta-srv): reuse send_mock_reply in the missing region test

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

* fix(meta-srv): handle every downgrade reply of a batch

A failed region no longer ends the handling of a batch reply early, so
the last entry ids of the other regions are still recorded.

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

* fix(meta-srv): log each missing region and test the first failure of a batch

Log a missing region where its reply is handled, so that it is reported
even when an earlier reply of the batch already failed. Test that a
batch returns its first failure in reply order, and list the retry
causes of the downgrade by the retry hint of the reply.

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

* docs(meta-srv): qualify the missing region retry cause

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

* refactor(meta-srv): state the first failure policy of a downgrade batch

Drop the warn log of a missing region, since the retry and failure logs
already print the reason, and reword the retry doc of a missing region.

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
2026-11-18 10:56:58 +00:00