* fix(mito2): hand over a region awaiting the Leader lease of another migration A region that a catchup promoted awaits its Leader lease. A catchup that reached it was always caught up again from this node's WAL with an empty commit, as a repeat of the promoting migration. After a rolled-back migration, the catchup of the next one then recorded none of the source's later entries. The region now records the candidate lease id of the catchup that promoted it. Only a catchup with that id is a repeat; any other catchup, or one without an id, takes the path of a region that awaits nothing, after asking the earlier promotion's tail replay to end. The metric engine passes the candidate lease id to the metadata region too. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * fix(mito2): keep the promoting catchup's id in the promotion fence The id of the catchup that promoted a region is kept in the promotion fence and set by the promotion itself. The tests hold the replay commits they read, wait for the earlier replay to be registered, pin the cancel of a replay held in a listing, the record on a caught-up-again replacement, and the catchups of a region not published conditionally. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * docs(mito2): word the record and the close of a refused catchup plainly Text only: the begin_catchup and promoted_by docs, the close comment on a Follower a refused catchup leaves, the test docs and AGENTS.md. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * fix(mito2): catch an awaiting region up again unless the catchup promotes it Only a catchup with set_writable of another migration takes the path of a region that awaits no Leader lease. A catchup that does not make the region writable is caught up again whatever its id, so a replay that falls short keeps the region with its rows, as before. Word the replay-position check and the close of a refused Follower precisely, carry the migration's id in the remaining test catchups that model an upgrade, and check that each promotion replaces the record. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * fix(mito2): reject competing promotions during leader transitions Signed-off-by: jeremyhi <fengjiachun@gmail.com> * docs(mito2): clarify catchup routing while awaiting a leader lease Signed-off-by: jeremyhi <fengjiachun@gmail.com> --------- Signed-off-by: jeremyhi <fengjiachun@gmail.com>
22 KiB
mito2 — Agent & Contributor Guide
Navigation aid for src/mito2. Keep it short and point to code; do not duplicate
the code here. Paths are relative to the repo root.
Repo-wide rules that apply here: .agents/architecture-invariants.md.
What this crate does
Mito2 is GreptimeDB's primary time-series region storage engine. It owns the
write path (memtable + WAL), flushing memtables to Parquet SST files,
TWCS/windowed compaction, and the read path (multi-level merge + dedup with
snapshot isolation). It implements the RegionEngine trait from store-api.
Module map
| Module | Path | Purpose |
|---|---|---|
engine |
src/mito2/src/engine.rs |
MitoEngine (the RegionEngine impl) and request dispatch |
worker |
src/mito2/src/worker.rs, src/mito2/src/worker/ |
Per-region worker loop; write/alter/flush handlers |
region |
src/mito2/src/region.rs, src/mito2/src/region/version.rs |
MitoRegion state and copy-on-write VersionControl snapshots |
request |
src/mito2/src/request.rs |
WriteRequest/RegionRequest types and result channels |
wal |
src/mito2/src/wal.rs |
Write-ahead log wrapper over log-store |
memtable |
src/mito2/src/memtable/ |
In-memory write buffers (time-series / bulk / partition) |
flush |
src/mito2/src/flush.rs |
FlushScheduler, WriteBufferManager, memtable → SST |
compaction |
src/mito2/src/compaction/ |
Compaction scheduler (scheduler.rs + scheduler/), TWCS picker, strict-window manual picker, compactor, memory control |
compaction/multi_region |
src/mito2/src/compaction/multi_region.rs |
Enterprise lossless routing by a captured table partition rule; selected SSTs to per-region outputs, without manifest publication |
engine/table_compaction |
src/mito2/src/engine/table_compaction.rs |
Enterprise conditional publication of table-compaction results: shared-input snapshot, verified-output checks, and the manifest-locked swap of shared inputs for L0 outputs |
access_layer |
src/mito2/src/access_layer.rs |
SST read/write over the object store |
sst |
src/mito2/src/sst/ |
Parquet format, file metadata, index layout |
series_index |
src/mito2/src/series_index/ |
Native series and samples codecs, exact-key discovery and manifest-backed series index maintenance |
read |
src/mito2/src/read/ |
ScanRegion, merge, dedup, projection, streaming |
manifest |
src/mito2/src/manifest/ |
RegionManifestManager, manifest actions/edits |
cache |
src/mito2/src/cache.rs |
Write/file/page caches |
gc |
src/mito2/src/gc.rs, src/mito2/src/gc/ |
Dropped-file cleanup worker |
schedule |
src/mito2/src/schedule/ |
Local/remote background job scheduling |
remap_manifest |
src/mito2/src/remap_manifest.rs |
Manifest path remapping for region copy/migration |
config |
src/mito2/src/config.rs |
MitoConfig tuning knobs |
tail_replay |
src/mito2/src/tail_replay.rs, src/mito2/src/worker/handle_tail_replay.rs |
Background replay of pending WAL tails into SSTs, published with one manifest edit |
temp_file_sweeper |
src/mito2/src/temp_file_sweeper.rs |
Reclaims temporary files a crashed writer left in a region, triggered when the region becomes a writable leader or a create opens an existing region (under the hdfs-object-store feature) |
test_util |
src/mito2/src/test_util.rs |
TestEnv and builders (under the test feature) |
Write path
MitoEngine::handle_request (engine.rs), or handle_batch_put_requests for the puts
of one request to several regions (one message per worker) → worker loop
(worker/handle_write.rs) → sequence + WAL assembly (region_write_ctx.rs) →
wal.rs → memtable (memtable/) → when buffer pressure trips, flush.rs
writes SSTs via access_layer.rs and appends a RegionEdit to the manifest
(manifest/manager.rs).
When reconstructing primary key bytes, follow the writer's ordering. Mito encodes raw tags in declared primary key order. Metric-engine sparse keys encode table ID and TSID first, then non-null labels in label-name order.
Read path
MitoEngine::handle_query (engine.rs) → read/scan_region.rs takes an
immutable Version (region/version.rs) → scans memtables and Parquet SSTs
(sst/parquet.rs) → merges (read/) and dedups by sequence → projected,
filtered RecordBatch stream.
Compaction SST scans share a read path. Multi-region compaction retains raw versions and routes each row before merging. Sparse routing temporarily materializes only the columns used by the partition rule.
Internal series merges use the query runtime pool forwarded through
QueryScanContext; reader and output-batch accounting uses the separate scan
memory tracker. Direct scanner callers default to an unbounded operator pool.
Live compaction queries read shared per-region state directly from MitoRegion,
without sending a worker request. The scheduler publishes active and pending task
state together; readers clone task Arcs under a short read lock, then filter and
build rows outside the lock. Execution handles provide live background phases.
There is no second task registry or completed-task history. See
compaction/scheduler/state.rs. The datanode provider reuses the lazy inspection scan
path and retains residual SQL filters.
Task cancellation uses RegionRequest::CancelCompaction through Region.Handle;
the owning worker matches the live task ID without entering the DDL queue.
Task-specific cancellation preserves other pending manual work when no DDL is
pending. DDL cancellation retains its existing scheduling fence and priority.
Public surface
- Entry:
MitoEngineinsrc/mito2/src/engine.rs, built viaMitoEngineBuilder. - Trait:
impl RegionEngine for MitoEngine(store-api's region engine contract). - Consumed by
datanode(sendsRegionRequests) and the query layer (scans).
When you change X, also touch Y
- Manifest format (
manifest/action.rs): affects crash recovery and follower replay. Keep it backward compatible. Compaction task state does not belong in the manifest; publication uses ordinary file edits after locked input checks. Shared SSTs require Enterprise capability. Compatibility fixtures:tests/compatibility/manifest/table_compaction/andtests/compatibility/manifest/pending_tails/. - SST/Parquet layout (
sst/): readers must stay compatible with existing files. Metadata COUNT (read/scan_region/aggr.rs) uses the footer for both file-local uniqueness and all-Put evidence. Only writers that fold versions may addgreptimedb.deduped. LastNonNull can retain delete barriers, so it requires all-Put output before adding the marker. In non-append regions, a multi-row SST also needsFileMeta::dedup_marker_trusted. Old manifests default this field to false. External imports cannot establish trust, and internal file transfers preserve it. - Index extensions: shared contracts and provider validation live in
sst/index/registry.rs; typed sketch options are enterprise-gated. Lifecycle and failure tests live inengine/index_build_test.rsandcompaction/. A background rebuild must not replace a file that carries extension indexes (worker/handle_rebuild_index.rs::needs_background_indexes). - Narthex series maintenance (
series_index/task.rs) streams exact keys from pinned Narthex files and publishes index replacements through a region manifest edit. Expiry respects the certified window. Reader handles pin retired files until the last reader releases them. - Series discovery (
read/series_scan/prepared/narthex.rs) checks the sequence domain, schema and required artifacts before skipping sample keys. Samples and live memtables determine visibility. The series and sample wire formats are documented indocs/formats/mito-series.mdanddocs/formats/mito-samples.md. Partition rules on non-tag columns apply to sample rows. Tag-only rules apply during series discovery. - Request types (
request.rs): usually tied to proto definitions consumed bydatanode. - WAL/memtable encoding (
wal/,memtable/): breaks replay if changed incompatibly.
The grouped Narthex samples layout, including logical key references and physical key frames, is specified in mito-samples.md.
Testing
cargo nextest run -p mito2
Tests live next to the code as *_test.rs (e.g. src/mito2/src/engine/flush_test.rs).
TestEnv in test_util.rs spins up an engine over an in-process object store.
Gotchas
-
Parquet versus Narthex storage is fixed at region creation. ALTER cannot cross that boundary; COPY, remap, and imported edits must reject mismatches before publication. Readers and compaction select storage from region options, not by inspecting individual files. Parquet flat/primary-key layouts may coexist.
-
Narthex series-index maintenance and scans share fixed-window sequence watermarks over manifest-tracked index files. The coverage contract lives in
docs/formats/mito-series.md. Keep the samples and series format specs focused on persisted layout, field semantics, and compatibility. Narthex index selection and scheduling policy lives inseries_index/task.rs. -
Parquet row groups have uniform row counts except for the final group (
sst/parquet/row_selection.rs). Memory-pressure flushing must not create arbitrary partial groups: readers and index row IDs rely on this layout. -
Encoded Narthex bulk parts already contain the final samples manifest and part objects. Their file ID is embedded in the manifest. A direct flush retry reuses that ID, so cleanup for a rejected upload must finish before the retry.
-
Append-mode Narthex raw-series reads apply LastRow dedup after merging; non-append reads use the configured merge mode, and batch reads retain append semantics. Physical COPY follows Parquet's untrusted source-sequence semantics; repartition still assigns admission sequences. The region worker owns COPY locks; task guards hold them through publication and installation so retries cannot race failure cleanup, including across region reopen. The last active or queued task removes its lock entry, including on cancellation.
-
Sequence numbers are strictly increasing per region; dedup and snapshot reads depend on this. Do not change assignment lightly.
-
Manifest version is monotonic — never reset or skip it. Staging takes no version: its actions stay in memory (
manifest/manager.rs) and are committed once, as the next version, when staging ends (MitoRegion::end_staging_locked). -
In regions whose writes require a lease and whose WAL is the object store WAL, each manifest version has one fixed object name, created conditionally. A late create can succeed again once checkpoint cleanup frees the name, so a commit checks its result (
ensure_version_not_checkpointedinmanifest/storage.rs). A conditional open lists checkpoints, fetches deltas, then lists checkpoints again. It fails retryably if a checkpoint now covers the replay start. A gap triggers the same check before fetching deltas, allowing recovery of legacy histories with gaps when no checkpoint covers the replay start. Cleanup may only delete deltas below a checkpoint. -
In those regions a commit after the region's Leader deadline sends nothing, and a version conflict fences the region (
ManifestContext::fence_for_reload): no lease or catchup promotes it until the worker swaps in an instance reloaded from the new manifest (worker/handle_reload.rs). A tail replay round that fails while the storage holds a newer manifest fences a writable leader the same way. Never await a worker sender while holding a manifest guard. The catchup commit (ManifestContext::commit_catchup_locked, whichcommit_catchupwraps) is the exception: it commits as a Follower without the deadline check, and a conflict fails the catchup retryably without fencing the region; a retry reopens it from the newer manifest. -
Pending tails (
RegionManifest::pending_tails) are WAL ranges a region still has to recover; the flushed entry id never prunes them. Opening a region replays its WAL afterRegionManifest::wal_replay_start, and so does a catchup's replay. The WAL releases at open, after a flush, on close, after a catchup's replay and after a handover stay below this node's tails (cap_wal_release), and so does the boundwal_release_boundreturns; truncate, drop and offline cleanup release without that cap. Handoff floors are dropped once the flushed entry id reaches them, inRegionManifestBuilder::try_build. While a region has pending tails, scans and memtable/SST stats fail withRegionPendingTails, and so do truncate, entering staging, a repartition flush, a close withflush_on_close, and every ALTER other than adding nullable columns without a default or changing options; compaction pauses. These checks run before any region state changes. Full-listing GC skips a region that has pending tails or whose manifesthas_update()reports newer, or fails to check. -
A catchup with
set_writableand the source's last entry, of a region whose manifest is published conditionally and that does not await the Leader lease of a promotion by a catchup with the same candidate lease id (AwaitedPromotionfrombegin_catchup), hands the region over without replaying: seehand_overandHANDOVER_SEQUENCE_GAPinregion/catchup.rs. It refuses an awaiting region that is still a leader afterbegin_catchup, a region with rows in its memtable, or an instance whose tail replay has not reported its end; the worker applies the committed edit (handle_handed_over). A manifest sync and a follower's skip-WAL change are refused while the instance is in a catchup, or is fenced while the worker holds a catchup or reload registration for the region (is_catching_up_or_reloading); a follower opened after a close is not refused for its predecessor's catchup. A takeover (no reported entry) is prepared byprepare_takeoversinengine.rs(manifest version, one heartbeat request, one WAL listing per source, even after ALTER enables skip_wal) and waits for its candidate lease (GrantedLeases::wait_for_candidate_lease) before it commits after that version. -
A leader that is writable, altering or editing replays its pending tails in one background task (
tail_replay.rs), started by the worker when a lease, catchup or role change makes the region writable, or when it registers a region created or opened as a writable leader. Each tail goes into its own SSTs, since an SST can give all its rows its largest sequence. The task commits outside the edit queue (ManifestContext::update_manifest_for_tails) and always reports its end, which lets the worker start the next replay or reload a fenced region. The edit that records tails must raise the committed sequence to theirs, or writes accepted during the replay lose to replayed rows. This node's later entry ids must be above every tail'supto, and its unflushed entries at or below one must be in its own tails, or the tail commit's flushed entry id skips them. A node bounds its replays' concurrency and SST writes apart from flushes, and their chunk memory within the global write buffer (TailReplayLimits). Replayed SSTs build indexes as flushed ones (IndexBuildType::Flush), undercreate_on_flush.RegionRequest::DiscardPendingTailsdiscards one node's tails without replaying them; it commits throughupdate_manifest_for_tailstoo (worker/handle_tail_replay.rs) and raises the flushed entry id to the largest discardedupto, so the same entry id rule applies. -
Lock ordering: take the manifest lock before updating
version_control; the reverse deadlocks against concurrent flush/compaction. -
All region I/O runs on tokio workers; never
block_oninside a worker. -
Loaded regions have resident compaction state, including
Idleand handed-off DDLs. Publish create/open/catchup results through the worker'sregister_region; only close/drop unregisters them. Seecompaction/scheduler/state.rs. -
Explicit truncate retires shared references too (
worker/handle_truncate.rs):Allremoves all data;ByTimeRangesremoves fully contained files. Other regions/readers still protect the shared objects. Stale compaction results must not reinstate truncated inputs. -
Manifest and runtime file views share immutable
FileMetaRefvalues. The engine-local metadata interner compares complete metadata before sharing; file identity alone is insufficient. Partition expressions are shared by table and complete expression content, so historical SST partition rules remain distinct after repartition. Interned references reclaim entries on final release, including delayed readers, without a maintenance task or new writes. Hash table capacity remains allocated until the interner is dropped. Manifest consumers receive the interner directly. Scrape-time entry counts use weak references and do not add maintenance tasks or retain engine storage. Index replacement preserves old readers and updates the lifetime guard to the newest metadata. -
Local compaction units use the snapshot-free
CompactionContext. Retaining a fullCompactionRegionin a unit pins other units' inputs and delays SST purge. -
Candidate waiting history is owned by the region scheduler (
scheduler/history.rs). Background planning works on a private snapshot; only a fenced result may replace resident history, and an accepted plan consumes the fairness turn for each selected key. Execution success or failure must not rewrite waiting ages. TWCS discovery must not mutate scheduler state. -
Compaction admission is engine-wide (
compaction/scheduler/coordinator.rs), but pick/DDL state remains worker-owned. Repick only after every batch unit'sReleased; FIFO submission is not admission and pipeline children share the parent unit's slot. Keep service accounting across batches until region unload. -
In flat batches, equal
__primary_keydictionary keys imply the same series, but not the reverse:wrap_pk_binary_to_dictgives every row its own key. Compare key bytes when grouping rows by series. -
Staging regions, ending staging included, never flush: a flush would stage its SST and release the rows' WAL, losing them if staging does not end successfully. Every flush trigger in
worker/handle_flush.rsmust skip them: background triggers testis_writable()anddefers_background_flush(), a flush requestis_flushable()andis_staging()(is_writable()andis_flushable()are false while ending staging).handle_closeleaves staging first. Tail replays never run for them: entering staging fails while tails are pending. -
Direct SST imports without a staging binding cannot publish into staging.
worker/handle_manifest.rsseals edit admission while EnterStaging drains accepted edits. Scheduler-owned DDLs resume through execution, bypassing initial admission. -
On a node whose writes need a lease, a region that a catchup made writable waits for a Leader or StagingLeader lease sent after the catchup (
awaits_leader_lease). Until thenManifestContext::update_lockedrefuses its commits unless they are staged or the region is downgrading (a close that must flush downgrades first); only a replay of tails (TailsEditor::Replay) skips the check, a discard does not, and ending staging checks it beforecommit_staged_locked.ManifestContext::commit_catchupcommits an empty edit (a handover's edit throughcommit_catchup_locked) as a Follower; fire its hook only after every manifest guard is dropped, including the old instance's read guard held byhandle_caught_up_again. No flush or compaction trigger starts work for a waiting region except a downgrade's flush. The lease that ends the wait wakes the worker (handle_leader_lease_wait_ended) to schedule the flushes the wait deferred and, only if the region is then a writable leader, start a compaction. The missing indexes, the refused index build retries and the backfilled metadata wait indeferred_lease_work, which the worker sweeps after each batch (sweep_deferred_lease_work). A catchup of a waiting region with the candidate lease id of the catchup that promoted it catches it up again into an unregistered replacement while the region stays registered, demoted unless it is in a transient leader state. The replacement replaces it only if the replay succeeds, the region took no write and made no commit meanwhile and, for a catchup that makes it writable, the replacement's catchup commit succeeds; otherwise the region keeps its memtable for the next Leader lease (catch_up_again,handle_caught_up_again); the datanode upgrade handler sends that catchup unlessRegionEngine::is_confirmed_leaderis true, so an engine wrapping mito must implement that method from mito's answers (the metric engine requires both regions of the pair). A non-promoting catchup of a waiting region takescatch_up_againregardless of candidate id. After any takeover check, a catchup withset_writableand a different or missing id returnsRegionBusyif the region is still a leader (e.g. Editing or Downgrading). On a Follower it asks the tail replay to end and proceeds as for a region with no pending promotion. A Follower lease carrying acandidate_lease_idleaves a waiting region alone (ManifestContext::demote_candidate); other Follower leases demote it. -
The latest lease each region received (
GrantedLeasesinlease.rs) lives outside the region instance, so a reopen during catchup keeps it. Every path that removes a region from a worker's region map must also remove its record and its deferred lease work:RegionWorkerLoop::remove_region(worker/handle_close.rs, also used after a close-time flush),drop_region(worker/handle_drop.rs) andRegionWorkerLoop::clean(worker.rs).
Maintenance contract
Update this file when you add/rename a top-level module, change the write/read path entry points, or alter a persisted format (manifest, SST, WAL).