The user wants a library for compaction and garbage collection (GC) policies for logs and columnar stores.
This is a broad request. I need to define the scope, architecture, and key components.
1. Understand the Context:
- Logs: Append-only sequences (WAL, CommitLog). Compaction usually means removing old segments or merging them to reclaim space (e.g., in Kafka or a local log).
- Columnar Stores: Often immutable files (like Parquet/ORC in data lakes) or LSM-tree based (like ClickHouse, Parquet in Delta Lake/Iceberg). Compaction here involves rewriting files to handle small files, prune deleted rows, or change sorting order.
2. Key Requirements for a Library:
- Abstraction: It shouldn't be tied to a specific storage engine (like RocksDB or a specific file system). It should provide policies and metadata management, not necessarily the I/O execution (though it needs to trigger it).
- Flexibility: Support different strategies (Size-Tiered, Time-Window, Leveled, Cost-Benefit).
- Observability: Metrics, logging.
- Scheduling: Asynchronous execution, rate limiting.
3. High-Level Architecture:
- Metadata Store (Interface): The library needs to know what files exist, their sizes, and timestamps.
- File Proxy (Interface): Represents a file or segment. Needs stats (size, creation time, tombstone count).
- Policy Engine: The brain. Takes current state -> returns a plan.
- Executor: Performs the I/O (Read -> Merge/Compact -> Write).
4. Designing the Policies:
5. Drafting the Code Structure (Python/TypeScript/Pseudo-code):
I'll use Python for clarity and readability, using Abstract Base Classes (ABCs) to define the interfaces. This makes it a "library" in the conceptual sense.
- Core Classes:
FileMetadata, CompactionPlan, Compactor.
- Policies:
LogRetentionPolicy
SizeTieredPolicy (LSM style)
CostBenefitPolicy (looking at read/write amplification)
6. Refining the "Columnar" aspect:
Columnar stores often deal with delete vectors or tombstones. A GC policy for columnar stores needs to look at the ratio of deleted rows to valid rows.
- Constraint: If
tombstone_ratio > threshold, compact.
7. Structuring the Response:
- Introduction: Define the goals (write amplification vs. space amplification vs. read amplification).
- Architecture Diagram (Textual): How pieces fit.
- Core Interfaces: The API contracts.
- Implemented Policies:
- Policy 1: Time-to-Live (TTL) / Retention (Logs).
- Policy 2: Size-Tiered (Columnar/LSM).
- Policy 3: Cost-Benefit (Columnar - maintenance).
- The Engine/Runner: How to schedule these.
- Example Usage: Putting it together.
Self-Correction/Refinement during drafting:
- Initial thought: Should I implement the actual file merging logic?
- Correction: No, that's too low-level and depends on the file format (Parquet vs Avro vs Binary). The library should output a Plan (e.g., "Merge [A, B, C] into D"). The user provides the implementation of "Merge".
Code details to include:
- Enums for Strategy.
- Dataclasses for
FileDescriptor.
- Logic for
select_files().
8. Final Polish:
Make the code clean, type-hinted, and modular. Add comments explaining why certain logic exists (e.g., why size-tiered works well for write-heavy workloads).
Let's write the code.
-
File Metadata: needs path, size_bytes, creation_time, tombstone_count (for columnar GC).
-
Policy Interface: get_compaction_candidates(all_files) -> list[CompactionJob].
-
Specific Policy Logic:
- Log Retention: Simple filter by time.
- Log Dedupe: Keep latest keys (simplified simulation).
- Columnar (Size Tiered): Bucket files by size, pick bucket if > N files.
9. The "Library" feel:
Use a module structure in the explanation.
compaction_lib/policies.py, compaction_lib/core.py.
Let's build it.
Building a compaction and garbage collection (GC) library requires balancing three competing factors: Write Amplification (how much data is rewritten), Space Amplification (how much stale/deleted data exists), and Read Amplification (how many files need to be read to satisfy a query).
Below is a design and Python implementation for a modular Storage Maintenance Library. It is designed to be storage-engine agnostic (working for both Logs/SSTables and Columnar formats like Parquet/ORC).
1. Architectural Concepts
The library is built around three abstractions:
StoreFile: Represents a file on disk (contains metadata like size, age, and tombstone ratio).
PlanStrategy: The logic that selects which files to compact (The "Policy").
MaintenanceExecutor: The orchestrator that runs the policies and simulates the file system operations.
2. The Library Code
import os
import time
import logging
from dataclasses import dataclass, field
from typing import List, Optional, Protocol, Tuple
from enum import Enum, auto
from collections import defaultdict
# --- 1. Domain Models ---
class FileType(Enum):
LOG = auto() # Append-only, unsorted
COLUMNAR = auto() # Sorted, compressed (e.g., Parquet)
@dataclass
class StoreFile:
"""
Represents a physical file in the storage engine.
"""
path: str
size_bytes: int
created_at: float # Epoch timestamp
file_type: FileType
# Metadata for GC/Compaction heuristics
tombstone_ratio: float = 0.0 # 0.0 to 1.0 (percentage of deleted data)
min_key: str = ""
max_key: str = ""
@property
def age_hours(self) -> float:
return (time.time() - self.created_at) / 3600
@property
def valid_size(self) -> int:
"""Actual data size excluding tombstones."""
return int(self.size_bytes * (1 - self.tombstone_ratio))
@dataclass
class CompactionPlan:
"""
A plan generated by a Strategy to be executed.
"""
files_to_compact: List[StoreFile]
target_output_size: int
reason: str
# --- 2. Policies (The Strategy Pattern) ---
class CompactionStrategy(Protocol):
def select_candidates(self, files: List[StoreFile]) -> Optional[CompactionPlan]:
...
class LogRetentionStrategy:
"""
Standard Log Rotation / TTL Policy.
Good for: Write Ahead Logs (WAL), Commit Logs.
Policy: Delete files older than X hours OR if total size exceeds limit.
"""
def __init__(self, max_age_hours: float = 24, max_total_size_gb: float = 100):
self.max_age_hours = max_age_hours
self.max_total_size = max_total_size_gb * 1024**3
def select_candidates(self, files: List[StoreFile]) -> Optional[CompactionPlan]:
# Filter for expired files (GC)
expired = [f for f in files if f.age_hours > self.max_age_hours]
# Filter for size overflow (Oldest files first to clear space)
current_size = sum(f.size_bytes for f in files)
overflow_files = []
if current_size > self.max_total_size:
# Sort oldest first
sorted_files = sorted(files, key=lambda f: f.created_at)
running_size = current_size
for f in sorted_files:
if running_size <= self.max_total_size:
break
overflow_files.append(f)
running_size -= f.size_bytes
targets = list(set(expired + overflow_files))
if targets:
return CompactionPlan(
files_to_compact=targets,
target_output_size=0, # 0 implies deletion
reason=f"Log Retention: {len(targets)} files expired or over quota."
)
return None
class SizeTieredCompactionStrategy:
"""
Classic LSM-Tree / Columnar Strategy.
Good for: High throughput writes, reducing file counts.
Policy: Merge files of similar size into larger files.
"""
def __init__(self, min_file_count: int = 4, max_file_size: int = 128 * 1024**2):
self.min_file_count = min_file_count
self.max_file_size = max_file_size
def select_candidates(self, files: List[StoreFile]) -> Optional[CompactionPlan]:
# Group by rough size (power of 2 buckets)
buckets = defaultdict(list)
for f in files:
# Bucket by size: 0-1MB, 1-2MB, 2-4MB, etc.
if f.size_bytes == 0: continue
bucket_idx = int(f.size_bytes).bit_length()
buckets[bucket_idx].append(f)
best_bucket = None
for bucket in buckets.values():
# Sort by creation time to merge adjacent files usually
bucket.sort(key=lambda f: f.created_at)
if len(bucket) >= self.min_file_count:
if best_bucket is None or len(bucket) > len(best_bucket):
best_bucket = bucket
if best_bucket:
return CompactionPlan(
files_to_compact=best_bucket[:self.min_file_count],
target_output_size=self.max_file_size,
reason=f"Size Tiered: Merging {len(best_bucket[:self.min_file_count])} similar sized files."
)
return None
class CostBenefitStrategy:
"""
Advanced Strategy (Similar to RocksDB Leveled or Tiered-Leveled).
Good for: Columnar stores (Parquet), optimizing read performance.
Policy: Pick files that have the highest "benefit" (tombstone cleanup)
or reduce file count significantly.
"""
def __init__(self, tombstone_threshold: float = 0.2, read_amp_threshold: int = 10):
self.tombstone_threshold = tombstone_threshold
self.read_amp_threshold = read_amp_threshold
def select_candidates(self, files: List[StoreFile]) -> Optional[CompactionPlan]:
# 1. Check for Garbage Collection (High Tombstone Ratio)
gc_candidates = [
f for f in files
if f.tombstone_ratio > self.tombstone_threshold
]
if gc_candidates:
# Sort by highest garbage ratio
gc_candidates.sort(key=lambda f: f.tombstone_ratio, reverse=True)
return CompactionPlan(
files_to_compact=gc_candidates[:4], # Compact top 4 worst files
target_output_size=128 * 1024**2,
reason=f"Garbage Collection: Reclaiming space from {len(gc_candidates[:4])} files."
)
# 2. Check for Read Amplification (Too many small files)
# (Logic to merge smallest files to improve columnar scan speed)
if len(files) > self.read_amp_threshold:
smallest_files = sorted(files, key=lambda f: f.size_bytes)[:4]
return CompactionPlan(
files_to_compact=smallest_files,
target_output_size=128 * 1024**2,
reason=f"Read Optimization: Reducing file count."
)
return None
# --- 3. The Engine ---
class CompactionEngine:
def __init__(self, store_path: str):
self.store_path = store_path
self.current_files: List[StoreFile] = []
self.strategies: List[CompactionStrategy] = []
self.logger = logging.getLogger("CompactionEngine")
def register_strategy(self, strategy: CompactionStrategy):
self.strategies.append(strategy)
def snapshot_filesystem(self):
"""
In a real implementation, this would read the manifest/file directory.
Here we simulate loading files.
"""
# Mock implementation for demonstration
pass
def run_maintenance_cycle(self):
self.logger.info(f"--- Starting Maintenance Cycle on {self.store_path} ---")
# In a real system, we would refresh the file list here
# self.snapshot_filesystem()
for strategy in self.strategies:
plan = strategy.select_candidates(self.current_files)
if plan:
self._execute_plan(plan)
break # Execute one plan per cycle to avoid resource contention
self.logger.info("--- Cycle Complete ---\n")
def _execute_plan(self, plan: CompactionPlan):
self.logger.info(f"ACTION: {plan.reason}")
if plan.target_output_size == 0:
# Simulate Deletion (Log Retention / Expiration)
for f in plan.files_to_compact:
self.logger.info(f" - Deleting {f.path}")
self.current_files.remove(f)
else:
# Simulate Compaction (Merge Read + Rewrite)
total_input_size = sum(f.size_bytes for f in plan.files_to_compact)
# Create new merged file
new_file = StoreFile(
path=f"{self.store_path}/compacted_{time.time()}.parquet",
size_bytes=total_input_size, # Assume 1:1 copy for sim
created_at=time.time(),
file_type=FileType.COLUMNAR,
tombstone_ratio=0.0 # Compaction cleans tombstones
)
self.logger.info(f" - Merging {len(plan.files_to_compact)} files ({total_input_size / 1024**2:.2f} MB)")
self.logger.info(f" + Creating {new_file.path}")
# Update state
for f in plan.files_to_compact:
self.current_files.remove(f)
self.current_files.append(new_file)
3. Usage Demonstration
Here is how you would use this library in a simulation of a storage system running over time.
import time
import random
def setup_logging():
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%H:%M:%S')
def simulate_system():
setup_logging()
# Initialize Engine
engine = CompactionEngine(store_path="/data/columns")
# Register Policies (Order matters: usually GC/Expiration first, then Tuning)
engine.register_strategy(LogRetentionStrategy(max_age_hours=0.01, max_total_size_gb=0.001)) # Aggressive for demo
engine.register_strategy(CostBenefitStrategy(tombstone_threshold=0.3))
engine.register_strategy(SizeTieredCompactionStrategy(min_file_count=3))
# 1. Simulate writing some initial files (Logs & Columnar)
print("1. Writing initial batch of files...")
for i in range(5):
f = StoreFile(
path=f"/data/columns/file_{i}.parquet",
size_bytes=random.randint(10, 50) * 1024**2,
created_at=time.time() - random.randint(100, 500), # Some are old
file_type=FileType.COLUMNAR
)
engine.current_files.append(f)
# 2. Simulate a file with lots of deletes (Tombstones)
print("2. Creating a file requiring GC (30% deleted)...")
gc_file = StoreFile(
path="/data/columns/file_stale.parquet",
size_bytes=100 * 1024**2,
created_at=time.time(),
file_type=FileType.COLUMNAR,
tombstone_ratio=0.4 # 40% garbage
)
engine.current_files.append(gc_file)
# 3. Run Cycle 1 -> Should trigger CostBenefit (GC) to remove tombstones
engine.run_maintenance_cycle()
# 4. Simulate time passing (making files old)
print("3. Simulating passage of time...")
for f in engine.current_files:
f.created_at -= 3600 * 10 # Make files 10 hours older
# 5. Run Cycle 2 -> Should trigger LogRetention (Deletion)
engine.run_maintenance_cycle()
if __name__ == "__main__":
simulate_system()
4. Implementation Details for Production
To move this from a library to a production system, you would need to implement the following:
- The Manifest Interface: The
StoreFile dataclass relies on data. In production, you need an interface to your specific metadata store (e.g., a SQLite DB for generic logs, or the _metadata delta log for Delta Lake, or Zookeeper/Consul).
- Read/Write Locks: Compaction is "stop-the-world" for the specific files being compacted. You need a lock manager to ensure queries aren't trying to read a file while the compactor is deleting it.
- Concurrency Strategies:
- Copy-on-Write (CoW): Create new file, swap pointer in manifest atomically (used by Parquet/Iceberg).
- Level Compaction: Background threads merging levels without locking the whole store.
- Stats Collection: The
StoreFile needs accurate tombstone_ratio.
- For Logs: This is usually implicit (the log cleaner reads the log and checks if the transaction is committed in the main DB).
- For Columnar: You usually calculate this when reading metadata (e.g., Parquet stores
num_rows and num_nulls, or you have a separate delete vector file).