mito2/engine/region_hook.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Region hook extension point for observing SST writes and manifest mutations.
16//!
17//! ## Design
18//!
19//! The [`RegionHook`] trait observes region activity through two categories of
20//! callbacks — manifest/file observation and region lifecycle:
21//!
22//! - [`on_sst_files_written`]: Fires when mito2 physically writes SST **data files**.
23//! Provides per-file [`SstInfo`] + [`FileMeta`]; metadata richness varies by path
24//! (see [`SstFileInfo`] and the coverage footnote).
25//!
26//! - [`on_manifest_updated`]: Fires after a manifest write is committed to the **live**
27//! (normal) manifest directory. Actions staged in memory (enter staging,
28//! operations during staging, the intermediate apply-staging edit) are suppressed —
29//! their effects are accumulated and delivered in a single notification when the
30//! staged actions are promoted to the live manifest. Receives the full
31//! [`RegionMetaActionList`] so consumers can inspect what changed (file additions/
32//! removals, schema changes, truncation, partition expression changes, etc.).
33//!
34//! - [`on_region_opened`] / [`on_region_closed`] / [`on_region_dropped`] / [`on_region_files_removed`]:
35//! Region **lifecycle** callbacks for open, close, logical drop, and physical file removal.
36//! See [Region lifecycle](#region-lifecycle) below.
37//!
38//! Hook implementations are registered via the [`Plugins`](common_base::Plugins) system:
39//! ```ignore
40//! plugins.insert(Arc::new(MyHook) as RegionHookRef);
41//! ```
42//!
43//! ## Coverage
44//!
45//! Only manifest writes to the **normal** (live) manifest directory trigger
46//! `on_manifest_updated`. Actions staged in memory (operations
47//! that happen while the region is in staging mode) are intentionally suppressed:
48//! their effects are accumulated and delivered in a single notification when
49//! the staged actions are committed to the live manifest via `end_staging_locked`.
50//!
51//! | Scenario | `on_sst_files_written` | `on_manifest_updated` |
52//! |------------------------------|:----------------------:|:---------------------:|
53//! | Flush (memtable → SST) | ✅ Yes | ✅ Yes |
54//! | Local compaction | ✅ Yes | ✅ Yes |
55//! | Pending WAL tail replay | ✅ Yes | ✅ Yes |
56//! | Remote compaction | ✅ (compactor node) ¹ | ✅ (compactor node) ¹ |
57//! | RegionEdit / bulk ingestion | ❌ (files pre-written) | ✅ Yes |
58//! | Copy region | ❌ (object-store copy) | ✅ Yes |
59//! | Apply staging (promote) | ❌ (delegates to edit) | ✅ Yes ² |
60//! | Alter (schema change) | ❌ (no SST files) | ✅ Yes |
61//! | Truncate | ❌ (removes files) | ✅ Yes |
62//! | Enter staging | ❌ (no SST files) | ❌ (in memory) |
63//! | Operations during staging | N/A | ❌ (in memory) |
64//! | Async index build | ❌ (index files only) | ✅ Yes |
65//! | Writable catchup ³ | ❌ (no SST files) | ✅ Yes |
66//!
67//! ¹ Remote compaction runs on a dedicated compactor node via `CompactionRegionOpener::open()`;
68//! pass plugins via `OpenCompactionRegionRequest` to enable hooks there. `sst_infos` is
69//! `#[serde(skip)]` over the wire, so each [`SstInfo`] is rebuilt from [`FileMeta`] with
70//! empty footer/index — see [`SstFileInfo`] for field-level detail.
71//! ² Apply staging fires `on_manifest_updated` once when `end_staging_locked` commits
72//! all staged manifest actions (including the SST file additions) into the live manifest.
73//! The intermediate staging `RegionEdit` is staged in memory and does not
74//! fire the hook — its file list is included in the promote notification.
75//! ³ Only under conditional manifest publication: the catchup commits a `RegionEdit` while the
76//! region is still a Follower. A catchup that replays the WAL commits an empty edit. A handover
77//! records this node's handoff floor. If the source bound exceeds its replay start, it also records the
78//! region's pending tails with the source's new tail appended, and the raised committed
79//! sequence.
80//!
81//! The following paths do **not** trigger any hook:
82//! - Follower region sync, and a catchup that does not make the region writable (manifest
83//! read-only; followers don't author changes). A catchup that makes the region writable
84//! under conditional manifest publication commits an edit (³) and fires
85//! `on_manifest_updated` for it.
86//! - GC / checkpoint / remap (internal bookkeeping, not logical state changes)
87//!
88//! An explicit region **drop** does fire lifecycle hooks — see
89//! [Region lifecycle](#region-lifecycle).
90//!
91//! ## Region lifecycle
92//!
93//! Beyond manifest/SST observation, the hook observes the high-level lifecycle of an
94//! active region:
95//!
96//! | Event | Method | When |
97//! |-------|--------|------|
98//! | Open | [`on_region_opened`] | A create or open request registers the region as active (the counterpart to close/drop). Does not fire for the compactor's transient regions or the catch-up reopen. |
99//! | Close | [`on_region_closed`] | A close request (or a close-after-flush) removes the region from the active set. Data files, manifest and WAL state are **preserved**; the region may be reopened. |
100//! | Logical drop | [`on_region_dropped`] | A drop request has been handled: the region leaves the active set and its WAL entries are marked obsolete. Data files are **not yet deleted**. |
101//! | Physical file removal | [`on_region_files_removed`] | The drop GC worker has deleted the region directory. Terminal file-lifecycle event. |
102//! | Global GC pass | [`on_region_gc`] | The datanode's global GC worker finished a GC pass for a region — both periodic GC for live regions and the global reclamation of dropped/repartitioned regions (`is_region_dropped`). Also fired by the offline cleanup path (`handle_offline_cleanup_request`, i.e. soft-drop PURGE) once the region directory is removed, with `is_region_dropped = true` and `full_file_listing = true`. |
103//!
104//! Notes:
105//! - `on_region_closed` / `on_region_dropped` run **inline in the region worker loop**,
106//! so implementations must be fast (same contract as `on_manifest_updated`).
107//! - `on_region_opened` runs inline in the worker loop on the **create** path, but on the
108//! **open** path it fires inside the spawned open task (`common_runtime::spawn_global`),
109//! i.e. concurrently with the worker loop — after WAL replay, before the region is
110//! registered and its open request is acknowledged. Implementations must still be fast
111//! and must not assume worker-loop-thread affinity or strict ordering against concurrent
112//! requests to other regions.
113//! - `on_region_files_removed` runs on the background drop GC task, outside the worker loop.
114//! - When global GC is enabled and a normal table region is dropped with `partial_drop`, its
115//! directory is left for global reclamation and `on_region_files_removed` is **not** fired
116//! by the drop worker (observe it via the global GC path instead).
117//! - The offline cleanup path (`handle_offline_cleanup_request`, reached by a soft-drop
118//! `PURGE`) force-removes the region directory but has no `RegionMetadataRef` for the
119//! offline region, so it cannot fire `on_region_files_removed`. It fires `on_region_gc`
120//! instead — with `is_region_dropped = true` and `full_file_listing = true` — so
121//! extensions can reclaim sidecar state for the now-removed region. A hook `Err` is
122//! propagated so the caller retries the (idempotent) cleanup.
123//! - Logical file removal (compaction, region edit, truncate) is already observable via
124//! [`on_manifest_updated`] (`Edit.files_to_remove` / `Truncate` action); only the drop
125//! worker's physical directory deletion needs a dedicated file hook.
126//!
127//! ## Invocation points
128//!
129//! `on_sst_files_written` is invoked at the SST write site (flush task, compaction task or
130//! tail replay task), immediately after SST files are written but **before** the manifest
131//! is committed.
132//!
133//! `on_manifest_updated` is funneled through the shared write that
134//! [`ManifestContext::update_locked`] makes after it checks the Leader lease; the
135//! write calls the low-level [`RegionManifestManager::update_with_verification`]
136//! and packages each successful write into a [`PendingManifestHook`]. The caller
137//! owns the write lock, drops it, and *then* fires the receipt — the hook must
138//! never run under the lock. [`ManifestContext::update_manifest`] is the common
139//! case: it acquires the lock, delegates to `update_locked`, and fires the
140//! receipt in one go. The role-state backfill and the table-compaction publication
141//! call `update_locked` directly under their own held guard; a replay of pending
142//! tails makes the same write without the Leader lease check, the end of
143//! staging builds its receipt in `commit_staged_locked`, and the edit of a catchup
144//! builds its receipt in [`ManifestContext::commit_catchup_locked`].
145//!
146//! Non-logical writes (GC, staging bookkeeping) call the manager's own methods
147//! directly and intentionally do not fire the hook.
148//!
149//! ## Future work
150//!
151//! `on_region_files_removed` currently covers only the **drop** GC worker's physical
152//! directory removal. The global-GC reclamation path and the offline-cleanup path
153//! (soft-drop PURGE) are covered by `on_region_gc` instead. A broader per-file
154//! `on_files_removed` hook covering compaction removal and truncate is not yet implemented
155//! (though logical file removal is already observable via `on_manifest_updated`,
156//! and the global GC reclamation path is covered by `on_region_gc`).
157//! Role/leadership transitions (`on_region_role_changed`) are also not hooked.
158//!
159//! [`on_sst_files_written`]: RegionHook::on_sst_files_written
160//! [`on_manifest_updated`]: RegionHook::on_manifest_updated
161//! [`on_region_opened`]: RegionHook::on_region_opened
162//! [`on_region_closed`]: RegionHook::on_region_closed
163//! [`on_region_dropped`]: RegionHook::on_region_dropped
164//! [`on_region_files_removed`]: RegionHook::on_region_files_removed
165//! [`on_region_gc`]: RegionHook::on_region_gc
166//! [`RegionManifestManager::update_with_verification`]: crate::manifest::manager::RegionManifestManager::update_with_verification
167//! [`ManifestContext::update_locked`]: crate::region::ManifestContext::update_locked
168//! [`ManifestContext::update_manifest`]: crate::region::ManifestContext::update_manifest
169//! [`ManifestContext::commit_catchup_locked`]: crate::region::ManifestContext::commit_catchup_locked
170
171use std::collections::HashSet;
172use std::fmt::Debug;
173use std::sync::Arc;
174
175use async_trait::async_trait;
176use parquet::file::metadata::ParquetMetaData;
177use store_api::ManifestVersion;
178use store_api::metadata::RegionMetadataRef;
179use store_api::storage::RegionId;
180
181use crate::access_layer::{AccessLayer, AccessLayerRef};
182use crate::error::Result;
183use crate::manifest::action::{RegionMetaActionList, RemovedFile};
184use crate::sst::file::{FileMeta, RegionFileId};
185use crate::sst::parquet::SstInfo;
186
187/// A deferred [`RegionHook::on_manifest_updated`] notification produced by a
188/// logical manifest write via [`ManifestContext::update_locked`](crate::region::ManifestContext::update_locked),
189/// a replay of pending tails or the end of staging.
190///
191/// Must be [`fire`](Self::fire)d **after** the manifest write lock is released
192/// (the hook may read the manifest). `#[must_use]` so a forgotten receipt warns.
193///
194/// ## Staging suppression
195///
196/// When `is_staging` is `true`, [`fire`](Self::fire) is a no-op — the actions were
197/// staged in memory. The hook only observes writes to the live (normal)
198/// manifest directory. Staging actions are accumulated and delivered in a single
199/// notification when `end_staging_locked` commits them (`is_staging = false`).
200#[must_use = "the region hook must be fired after releasing the manifest write lock"]
201pub(crate) struct PendingManifestHook {
202 region_id: RegionId,
203 /// `None` when no hook is registered (fire becomes a no-op).
204 action_list: Option<RegionMetaActionList>,
205 version: ManifestVersion,
206 hook: Option<RegionHookRef>,
207 /// Whether the actions were staged in memory.
208 /// When `true`, `fire()` is suppressed — the hook only observes live manifest writes.
209 is_staging: bool,
210}
211
212impl PendingManifestHook {
213 pub(crate) fn new(
214 region_id: RegionId,
215 action_list: Option<RegionMetaActionList>,
216 version: ManifestVersion,
217 hook: Option<RegionHookRef>,
218 is_staging: bool,
219 ) -> Self {
220 Self {
221 region_id,
222 action_list,
223 version,
224 hook,
225 is_staging,
226 }
227 }
228
229 /// The manifest version produced by the write.
230 pub(crate) fn version(&self) -> ManifestVersion {
231 self.version
232 }
233
234 /// Fires the hook if one is registered, **unless** the actions were staged in
235 /// memory (`is_staging = true`). Safe to call unconditionally:
236 /// it is a no-op when no hook is registered or when the actions were staged in memory.
237 pub(crate) async fn fire(self) {
238 if self.is_staging {
239 return;
240 }
241 if let (Some(hook), Some(action_list)) = (self.hook, self.action_list) {
242 hook.on_manifest_updated(self.region_id, &action_list, self.version)
243 .await;
244 }
245 }
246
247 /// Merges two pending notifications into one so consumers observe a single
248 /// `on_manifest_updated` call covering all actions. The combined action list
249 /// keeps `self`'s actions followed by `other`'s, and the *later* manifest
250 /// version wins. Used when a sequence of writes (e.g. staging-exit followed
251 /// by metadata backfill) should notify the hook exactly once.
252 ///
253 /// `is_staging` is `true` only if **both** sides are staging; if either side
254 /// is a live write, the merged result is also live.
255 pub(crate) fn merge(self, other: PendingManifestHook) -> PendingManifestHook {
256 debug_assert_eq!(
257 self.region_id, other.region_id,
258 "Cannot merge pending hooks of different regions: {:?} and {:?}",
259 self.region_id, other.region_id
260 );
261 PendingManifestHook {
262 region_id: self.region_id,
263 action_list: match (self.action_list, other.action_list) {
264 (Some(mut a), Some(b)) => {
265 a.actions.extend(b.actions);
266 Some(a)
267 }
268 (a, None) => a,
269 (None, b) => b,
270 },
271 version: self.version.max(other.version),
272 hook: self.hook.or(other.hook),
273 is_staging: self.is_staging && other.is_staging,
274 }
275 }
276}
277
278/// Information about a single SST data file written during flush or compaction.
279///
280/// `file_meta` is always complete. `sst_info_ref` mirrors those scalars and adds the
281/// Parquet footer (`file_metadata`) and full `index_metadata` — but **only when mito2
282/// wrote the file in-process** (flush, local compaction). On remote compaction `SstInfo`
283/// is rebuilt from `FileMeta`, so both are empty; hooks needing column statistics must
284/// fetch the footer from object storage.
285pub struct SstFileInfo<'a> {
286 pub sst_info_ref: &'a SstInfo,
287 pub file_meta: &'a FileMeta,
288}
289
290/// Externally produced SST with its verified footer. Index-builder statistics
291/// are deliberately absent: they cannot be reconstructed from FileMeta.
292pub struct VerifiedSstFileInfo<'a> {
293 pub file_meta: &'a FileMeta,
294 pub footer: &'a Arc<ParquetMetaData>,
295}
296
297/// Hook for observing region mutations in mito2.
298///
299/// Implementations can be registered via the `Plugins` system:
300/// ```ignore
301/// use std::sync::Arc;
302/// use common_base::Plugins;
303/// use mito2::engine::region_hook::{RegionHook, RegionHookRef};
304///
305/// plugins.insert(Arc::new(MyHook) as RegionHookRef);
306/// ```
307#[async_trait]
308pub trait RegionHook: Send + Sync + Debug {
309 /// Called after SST **data files** are physically written, before manifest commit.
310 ///
311 /// This fires only when mito2 itself writes SST files (flush, compaction and the replay
312 /// of pending WAL tails).
313 /// It does **not** fire when SST files are pre-written externally (bulk ingestion,
314 /// copy region) or when only index files are written (async index build).
315 ///
316 /// # Metadata availability
317 /// See [`SstFileInfo`]: `file_meta` is always complete, but the [`SstInfo`] footer
318 /// and index output are empty on remote compaction. Hooks needing column statistics
319 /// (e.g. an Iceberg manifest) must fetch the footer from object storage.
320 async fn on_sst_files_written(
321 &self,
322 region_id: RegionId,
323 region_metadata: &RegionMetadataRef,
324 files: &[SstFileInfo<'_>],
325 ) {
326 let _ = (region_id, region_metadata, files);
327 }
328
329 /// Queries durable file protections immediately before deletion. Implementations
330 /// must include pending uploads, inputs and undecided outputs, and fail on
331 /// unavailable/uncertain state. File identities are scoped by the access layer's
332 /// storage, table directory and PathType; protection covers all index generations.
333 /// GC rechecks the manifest after this await. This is not `on_region_gc`, which
334 /// is too late to protect anything. Calls must not retain a manifest lock.
335 async fn protected_sst_files(
336 &self,
337 access: &AccessLayer,
338 files: &[RegionFileId],
339 ) -> Result<HashSet<RegionFileId>> {
340 let _ = (access, files);
341 Ok(HashSet::new())
342 }
343
344 /// Called for verified table-compaction outputs before manifest publication.
345 /// Unlike `on_sst_files_written`, this carries actual remote footers without
346 /// fabricating unavailable index-builder statistics. Retries may repeat it;
347 /// no manifest lock is held and implementations must be idempotent. Publication
348 /// may still fail after this callback; it is not a publication acknowledgement.
349 /// Use `on_manifest_updated` to observe a successful manifest commit.
350 async fn on_sst_files_verified(
351 &self,
352 region_id: RegionId,
353 region_metadata: &RegionMetadataRef,
354 files: &[VerifiedSstFileInfo<'_>],
355 ) {
356 let _ = (region_id, region_metadata, files);
357 }
358
359 /// Called after the region manifest is successfully committed to the **live**
360 /// (normal) manifest directory.
361 ///
362 /// Fires for: flush, compaction, region edit, copy region, alter, truncate,
363 /// async index build, apply-staging promote, and a catchup that makes the
364 /// region writable under conditional manifest publication (a `RegionEdit`
365 /// committed while the region is still a Follower, whose contents the module
366 /// docs list). Does **not**
367 /// fire for actions staged in memory (enter staging, operations during staging,
368 /// the intermediate apply-staging edit) — those are suppressed because their
369 /// effects are accumulated and delivered in a single promote notification.
370 ///
371 /// Does **not** fire for:
372 /// - Follower sync and a catchup that does not make the region writable
373 /// (no write)
374 /// - GC / checkpoint (internal bookkeeping)
375 /// - Failed manifest updates
376 async fn on_manifest_updated(
377 &self,
378 region_id: RegionId,
379 action_list: &RegionMetaActionList,
380 manifest_version: ManifestVersion,
381 ) {
382 let _ = (region_id, action_list, manifest_version);
383 }
384
385 /// Called once a region **open** or **create** succeeds, but **before** the
386 /// region is registered in the engine's active set (`insert_region` runs
387 /// immediately afterwards).
388 ///
389 /// Fires once when a region becomes active via a create or open request —
390 /// the natural counterpart to [`on_region_closed`] / [`on_region_dropped`].
391 /// It does **not** fire for the compactor's transient compaction regions
392 /// (`CompactionRegionOpener::open`), nor for the internal reopen performed during
393 /// follower catch-up / leadership promotion.
394 ///
395 /// On the **create** path it runs inline in the region worker loop; on the
396 /// **open** path it runs inside the spawned open task
397 /// (`common_runtime::spawn_global`), concurrently with the worker loop
398 /// (after WAL replay, before the region is registered/acknowledged).
399 /// Implementations must be fast and must **not** assume worker-loop-thread
400 /// affinity or strict ordering against concurrent requests to other regions.
401 ///
402 /// [`on_region_closed`]: RegionHook::on_region_closed
403 /// [`on_region_dropped`]: RegionHook::on_region_dropped
404 async fn on_region_opened(&self, region_id: RegionId, region_metadata: &RegionMetadataRef) {
405 let _ = (region_id, region_metadata);
406 }
407
408 /// Called after a region is **closed** via a close request.
409 ///
410 /// The region is removed from the engine's active set, but its data files,
411 /// manifest, and WAL state are **preserved**; the region may be reopened
412 /// later. Fires once per successful close, after the region's background
413 /// tasks (flush/compaction) have been stopped.
414 ///
415 /// Fires for a region of **any** role (leader or follower) that is closed.
416 /// Does **not** fire when a region is dropped (see [`on_region_dropped`]).
417 ///
418 /// Runs inline in the region worker loop; implementations should be fast.
419 ///
420 /// [`on_region_dropped`]: RegionHook::on_region_dropped
421 async fn on_region_closed(&self, region_id: RegionId, region_metadata: &RegionMetadataRef) {
422 let _ = (region_id, region_metadata);
423 }
424
425 /// Called after a region is **logically dropped** (a drop request has been
426 /// handled).
427 ///
428 /// The region is removed from the active set and its WAL entries are marked
429 /// obsolete. Its data files are **not yet deleted** — they are scheduled for
430 /// asynchronous removal by the GC worker. Observe physical deletion via
431 /// [`on_region_files_removed`].
432 ///
433 /// Runs inline in the region worker loop; implementations should be fast.
434 ///
435 /// [`on_region_files_removed`]: RegionHook::on_region_files_removed
436 async fn on_region_dropped(&self, region_id: RegionId, region_metadata: &RegionMetadataRef) {
437 let _ = (region_id, region_metadata);
438 }
439
440 /// Called after a dropped region's data files are **physically removed** by
441 /// the drop GC worker (the region directory has been deleted).
442 ///
443 /// This is the terminal event in a region's file lifecycle; no further
444 /// callbacks fire for this region id afterwards. Fires only when the drop
445 /// worker itself deletes the directory. When global GC is enabled and the
446 /// region is a normal table region dropped with `partial_drop`, the
447 /// directory is left for global reclamation and this hook is **not** fired
448 /// by the drop worker.
449 ///
450 /// Runs on a background task, outside the region worker loop.
451 async fn on_region_files_removed(
452 &self,
453 region_id: RegionId,
454 region_metadata: &RegionMetadataRef,
455 ) {
456 let _ = (region_id, region_metadata);
457 }
458
459 /// Called after the datanode's global GC worker (`LocalGcWorker`) finishes a
460 /// GC pass for a region — live regions (periodic GC) or dropped/repartitioned
461 /// regions (the global reclamation path). Also fired by the offline cleanup
462 /// path (`handle_offline_cleanup_request`, i.e. soft-drop PURGE) once the
463 /// region directory has been removed. Lets extensions with sidecar files
464 /// outside mito2's region dir clean up residual files.
465 ///
466 /// Always scoped to [`RegionGcInfo::removed_files`]: clean only sidecar
467 /// artifacts for the files mito deleted this pass. On a
468 /// [`RegionGcInfo::full_file_listing`] pass you may also reconcile
469 /// sidecar-only orphans (e.g. detect a fully-reaped region by cross-checking
470 /// the region dir against your own manifest). This callback never authorizes
471 /// blind whole-directory removal — derive "fully reaped" from your own state
472 /// so a stale mito snapshot can't cause accidental deletion.
473 /// [`RegionGcInfo::is_region_dropped`] is context, not authorization.
474 ///
475 /// # Retry
476 ///
477 /// Returning `Err` keeps the region un-acknowledged (`need_retry_regions`)
478 /// for a future replay. **Dropped/repartitioned**: guaranteed — metasrv keeps
479 /// the `table_repart` tombstone until `Ok`, so full-listing passes continue
480 /// until cleanup finishes. **Live**: best-effort — not expedited through
481 /// candidate selection, and a later full-listing pass may not reconstruct the
482 /// same `removed_files`; treat live cleanup as opportunistic.
483 ///
484 /// `region_metadata` is `None` for dropped regions; use `region_id` +
485 /// `access_layer`. Idempotent.
486 ///
487 /// # Execution context
488 ///
489 /// On the global-GC path this runs on the background GC task, outside the
490 /// region worker loop. The offline cleanup path
491 /// (`handle_offline_cleanup_request`, reached by soft-drop PURGE) instead
492 /// runs it **inline in the region worker loop** and propagates `Err` so the
493 /// caller retries the (idempotent) cleanup. So — like `on_region_closed` /
494 /// `on_region_dropped` — implementations **must be fast and must not block
495 /// indefinitely** while awaited there: while the callback is pending, every
496 /// subsequent DDL request for every region on that worker is blocked.
497 /// Extension authors who wrote their hook against the "background GC task"
498 /// contract must account for this second, latency-sensitive trigger.
499 ///
500 /// The offline cleanup path fires this callback once the region directory is
501 /// confirmed **absent** — including no-op purges where nothing was actually
502 /// removed this call (a retry after the directory was already gone, or a
503 /// region that never had files on this datanode, since
504 /// `remove_region_dir_for_full_drop` returns `Ok` for an absent/empty
505 /// prefix). `RegionGcInfo::removed_files` is empty in that case; do **not**
506 /// interpret the call as "files were deleted in this call". This is
507 /// asymmetric with the GC path, which fires only when files were deleted or
508 /// a full listing was performed.
509 async fn on_region_gc(
510 &self,
511 region_id: RegionId,
512 region_metadata: Option<&RegionMetadataRef>,
513 access_layer: &AccessLayerRef,
514 info: &RegionGcInfo<'_>,
515 ) -> Result<()> {
516 let _ = (region_id, region_metadata, access_layer, info);
517 Ok(())
518 }
519}
520
521/// What mito2's GC pass deleted for a region, handed to
522/// [`RegionHook::on_region_gc`].
523pub struct RegionGcInfo<'a> {
524 /// Files mito2 physically deleted this pass. Cleanup must be scoped to these
525 /// (plus sidecar-only orphans you can identify on a [`Self::full_file_listing`]
526 /// pass).
527 pub removed_files: &'a [RemovedFile],
528 /// `true` when the region is dropped/absent (e.g. a repartitioned source).
529 /// Context only — not authorization. `region_metadata` is `None` when `true`.
530 pub is_region_dropped: bool,
531 /// Whether this pass did a full object-store listing.
532 pub full_file_listing: bool,
533}
534
535pub type RegionHookRef = Arc<dyn RegionHook>;