Okay, the user wants a compaction/GC policy library for logs and columnar stores. Let me break down what that means. They're likely working with time-series data, event logs, or columnar databases where data accumulates over time and needs to be managed efficiently.
First, I need to clarify the scope. Compaction and GC policies apply differently to logs (like append-only streams) and columnar stores (like Parquet files). The user might be building a data infrastructure component or optimizing storage for analytics.
What are the key requirements? Probably configurability, multiple policy types, and support for different storage formats. They might need both time-based and size-based strategies. For logs, maybe segment-based compaction; for columnar stores, merging small files or dropping old partitions.
Also, the library should be reusable across systems. That means abstracting the core logic from storage-specific implementations. Need to define interfaces for policies, metrics, and triggers. The user might not have mentioned monitoring, but any production system would need metrics and alerts.
Wait, are they using this for a specific tech stack? The query doesn't specify, so I should keep it language-agnostic but provide concrete examples in common languages like Python or Java. Maybe pseudocode first, then implementations.
Potential pitfalls: Overlooking data retention vs. cost trade-offs, or not handling late-arriving data. Also, idempotency is crucial—compaction should be safe to retry.
Should I include examples for both log and columnar cases? Yes, to show applicability. Maybe a compaction scheduler and a policy evaluator. The user might also need to integrate with existing orchestration (like Airflow or Kubernetes CronJobs).
Finally, emphasize testing and observability. Without proper metrics, tuning policies is guesswork. Suggest key metrics like compaction duration, data reduction ratio, and storage savings.
I'll design a comprehensive compaction/Garbage Collection (GC) policy library that works for both log/streaming systems (like Kafka, Pulsar, or custom log stores) and columnar stores (like Parquet, ORC, or Delta/Iceberg tables). This library should be configurable, observable, and extensible.
Core Architecture
1. Policy Interface Definitions
# Core abstraction layer
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from enum import Enum
class StorageType(Enum):
LOG_SEGMENT = "log_segment" # Kafka-like segments
COLUMNAR_FILE = "columnar_file" # Parquet/ORC files
TIME_PARTITION = "time_partition" # Hive/Glue partitions
MEMORY_TABLE = "memory_table" # In-memory structures
@dataclass
class DataStats:
path: str
size_bytes: int
record_count: int
created_at: datetime
last_accessed: datetime
partition_key: Optional[str] = None
metadata: Dict[str, Any] = None
@dataclass
class CompactionDecision:
path: str
strategy: str
estimated_space_saved: int
priority: float # 0-1 scale
reason: str
needs_compaction: bool
class BasePolicy(ABC):
@abstractmethod
def evaluate(self, stats: List[DataStats],
storage_type: StorageType) -> List[CompactionDecision]:
"""Evaluate which data needs compaction/GC"""
pass
@abstractmethod
def get_config(self) -> Dict[str, Any]:
"""Return current policy configuration"""
pass
@abstractmethod
def validate_config(self, config: Dict[str, Any]) -> bool:
"""Validate policy configuration"""
pass
class CompactionExecutor(ABC):
@abstractmethod
def compact(self, paths: List[str], strategy: str) -> Dict[str, Any]:
"""Execute compaction on given paths"""
pass
@abstractmethod
def delete(self, paths: List[str]) -> Dict[str, Any]:
"""Delete data (GC for unrecoverable data)"""
pass
2. Built-in Policy Implementations
A. For Log/Streaming Systems
class LogRetentionPolicy(BasePolicy):
"""Time + size based retention for log segments"""
def __init__(self,
retention_hours: int = 168, # 7 days
segment_size_mb: int = 100,
min_compact_size_mb: int = 10,
max_compact_segments: int = 10):
self.retention_delta = timedelta(hours=retention_hours)
self.segment_size = segment_size_mb * 1024 * 1024
self.min_compact = min_compact_size_mb * 1024 * 1024
self.max_compact = max_compact_segments
def evaluate(self, stats: List[DataStats],
storage_type: StorageType) -> List[CompactionDecision]:
decisions = []
cutoff = datetime.utcnow() - self.retention_delta
# Group segments by log topic/partition
segments_by_topic = self._group_by_topic(stats)
for topic, segments in segments_by_topic.items():
# Sort by offset/time
sorted_segments = sorted(segments, key=lambda s: s.created_at)
# 1. Mark old segments for deletion
for seg in sorted_segments:
if seg.created_at < cutoff:
decisions.append(CompactionDecision(
path=seg.path,
strategy="delete",
estimated_space_saved=seg.size_bytes,
priority=1.0,
reason=f"Older than {self.retention_delta}"
))
# 2. Identify compaction candidates (small segments)
compact_candidates = [s for s in sorted_segments
if s.size_bytes < self.min_compact]
if len(compact_candidates) >= 3: # Minimum to compact
total_size = sum(s.size_bytes for s in compact_candidates[:self.max_compact])
decisions.append(CompactionDecision(
path=[c.path for c in compact_candidates[:self.max_compact]],
strategy="log_merge",
estimated_space_saved=total_size * 0.3, # Estimate 30% savings
priority=0.7,
reason=f"Merge {len(compact_candidates)} small segments"
))
return decisions
def _group_by_topic(self, stats: List[DataStats]) -> Dict[str, List[DataStats]]:
groups = {}
for stat in stats:
# Extract topic from path (e.g., /logs/topic1/partition_0/segment_1.log)
topic = stat.path.split('/')[1] if len(stat.path.split('/')) > 1 else "default"
groups.setdefault(topic, []).append(stat)
return groups
class LogSequenceNumberPolicy(BasePolicy):
"""For systems with sequence numbers (like Kafka offsets)"""
def __init__(self,
retain_sequences: bool = True,
gap_threshold: int = 1000,
min_sequence_gap: int = 100):
self.retain_sequences = retain_sequences
self.gap_threshold = gap_threshold
self.min_gap = min_sequence_gap
def evaluate(self, stats: List[DataStats],
storage_type: StorageType) -> List[CompactionDecision]:
if not self.retain_sequences:
return []
decisions = []
# Logic to find sequence gaps and compact sparse segments
# Implementation depends on specific sequence numbering scheme
return decisions
B. For Columnar Stores
class ColumnarPartitionPolicy(BasePolicy):
"""Time-based partition management for columnar stores"""
def __init__(self,
hot_partitions_days: int = 7,
warm_partitions_months: int = 3,
cold_partitions_years: int = 2,
small_file_threshold_mb: int = 10,
merge_threshold_files: int = 10):
self.hot = timedelta(days=hot_partitions_days)
self.warm = timedelta(days=warm_partitions_months * 30)
self.cold = timedelta(days=cold_partitions_years * 365)
self.small_file = small_file_threshold_mb * 1024 * 1024
self.merge_threshold = merge_threshold_files
def evaluate(self, stats: List[DataStats],
storage_type: StorageType) -> List[CompactionDecision]:
decisions = []
now = datetime.utcnow()
# Group by partition
partitions = {}
for stat in stats:
part_key = stat.partition_key or self._extract_partition(stat.path)
partitions.setdefault(part_key, []).append(stat)
for partition, files in partitions.items():
# Determine partition age from partition key (assumes YYYY/MM/DD format)
partition_date = self._parse_partition_date(partition)
partition_age = now - partition_date
# Tiered strategy based on age
if partition_age > self.cold:
# Cold partitions: aggressive compaction + file merging
small_files = [f for f in files if f.size_bytes < self.small_file]
if len(small_files) >= self.merge_threshold:
decisions.append(CompactionDecision(
path=[f.path for f in small_files],
strategy="merge_partition_files",
estimated_space_saved=sum(f.size_bytes for f in small_files) * 0.2,
priority=0.9,
reason=f"Cold partition {partition}: merge {len(small_files)} small files"
))
elif partition_age > self.warm:
# Warm: moderate file merging
decisions.extend(self._warm_policy(files, partition))
else:
# Hot: minimal compaction, focus on delta merges
decisions.extend(self._hot_policy(files, partition))
return decisions
def _extract_partition(self, path: str) -> str:
"""Extract partition from path like /table/date=2024-01-01/file.parquet"""
parts = path.split('/')
for part in parts:
if '=' in part:
return part.split('=')[1]
return "default"
def _parse_partition_date(self, partition: str) -> datetime:
"""Parse partition string to datetime (YYYY-MM-DD format)"""
try:
return datetime.strptime(partition, "%Y-%m-%d")
except:
return datetime.utcnow() - timedelta(days=365)
class ColumnarFileSizePolicy(BasePolicy):
"""Compact small files based on size/count thresholds"""
def __init__(self,
target_file_size_mb: int = 128,
max_files_per_compact: int = 100,
min_files_to_compact: int = 5):
self.target_size = target_file_size_mb * 1024 * 1024
self.max_files = max_files_per_compact
self.min_files = min_files_to_compact
def evaluate(self, stats: List[DataStats],
storage_type: StorageType) -> List[CompactionDecision]:
decisions = []
# Sort by size
sorted_files = sorted(stats, key=lambda s: s.size_bytes)
# Find clusters of small files in same directory
dir_groups = {}
for file in sorted_files:
if file.size_bytes < self.target_size * 0.5: # Less than 50% of target
dir_name = '/'.join(file.path.split('/')[:-1])
dir_groups.setdefault(dir_name, []).append(file)
for dir_path, files in dir_groups.items():
if len(files) >= self.min_files:
total_size = sum(f.size_bytes for f in files[:self.max_files])
decisions.append(CompactionDecision(
path=[f.path for f in files[:self.max_files]],
strategy="file_merge",
estimated_space_saved=total_size * 0.3, # Headers/metadata overhead
priority=0.6,
reason=f"Merge {len(files)} small files in {dir_path}"
))
return decisions
class ColumnarVersionCleanupPolicy(BasePolicy):
"""For tables with versioning (Delta Lake, Iceberg)"""
def __init__(self,
keep_latest_versions: int = 10,
expire_older_than_days: int = 30,
soft_delete_retention_days: int = 7):
self.keep_latest = keep_latest_versions
self.expire_threshold = timedelta(days=expire_older_than_days)
self.soft_delete_retention = timedelta(days=soft_delete_retention_days)
def evaluate(self, stats: List[DataStats],
storage_type: StorageType) -> List[CompactionDecision]:
decisions = []
# Group by table
tables = {}
for stat in stats:
table_name = stat.path.split('/')[0] # Assuming /table/version/ format
tables.setdefault(table_name, []).append(stat)
for table, versions in tables.items():
sorted_versions = sorted(versions, key=lambda s: s.created_at, reverse=True)
# Keep latest N versions
versions_to_keep = sorted_versions[:self.keep_latest]
versions_to_expire = sorted_versions[self.keep_latest:]
for version in versions_to_expire:
age = datetime.utcnow() - version.created_at
if age > self.expire_threshold:
decisions.append(CompactionDecision(
path=version.path,
strategy="expire_version",
estimated_space_saved=version.size_bytes,
priority=0.8,
reason=f"Expire old version {version.path}"
))
return decisions
3. Composite/Chained Policies
class PolicyChain(BasePolicy):
"""Combine multiple policies with weighted scoring"""
def __init__(self, policies: List[BasePolicy], weights: List[float] = None):
self.policies = policies
self.weights = weights or [1.0] * len(policies)
def evaluate(self, stats: List[DataStats],
storage_type: StorageType) -> List[CompactionDecision]:
all_decisions = []
for policy, weight in zip(self.policies, self.weights):
decisions = policy.evaluate(stats, storage_type)
for d in decisions:
d.priority *= weight # Adjust priority by weight
all_decisions.extend(decisions)
# Deduplicate by path, taking highest priority
return self._deduplicate_decisions(all_decisions)
def _deduplicate_decisions(self, decisions: List[CompactionDecision]) -> List[CompactionDecision]:
best = {}
for d in decisions:
paths = d.path if isinstance(d.path, list) else [d.path]
for path in paths:
if path not in best or d.priority > best[path].priority:
best[path] = d
return list(best.values())
4. Scheduler & Executor
class CompactionScheduler:
"""Schedule and execute compaction jobs"""
def __init__(self,
policy: BasePolicy,
executor: CompactionExecutor,
max_concurrent: int = 3,
dry_run: bool = False):
self.policy = policy
self.executor = executor
self.max_concurrent = max_concurrent
self.dry_run = dry_run
self.running_jobs = {}
def run_cycle(self, stats_provider: callable,
storage_type: StorageType) -> Dict[str, Any]:
"""Run single compaction cycle"""
# 1. Collect stats
stats = stats_provider()
# 2. Evaluate policies
decisions = self.policy.evaluate(stats, storage_type)
# 3. Sort by priority
decisions.sort(key=lambda d: d.priority, reverse=True)
# 4. Execute (respecting concurrency limits)
results = []
for decision in decisions:
if len(self.running_jobs) >= self.max_concurrent:
break
if self.dry_run:
results.append({
"path": decision.path,
"strategy": decision.strategy,
"would_run": True,
"estimated_savings": decision.estimated_space_saved
})
else:
try:
result = self.executor.compact(
decision.path if isinstance(decision.path, list) else [decision.path],
decision.strategy
)
results.append(result)
except Exception as e:
results.append({
"path": decision.path,
"error": str(e)
})
return {
"cycle_id": datetime.utcnow().isoformat(),
"decisions_evaluated": len(decisions),
"executed": len([r for r in results if "error" not in r]),
"results": results,
"total_estimated_savings": sum(d.estimated_space_saved for d in decisions)
}
5. Configuration Examples
# config/compaction_policies.yaml
policies:
# For Kafka-like logs
log_streaming:
type: "log_retention"
retention_hours: 168
segment_size_mb: 100
min_compact_size_mb: 10
max_compact_segments: 20
# For Parquet data lake
parquet_lake:
type: "policy_chain"
policies:
- type: "partition_age"
hot_days: 7
warm_days: 90
cold_days: 730
- type: "file_size"
target_size_mb: 128
min_files: 5
- type: "version_cleanup"
keep_versions: 10
expire_days: 30
# For Delta Lake
delta_table:
type: "delta_specific"
vacuum_retention_hours: 168
optimize_file_size_mb: 256
max_file_age_days: 365
6. Metrics & Monitoring
class CompactionMetrics:
"""Prometheus-style metrics collector"""
def __init__(self):
self.metrics = {
"compaction_cycles_total": 0,
"compaction_files_processed": 0,
"compaction_bytes_saved": 0,
"compaction_duration_seconds": 0,
"compaction_errors_total": 0,
"storage_bytes_total": 0,
"file_count_total": 0
}
def record_cycle(self, cycle_result: Dict[str, Any], duration: float):
self.metrics["compaction_cycles_total"] += 1
self.metrics["compaction_files_processed"] += cycle_result["executed"]
self.metrics["compaction_bytes_saved"] += cycle_result["total_estimated_savings"]
self.metrics["compaction_duration_seconds"] += duration
def get_prometheus_format(self) -> str:
"""Export metrics in Prometheus text format"""
lines = []
for key, value in self.metrics.items():
lines.append(f"{key} {value}")
return '\n'.join(lines)
7. Storage-Specific Executors
class ParquetCompactionExecutor(CompactionExecutor):
"""Compaction for Parquet files"""
def compact(self, paths: List[str], strategy: str) -> Dict[str, Any]:
if strategy == "file_merge":
return self._merge_parquet_files(paths)
elif strategy == "merge_partition_files":
return self._optimize_partition(paths)
else:
raise ValueError(f"Unknown strategy: {strategy}")
def _merge_parquet_files(self, paths: List[str]) -> Dict[str, Any]:
# Use Spark/DuckDB/Polars to rewrite files
# Implementation depends on execution engine
return {
"paths_processed": len(paths),
"new_files_created": 1,
"bytes_written": sum(os.path.getsize(p) for p in paths) * 0.7
}
def delete(self, paths: List[str]) -> Dict[str, Any]:
# For cold data deletion
total_size = sum(os.path.getsize(p) for p in paths)
for p in paths:
os.remove(p) # In production, move to trash first
return {"deleted_paths": len(paths), "bytes_freed": total_size}
class LogSegmentExecutor(CompactionExecutor):
"""For Kafka/Pulsar like log segments"""
def compact(self, paths: List[str], strategy: str) -> Dict[str, Any]:
if strategy == "log_merge":
return self._merge_log_segments(paths)
elif strategy == "delete":
return self.delete(paths)
else:
raise ValueError(f"Unknown strategy: {strategy}")
def _merge_log_segments(self, paths: List[str]) -> Dict[str, Any]:
# Read all segments, rewrite into new segment
# Update index files
return {
"segments_merged": len(paths),
"new_segment_size": sum(os.path.getsize(p) for p in paths) * 0.8
}
8. Usage Example
# Example usage
def main():
# 1. Configure policy
policy = PolicyChain([
ColumnarPartitionPolicy(
hot_partitions_days=7,
warm_partitions_months=3,
cold_partitions_years=2
),
ColumnarFileSizePolicy(
target_file_size_mb=128,
min_files_to_compact=5
)
], weights=[0.7, 0.3])
# 2. Configure executor
executor = ParquetCompactionExecutor()
# 3. Create scheduler
scheduler = CompactionScheduler(
policy=policy,
executor=executor,
max_concurrent=2,
dry_run=False
)
# 4. Define stats collector
def collect_stats():
# Scan storage, return DataStats list
# Implementation depends on storage system
return scan_parquet_table("/data/analytics")
# 5. Run compaction cycle
result = scheduler.run_cycle(collect_stats, StorageType.COLUMNAR_FILE)
print(f"Processed {result['executed']} files")
print(f"Estimated savings: {result['total_estimated_savings'] / 1024**3:.2f} GB")
# 6. Emit metrics
metrics = CompactionMetrics()
metrics.record_cycle(result, duration=120.5)
print(metrics.get_prometheus_format())
if __name__ == "__main__":
main()
Key Features of This Library:
- Storage-Agnostic Core: Same policy logic for logs and columnar stores
- Extensible: Easy to add new policy types or storage adapters
- Tiered Strategies: Hot/warm/cold data handling
- Observable: Built-in metrics and dry-run mode
- Safe: Priority-based, configurable concurrency, error handling
- Production-Ready: Config validation, metrics, idempotent operations
Implementation Notes:
-
For Production Use:
- Add proper error handling and retry logic
- Implement distributed locks for concurrent schedulers
- Add audit logging of all compaction/GC operations
- Include rollback capability for failed compactions
- Add quota/throttling to limit impact on production workloads
-
Storage Integrations:
- Kafka: Use
kafka-log-dir-scan-tool or custom segment scanner
- Spark/Databricks: Use
OPTIMIZE and VACUUM commands
- Hive/Glue: Partition metadata scanning
- Custom Logs: Filesystem walk with metadata extraction
-
Advanced Features (optional):
- Machine learning based predictive compaction
- Cost-based optimization (considering query patterns)
- Cross-table compaction coordination
- Compaction budgeting (rate limiting)
- SLA-based guarantees
This library provides the foundation; specific integrations would need implementation for your storage systems and orchestration framework (Airflow, Prefect, Kubernetes CronJobs, etc.).