refactor(meta): separate migration construction and drain child tracking (#10098)
refactor(meta): separate migration construction and own drain child tracking
(cherry picked from commit 6a731a444f)
Signed-off-by: WenyXu <wenymedia@gmail.com>
Add a loader registration hook to TriggerDdlManager and invoke it
before procedure recovery. Test that registration reaches the
configured trigger DDL manager.
Signed-off-by: fys <fengys1996@gmail.com>
* feat: share streaming range results across scans
Share post-merge range batches across concurrent readers while preserving stream boundaries, cancellation and retry behavior. Encapsulate range ownership, compaction and publication in RangeResultCache, backed by the common SyncCache primitive.
Retain SST retirement fencing and memory accounting. Track live shared-buffer bytes and worker events alongside existing cache metrics.
Signed-off-by: WenyXu <wenymedia@gmail.com>
* fix(mito2): clean up shared range registrations on release
Signed-off-by: WenyXu <wenymedia@gmail.com>
---------
Signed-off-by: WenyXu <wenymedia@gmail.com>
DensePrimaryKeyCodec::decode_leftmost decoded the whole key and popped
the last value, so codecs with more than one field returned the
rightmost primary key column. Decode only the first field instead,
which also removes the full-key decoding noted in the TODO.
Current callers build single-field codecs and are unaffected.
Fixes#10089
Signed-off-by: Aumnertic <hznuzc@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
feat(postgres): OTLP binary payload ingest via COPY FROM STDIN
COPY FROM STDIN WITH (FORMAT otlp [, signal '...'] [, <options>]) ingests
one binary OTLP protobuf message over the postgres wire protocol — the
first binary COPY format (wire format code 1) — for all three signals:
- signal 'metrics' (default): ExportMetricsServiceRequest, completed
through OpenTelemetryProtocolHandler::metrics with the same context
preparation as the HTTP route (OtlpMetricCtx from the options); rows
are accepted data points.
- signal 'traces': ExportTraceServiceRequest through ::traces, with the
trace table name and pipeline name/version/params from the options
(an explicit pipeline name is required, exactly like the HTTP traces
endpoint); rows are accepted spans.
- signal 'logs': ExportLogsServiceRequest through ::logs, with the log
table name, pipeline options and extract keys from the options, and
the same OtlpLogDirect default as the HTTP route; rows are affected
rows.
The WITH options carry what the HTTP endpoints take as request headers,
reusing the HTTP path's own parsing helpers (truthy, SelectInfo,
GreptimePipelineParams, PipelineWay) so the two routes cannot drift;
values already provided by the postgres session (database, user,
permissions) are not repeated. Option semantics match the headers:
promote_all_resource_attrs / resource_attrs (';'-separated include or
exclude list) / promote_scope_attrs / translation_strategy for metrics;
table_name / pipeline_name / pipeline_version / pipeline_params /
extract_keys for traces and logs. Signal-inapplicable options are
rejected.
Like the influxdb format: table-less (a named table is rejected), the
whole payload is buffered until CopyDone exactly like one OTLP/HTTP
request body and bounded by the shared 64 MiB request limit, decoding
uses the same protobuf types, and the server must be wired —
PostgresServer::with_otlp_handler(handler, with_metric_engine) carries
the same metric-engine flag the HTTP wiring passes from its options.
The pipeline handler is derived from the protocol handler via trait
upcasting, as the HTTP routes do.
e2e: chunked binary metrics ingest; traces with table_name and
pipeline_name options; logs on the default table; metrics
promote_all_resource_attrs making a resource attribute queryable;
invalid-payload failure with connection reuse.
Signed-off-by: Ning Sun <sunning@greptime.com>
* fix(promql): collapse duplicate samples at one timestamp before range functions
A read path that does not deduplicate, such as an append-mode region, can
hand PromQL two rows for one series at one timestamp. Every range function
reads its samples from RangeManipulate, so the duplicate entries were
treated as independent samples: count_over_time counted both, idelta and
irate returned NULL because the last two entries shared a timestamp, and
delta/increase/rate deflated because the average sampling interval divides
the observed span by sample_count - 1.
Prometheus sample identity is one sample per series per timestamp, so its
range functions can never see this input. Restore that identity once, at
the operator every range function shares, instead of special-casing each
function's arithmetic.
The collapse compares native ticks, never the millisecond payload, so
distinct sub-millisecond samples that share a millisecond stay distinct as
calculate_range documents and tests. Batches without duplicate timestamps
take a single adjacency scan and are returned untouched; only when
duplicates exist is a take built, keeping tag and value columns aligned.
Keeping the last row of a group matches MergeMode::LastRow.
The normalize test that fed three rows at one timestamp now uses distinct
timestamps: it exercises histogram start-timestamp offsetting, and its
repeated timestamp was incidental, not asserted behavior.
Signed-off-by: discord9 <discord9@163.com>
* test(promql): cover duplicate samples end to end and keep the newer value
The operator now keeps the first row of a tied timestamp group, which is the row a
deduplicating read keeps: storage orders equal primary key and timestamp by sequence
descending, and FlatDedupReader takes the first row of each group. The end-to-end case
pins that choice by writing 100 and then 101 at the same timestamp: the window reports
increase 6, while keeping the stale 100 would report 8.
The sqlness case writes duplicate rows into an append_mode region, which is the read
path that does not deduplicate, and asserts every range function plus the unaffected
ordinary table in both the standalone and distributed environments.
Signed-off-by: discord9 <discord9@163.com>
* docs(promql): qualify duplicate-timestamp conflict selection
Signed-off-by: discord9 <discord9@163.com>
* perf(promql): avoid copying tags when collapsing duplicate samples
Signed-off-by: discord9 <discord9@163.com>
---------
Signed-off-by: discord9 <discord9@163.com>
* fix(datanode): pick a node epoch above the recorded one
The metasrv fences a datanode whose node epoch is lower than the
highest one it has recorded for the node id. A datanode used its start
time as its epoch, so after a restart on a host whose clock is behind
the previous process's, or after the clock stepped back, the new
process picked a lower epoch and was fenced for good: no region lease,
no keep-alive.
Before it creates the heartbeat task, the datanode now reads the
recorded epoch through its metadata backend and uses one more than it
if its start time is not higher. The node info still reports the local
start time. A failed read fails the startup, like the other metadata
reads.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test(datanode): tighten the node epoch tests
Use a lower record that leaves room below the start time, so the test
fails if the start time is ignored, and a nonzero node id, so it fails
if the node id is ignored. Clarify the doc comment of the epoch choice.
This assumes the previous process of a node id has stopped before a new
one starts.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
---------
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* feat: add relational region engine skeleton and registration
Add a read-only relational RegionEngine (create/open/drop lifecycle) and register it as the 4th engine in build_store_engines alongside mito/metric/file. Add a datanode-level test asserting all 4 engines are registered.
Signed-off-by: tian1220A <1573612521@qq.com>
* feat: add relational connection and idempotent region lifecycle
Move ConnectionInfo into relational-engine (DSN parsing + redacted rendering), place the RelationalOptions/RELATIONAL_META_KEY serialization contract in table::requests, make CREATE idempotent by comparing the persisted manifest definition against the incoming request (RegionExists on mismatch), and drop the empty EngineConfig placeholder.
Signed-off-by: tian1220A <1573612521@qq.com>
* refactor: address review comments on relational region engine
- remove connection.rs (only used by its own tests); it will be
reintroduced when connection handling is wired up
- drop RelationalOptions::version (not validated or used to select a
deserialization format)
- validate an idempotent create against the existing region definition
(region id / schema / primary key / options) and return Unexpected on
mismatch, with a reason field on RegionExists
- use serde.workspace and remove the empty [features] section
- cargo fmt
Signed-off-by: tian1220A <1573612521@qq.com>
* fix: adapt relational engine to latest main
- implement RegionEngine::set_region_role_with_lease (no-op lease, the
engine takes no writes so no lease is needed)
- pass node_id to build_object_store_manager in the registration test
- drop stale url dependency from the relational-engine lock entry
Signed-off-by: tian1220A <1573612521@qq.com>
* ci: register relational-engine in scope rules
Signed-off-by: tian1220A <1573612521@qq.com>
* fix: remove table self-dependency from Cargo.lock
Signed-off-by: tian1220A <1573612521@qq.com>
---------
Signed-off-by: tian1220A <1573612521@qq.com>
* perf(mito2): merge compaction inputs on a separate task
Compaction read, merged and encoded each output on a single task, so
parquet encoding waited for the merge and the merge waited for
encoding. The merge now runs on its own compaction runtime task and
hands merged batches to the SST writer through a bounded channel.
The channel also closes when that task panics, so the reading side
awaits the task before reporting the end of the input. A panic fails
the compaction instead of producing a truncated SST.
One output of 4.8M rows took 1.28s instead of 1.65s.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* perf(mito2): parallelize decoding and encoding of compaction outputs
Parquet encoding took about two thirds of a compaction output's time
and ran on a single thread. When `experimental_compaction_output_parallelism`
is above 1, the SST writer encodes the columns of each row group on up
to that many blocking threads of the compaction runtime while the next
row group is buffered, and the merge decodes up to that many input
files ahead of it on compaction runtime tasks.
The parallel writer feeds every column writer the same input as
`ArrowWriter`, so the SSTs are byte-identical. The bytes of a row group
reach the object store writer one row group later, so `max_file_size`
may split a file one row group later.
The option defaults to 1, which keeps today's CPU usage. One output of
4.8M rows took 0.44s with 4 and 0.38s with 8, against 1.28s with 1.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito2): cancel compaction producers before consumer polling
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat(mito2): support per-table compaction output parallelism
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito2): drain encoding tasks before returning failures
Abort remaining queued encoding tasks and await running tasks before propagating the first error, keeping row-group work inside the caller's compaction memory budget lifetime.
Add deterministic error and panic tests for queued cancellation, running-task cleanup, budget retention, and original error preservation.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito2): drain encoders on SST write errors
Add asynchronous abort cleanup to both SST write entry points so source errors cannot detach in-flight encoding work after its compaction memory budget is released. Share encoder task cleanup with the encoding-failure path and preserve the original write error.
Cover source-read failures in flat and primary-key writers with deterministic running and queued tasks.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito2): drain compaction outputs on cancellation
Stop scheduling new output batches on cancellation instead of aborting active writers. Await started outputs and retain successful SSTs, draining sibling tasks before propagating join failures.
Add deterministic cancellation regressions covering blocking encoder lifetime, budget retention, output ownership, join failures, and cancellation before work starts.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
---------
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(log-store): accept a retried first create of the conditional create probe
The startup probe of the object store WAL wrote its first create by hand
and failed on any error. When that create is stored but its response is
lost, the retry layer repeats it, the repeat meets the object, and the
probe reported a failed write, so the WAL refused to open.
Move the create of put_if_absent, which reads the object back and accepts
identical content, into a path-based core and use it for the probe's
first create too. The second create, which the store must refuse, is
unchanged.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test(log-store): reuse LosingWriter for the retried probe create test
Move LosingWriter from the fault matrix into the test module and use it,
armed with the lose_next pattern, in place of RetriedWriter. Say why the
probe's second create bypasses put_path_if_absent: a read-back would find
the first create's object and let an overwriting store pass.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
---------
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix: ignore stale leader grants after a region is downgraded
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix: compare stale leader grants with the longest lease seen
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix: treat a lease too long to store as unknown
A lease longer than a u64 of nanoseconds saturated to a shorter one, so the
derived send time could be later than the real one. Now such a lease makes
the send time unknown, which counts as earlier than any gate.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix: address review comments on stale leader grants
Scope the early send time claim to after a lease has been seen, drop the
unused role parameter of demote, clarify a test comment and check that a
fresh grant still makes a reopened region writable.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor: compare stale leader grants with the heartbeat send time
Pass the send time of the heartbeat behind a lease to set_region_role_with_lease,
and return whether the role was applied. Mito compares the send time with the
grant gate directly, so it no longer derives it from the longest lease seen.
The datanode finalizes leadership only when the grant was applied.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test: cover stale grants through the datanode and repeated downgrades
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor: keep leader grant rules in one region method
Apply a role grant in MitoRegion::apply_role_grant, which renews the lease
and decides whether the role changes; the engine only looks up the region.
Rename the gate to downgrade_started_at and demote to begin_downgrade, keep
the field private, and copy it on reopen through
inherit_downgrade_state_from.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor: drop a needless borrow
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor: keep lease concepts in the engine and role ordering in the region
ManifestContext, which owns the role, records when the role was last
demoted and promotes a region only for a promotion issued after that. The
time starts when the context is created, so a reopened region ignores
grants for heartbeats sent before the reopen, without copying state. The
engine translates leases: it renews the deadline and promotes with the
heartbeat send time. MitoRegion keeps no grant state.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix: keep the data region of a metric region off a grant its metadata region ignores
The metric engine applies a grant to the metadata region first and stops
if it is ignored, so the data region, whose role the engine reports, never
becomes a leader that skips finalization. Also describe what promoting
returns.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* docs: describe when a lease grant is ignored and flatten the finalize check
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor: move lease types out of the region and the Leader deadline into ManifestContext
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor: name the promotion fence after the downgrade it records
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
---------
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix(meta): register failure detectors for regions switched before a rollback
A region migration switches the routes of its tables one table at a
time. If it aborts after some tables were switched, those regions are
already served by the target, but the rollback deregistered the
target's failure detectors for every region and registered only the
source's. The target's next heartbeat registers them again, so if the
target stopped before sending one, nothing detected its failure and
the switched regions stayed unavailable until the metasrv leader
changed or the target came back.
The rollback now collects, from the routes it already reads, the
regions whose leader is the target and resets the target's failure
detectors for them at the end. It also skips a table whose route no
longer exists, so a table dropped meanwhile no longer fails the
rollback before the detectors are handled.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test(meta): roll back a downgrading leader in the rollback detector test
The table that was not switched yet keeps a downgrading leader in a real
abort, so the test now builds it that way and checks that the rollback
clears it.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix(meta): monitor regions switched before a rollback only on the target
The rollback registered the source's failure detectors for every region
of the migration, including the regions already switched to the target.
Those regions are served by the target after the rollback, so their
source detectors watched the wrong peer: when one fired, the failover
found the leader had changed and only removed it. The rollback now
registers the source's detectors only for the regions that were not
switched, and keeps resetting the target's detectors for the others.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor(meta): rename reset_failure_detectors_for_candidate_regions to reset_failure_detectors
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
---------
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* feat(postgres): influxdb line protocol ingest via COPY FROM STDIN
COPY FROM STDIN WITH (FORMAT influxdb [, precision 'ns']) ingests
InfluxDB line protocol over the postgres wire protocol, reusing the
HTTP ingestion pipeline wholesale for correctness and performance
parity: the whole payload is buffered and completed once at CopyDone
through the frontend's InfluxdbLineProtocolHandler::exec — conversion,
permissions, line-protocol interceptors, timestamp alignment to table
time-index units, merge mode and inserts are the same path an HTTP
write of the same bytes takes, under the connection's regular postgres
query context.
Formats are an explicit, closed enum (CopyFormat::Csv |
CopyFormat::Influxdb(options)); each variant states its own rules in
the copy lifecycle's match arms — csv requires a target table and
parses incrementally, influxdb forbids one (each line names its own
measurement) and buffers one bounded request body. The COPY layer owns
only the buffering: record boundaries, including newlines inside quoted
field values and after escapes, belong to the line-protocol parser
alone — one COPY statement is one bounded ingestion request (64 MiB;
larger imports are multiple COPY statements).
- Wiring: PostgresServer::with_influxdb_handler attaches the shared
line-protocol handler; unwired servers reject the format when a copy
starts.
- Grammar: COPY FROM STDIN without a table is scanned (an unquoted
FROM cannot be a table name); table-bound formats reject it with
guidance, influxdb rejects a named table.
- Options: precision accepts the HTTP endpoint's values via the shared
parse_time_precision (moved to servers::influxdb), defaulting to
nanoseconds.
Review findings (fengjiachun) are fixed at the root by removing the
pre-splitter rather than repairing it: the retired naive line splitter
broke quoted multiline records at chunk/flush boundaries (found by
removing record splitting entirely), drained the buffer quadratically
(found by append-only buffering), and capped nothing (found by an
explicit payload limit).
e2e: multi-measurement ingest with chunked feeds; a 32,768-physical-line
flush-threshold regression with a multiline quoted record split across
CopyData chunks; precision 'ms' epoch verification; invalid UTF-8 and
trailing-record-without-newline handling; payload limit; table-named
rejection; malformed-line abort with connection recovery.
Signed-off-by: Ning Sun <sunning@greptime.com>
* chore: typo
---------
Signed-off-by: Ning Sun <sunning@greptime.com>
Select Discard or Detach when submitting children via Status::Suspended.
Persist the policy from the child's first normal or rollback checkpoint.
Recover detached children as independent roots with their original id and
context, using existing execution and cleanup without rebuilding the graph.
Keep fresh root admission serialized while allowing accepted procedures to
recover above the submission limit. Cover first persistence, repeated
recovery, rollback, cleanup, defaults, and concurrent admission.
Signed-off-by: WenyXu <wenymedia@gmail.com>
* feat: Add last_sequence for max allocated sequence and add tests for the reproduced issue cases
Signed-off-by: hahaha <a310608318@gmail.com>
* test: Add a regression test for Kafka remote catchup
Signed-off-by: hahaha <a310608318@gmail.com>
---------
Signed-off-by: hahaha <a310608318@gmail.com>
* fix(catalog): propagate frontend process-list failures
Return the existing invocation error when a selected frontend cannot list processes, so a successful response cannot omit that peer.
Signed-off-by: Byte-Naut <Byte-Naut@proton.me>
* test(frontend): cover remote process-list errors and aggregation
Exercise real metadata discovery and gRPC listeners for a missing management service and successful catalog-scoped aggregation.
Signed-off-by: Byte-Naut <Byte-Naut@proton.me>
---------
Signed-off-by: Byte-Naut <Byte-Naut@proton.me>
* fix(log-store): make raft-engine periodic WAL sync actually fsync
On raft-engine 0.4.2, Engine::sync() writes an empty LogBatch and
write() returns before fsync (tikv/raft-engine#395). The periodic
sync task therefore never durable-flushed acknowledged WAL data.
Work around by writing a minimal non-empty marker with sync=true so
the fsync path is reached until a crates.io release includes
tikv/raft-engine#400.
Fixes#9712
Signed-off-by: Yvan Wang <131545713+BootstrapperSBL@users.noreply.github.com>
* perf(log-store): reuse LogBatch across periodic WAL syncs
Keep the periodic sync task's LogBatch across ticks instead of
allocating a fresh one (4 KiB encode buffer plus item vec) every
period. A successful Engine::write drains the batch but retains its
buffers; after a failed write or a panicked blocking task the batch is
discarded and recreated on the next tick, since it may be left
partially encoded.
Keep the marker put rather than deleting an empty key: the put
overwrites a single key, whereas every delete would become a recovery
tombstone that raft-engine keeps in memory while replaying append
files.
Also document that the marker value must not decode as a NamespaceImpl
(the marker key lies inside the range scanned by list_namespaces), add
a test covering batch reuse and namespace listing, and apply rustfmt.
Refs #9712
Signed-off-by: Yvan Wang <131545713+BootstrapperSBL@users.noreply.github.com>
---------
Signed-off-by: Yvan Wang <131545713+BootstrapperSBL@users.noreply.github.com>
* fix(meta): exclude route followers from failover targets
Failover target selection did not exclude the region's route followers.
The selector could keep picking a follower, the submit rejected it as a
peer conflict, and the region never failed over.
Group the failed regions by their followers and exclude them per group.
A group without a candidate is skipped instead of failing every region of
the datanode.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test: check failover continues after a group without candidates
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix(meta): keep failover going when follower routes can't be read
Fall back to selecting without follower exclusion when the routes can't
be read, log skipped groups with their followers at warn level, and test
a region without a route.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor(meta): select failover targets per exclusion set in select_peers
generate_failover_tasks now only reads the route followers of the regions.
select_peers resolves the affinity and the unschedulable datanodes once,
then selects per group of regions that exclude the same datanodes.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor(meta): drop a comment that repeats the code
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor(meta): tighten failover target selection
Name the route followers after the parameter they fill, read the routes
with unwrap_or_else, and log a group without a candidate as an error, as
the caller did before.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix(meta): let the region-stat-aware selector balance the whole batch
The region-stat-aware selector now receives each region's excluded peers
along with the whole batch, so it can still balance load across the
regions while keeping a region off its own followers. A region without a
candidate is left out of its output instead of failing the others. The
selectors driven by SelectorOptions keep selecting per group of regions
that exclude the same datanodes.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test: name the batch type of the stat-aware recorder
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* refactor(meta): treat a selector without candidates the same in both arms
Both selector arms now place what they can and treat NoEnoughAvailableNode
as nothing placed; the stat-aware selector's contract says so. Rename its
parameter to exclude_peer_ids_by_region, check for unplaced regions in
linear time, and describe what the code does in the comments.
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* test: keep the stat-aware recorder's placements off excluded peers
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
---------
Signed-off-by: jeremyhi <fengjiachun@gmail.com>
* fix(mito2): invalidate retired SST range results and coalesce loads
Coordinate decoded range loads by their full scan key, bound shared work, and prevent late fills after SST retirement. Invalidate range results for local purge and object-store GC while preserving old snapshot reads.
Fixes#9934
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito): preserve SST lifetime across index replacement
Share retirement and final purge across immutable index metadata views. Keep version-specific GC references until readers release them and match Parquet liveness by file identity.
Fixes#9944
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): list-based SST purge and single FilePurger::remove_file
The final purge of a retired SST no longer depends on FileMeta: index
files of every version are discovered by listing
({region_dir}/index/{file_id}. prefix), so even when the last live view
is a stale one, the purge still removes all newer index files.
- SstLifetime is slimmed down to { deleted, file_purger }; the purge now
runs in the last FileHandleInner::drop (Arc::strong_count == 1, which
is race-free here since only inners of the same file hold the lifetime).
- FilePurger is merged back into a single remove_file(file_meta,
is_delete) method; is_delete means the file was retired AND this is the
last live view.
- LocalFilePurger deletes the SST and all its index files via the new
delete_file_and_all_indexes helper (list before delete, so a listing
failure leaves the file untouched).
- Remove the dead index_outdated flag and its accessors, which had no
callers in the entire repo.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito): elect final SST view release atomically
Track metadata views with an atomic counter instead of inspecting the lifetime Arc strong count. Concurrent destructors now elect exactly one final releaser while preserving the single remove_file interface.
Add a deterministic concurrent-drop regression covering retired and live files.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): restore Arc-owned SST cleanup and clarify reference release
Restore the lifetime design from 835227dcbc, using the final Arc drop and latest metadata instead of manual view counting and per-SST index listing.
Rename FilePurger::remove_file to release_file_ref while retaining purge_file for final cleanup. Preserve and adapt the concurrent view-release regression test.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): track SST references by file lifetime
Register one reference guard per logical SST lifetime and release it on final drop, including normal region close. Remove per-view release_file_ref and index_outdated handling.
Protect all index generations while their SST is referenced. Preserve the existing GC snapshot format by expanding the recorded index generation upper bound for older version-aware workers.
Update coverage for independent references, normal close, cross-region ownership, concurrent final cleanup and both GC listing modes.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): release SST references directly on lifetime drop
Remove the redundant FileReferenceGuard and let SstLifetime register and unregister its file reference directly. Preserve unconditional reference release on normal close and retirement-only purge.
Expose the reference manager through FilePurger and adapt reference manager tests without changing GC or snapshot behavior.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* test(mito): verify SST cleanup with real storage and isolate GC policy cases
Replace the recording-only concurrent purge test with filesystem assertions using LocalFilePurger and shared fixtures. Keep intermediate-view retention and retired versus live file cleanup coverage without claiming exhaustive thread interleavings.
Separate GC reference-policy cases from reader-release ordering and reuse their setup. Production code remains unchanged.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* style(mito): format SST lifetime changes
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito2): use crate-rooted range cache imports
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito2): account for range cache delivery lifetime
Keep completed range results charged while watch subscribers or replay streams retain them. Cache entries keep weak delivery references, allowing cache-only ownership to release the delivery reservation. Cache hits reuse or nonblockingly acquire the reservation, falling back when the budget is exhausted.
Resize input reservations to completed-result estimates and cover successive slow consumers, cache-only handoff, hit sharing, invalidation, admission rejection, and cancellation with regression tests.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
---------
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* test: cover windowed sort cast unit mismatch
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(query): stop windowed sort on unit- or timezone-changing time casts
A cast on the time index column keeps the windowed-sort optimization
eligible only when it preserves the underlying timestamp values. Casts
that change the time unit (e.g. ms -> s) or that add a timezone to a
naive timestamp re-interpret the values, so the working ranges derived
from the time index no longer describe the sort column and the scan
fails with a working-range error or silently wrong order. Reject both
cast shapes so such queries fall back to the normal SortExec path.
The integration fixture uses two rows 1000 seconds apart so the cast
output stays distinct and the ordering assertions are not vacuous; the
descending arm gets its own expectation.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* fix(query): stop windowed sort on unit-changing timestamp wrappers
to_timestamp_seconds/millis/... cast their argument to their own unit
inside the function, so the hidden cast bypassed the explicit-cast guard
and kept the windowed-sort optimization eligible on a sort column whose
values no longer match the working ranges. The wrapper branch now applies
the same unit- and value-preserving predicate as the cast branch, with
the predicate extracted into preserves_timestamp_values and shared by
both.
The integration regression gains to_timestamp_seconds ASC/DESC arms and
a to_timestamp_millis value-preserving control; unit tests cover
unit-changing, tz-adding, and non-timestamp wrapper inputs.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test: regen windowed sort sqlness after wrapper guard
The windowed_sort_nanos and windowed_sort_advance cases sort by
to_timestamp_nanos over a millisecond index and to_timestamp_millis over
a nanosecond index. Both wrappers change the time unit inside the
function, so the windowed-sort rule no longer applies and the plans
render a plain SortExec. Query results are unchanged; only the EXPLAIN
plan line differs. Regenerated by the sqlness runner.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* test(query): simplify windowed sort cast regressions
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
---------
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
* perf(mito2): build encoded bulk part indexes from in-memory bytes during flush
Sync flush uploaded encoded bulk parts without indexes and rebuilt them after
the flush, which read every encoded SST back from the object store and needed a
second manifest commit. Build the indexes from the encoded bytes still in memory
before the flush commits, the same way the regular SST writer does, and drop the
post-flush rebuild for these files.
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(mito2): keep flush going when indexing encoded bytes fails
Match ParquetWriter: a failure while building indexes from the encoded bytes
logs and leaves the SST unindexed instead of failing the flush after the SST
was uploaded.
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(mito2): own encoded SSTs for cleanup before uploading them
Index creation now runs after an encoded SST is uploaded, so a truncate or drop
could cancel the flush after the upload but before UncommittedSsts tracked the
file, leaving the SST and its index behind. Track the file before the upload,
and fill the index metadata on the caller's SstInfo instead of a partial one.
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* refactor(mito2): name encoded SST index build params explicitly
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(mito2): drop index metadata when the puffin file fails and size index decode batches
Indexer::do_finish kept the per-index metadata when finishing the puffin file
failed, so callers could publish indexes that were not written. Return an
empty output instead.
Indexing encoded bulk parts now decodes with the batch size estimated from the
largest row group, the same estimate bulk merges use, instead of a fixed 8192
rows.
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* docs(config): document the mito index build_mode option
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(mito2): decode encoded SSTs for indexing on the blocking pool
Indexing encoded bulk parts decoded Parquet batches inside the flush task on
the global async runtime. Decode each batch with spawn_blocking_global and keep
the indexer update on the async task, with one batch in flight.
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
---------
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(mito): preserve SST lifetime across index replacement
Share retirement and final purge across immutable index metadata views. Keep version-specific GC references until readers release them and match Parquet liveness by file identity.
Fixes#9944
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): list-based SST purge and single FilePurger::remove_file
The final purge of a retired SST no longer depends on FileMeta: index
files of every version are discovered by listing
({region_dir}/index/{file_id}. prefix), so even when the last live view
is a stale one, the purge still removes all newer index files.
- SstLifetime is slimmed down to { deleted, file_purger }; the purge now
runs in the last FileHandleInner::drop (Arc::strong_count == 1, which
is race-free here since only inners of the same file hold the lifetime).
- FilePurger is merged back into a single remove_file(file_meta,
is_delete) method; is_delete means the file was retired AND this is the
last live view.
- LocalFilePurger deletes the SST and all its index files via the new
delete_file_and_all_indexes helper (list before delete, so a listing
failure leaves the file untouched).
- Remove the dead index_outdated flag and its accessors, which had no
callers in the entire repo.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito): elect final SST view release atomically
Track metadata views with an atomic counter instead of inspecting the lifetime Arc strong count. Concurrent destructors now elect exactly one final releaser while preserving the single remove_file interface.
Add a deterministic concurrent-drop regression covering retired and live files.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): restore Arc-owned SST cleanup and clarify reference release
Restore the lifetime design from 835227dcbc, using the final Arc drop and latest metadata instead of manual view counting and per-SST index listing.
Rename FilePurger::remove_file to release_file_ref while retaining purge_file for final cleanup. Preserve and adapt the concurrent view-release regression test.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): track SST references by file lifetime
Register one reference guard per logical SST lifetime and release it on final drop, including normal region close. Remove per-view release_file_ref and index_outdated handling.
Protect all index generations while their SST is referenced. Preserve the existing GC snapshot format by expanding the recorded index generation upper bound for older version-aware workers.
Update coverage for independent references, normal close, cross-region ownership, concurrent final cleanup and both GC listing modes.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* refactor(mito): release SST references directly on lifetime drop
Remove the redundant FileReferenceGuard and let SstLifetime register and unregister its file reference directly. Preserve unconditional reference release on normal close and retirement-only purge.
Expose the reference manager through FilePurger and adapt reference manager tests without changing GC or snapshot behavior.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* test(mito): verify SST cleanup with real storage and isolate GC policy cases
Replace the recording-only concurrent purge test with filesystem assertions using LocalFilePurger and shared fixtures. Keep intermediate-view retention and retired versus live file cleanup coverage without claiming exhaustive thread interleavings.
Separate GC reference-policy cases from reader-release ordering and reuse their setup. Production code remains unchanged.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* style(mito): format SST lifetime changes
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* fix(mito): reclaim obsolete indexes by reader version
Track exact index-version references per metadata view and restore version-specific Puffin liveness in both GC paths. Keep file-level Parquet protection and shared SST lifetime cleanup, without expanding snapshots into unreferenced index generations.
Include old readers of imported files even when the source region is not open locally. Add real-storage GC coverage for reader release and lingering while retaining Parquet and the current index.
Validated workspace checks with default and all features, all-target all-feature Clippy with warnings denied, and all 1853 mito2 tests.
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
---------
Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
* feat(partition): support iceberg_hash in partition rules
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(partition): reject partition column type changes and quote rule identifiers
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(table): keep time index widening for partition columns
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* refactor(partition): replace PartitionFunction with IcebergHash
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* docs(partition): describe iceberg_hash in the function module
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(meta): validate iceberg_hash partition bounds on ALTER and trim comments
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* test: quote partition rule identifiers in SHOW CREATE TABLE expectations
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* test(partition): check hash rules in information_schema and repartition target columns
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(partition): coerce hash partition rules against the evaluation schema
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* fix(partition): keep quotes in partition column names when building filters
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
---------
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
* feat: Support procedure_state() using the last procedure ID
Signed-off-by: hahaha <a310608318@gmail.com>
* feat: Fix and add tests according to review comments
Signed-off-by: hahaha <a310608318@gmail.com>
* fix: the zero-argument signature in ADMIN swallows explicit arguments
Signed-off-by: hahaha <a310608318@gmail.com>
* fix: fix the CI failures caused by SQL version issues
Signed-off-by: hahaha <a310608318@gmail.com>
* fix: apply the changes based on the review
Signed-off-by: hahaha <a310608318@gmail.com>
---------
Signed-off-by: hahaha <a310608318@gmail.com>
When every partition channel is full, the distributor walked the senders
round-robin with a 100us send timeout each. Tokio timers fire on a 1ms
tick, so a consumer that leaves some partitions unpolled costs about one
millisecond per unpolled partition for every series batch.
SeriesScan::build_stream and scan_all_partitions drain partitions one
after another, and SortPreservingMergeExec above a multi-partition
SeriesScan only pulls the partition holding the current minimum key.
With 16 partitions and one batch per series after a merge, a 40-series
scan read partition by partition took ~480ms (measured on the native
PromQL two-input route).
Wait on all senders at once and send to the first one that frees a slot.
The send-timeout metric goes away with the timeout.
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>