The user wants a "parallel data migration toolkit" with specific features:
- Parallelism: It must use multiple threads/processes to move data faster.
- Consistency Proofs: It needs a way to ensure the source and destination data match conceptually (often via checksums).
- Checksum Validation: Explicit verification of data integrity.
- Runtime Throttling: The ability to slow down if the system is under load.
- Abort Triggers: Mechanisms to stop the process if specific error conditions are met.
Target Audience/Language: Python is the best fit for this kind of utility. It has great libraries for threading, hashing, and system monitoring. Go would be a strong second choice, but Python is generally more accessible for "script/toolkit" style requests. I'll stick with Python.
Architecture Design:
- Core Component: The Migrator.
- Needs a source and destination interface (abstracted).
- Needs a queue of "tasks" (chunks of data to move).
- Needs a pool of workers.
- Consistency/Checksums:
- The unit of work should be a "Chunk".
- Process: Read Chunk -> Calculate Source Hash -> Write to Destination -> Read back (or calculate during write) -> Calculate Destination Hash -> Compare.
- Cryptographic hash: SHA-256 or MD5 (MD5 is faster for less security-critical stuff, but SHA-256 is standard). Let's go with SHA-256 for robustness.
- Throttling:
- How to measure load? CPU usage, Memory usage, or IOPS.
- Let's use a simple feedback loop. If the "lag" increases or system metrics exceed a threshold, sleep.
- For simplicity in a code example, I'll implement a "Token Bucket" or a dynamic sleep mechanism based on iteration time. actually, a resource monitor thread is better.
- Abort Triggers:
- Global flag or Exception based.
- Conditions: Too many errors, Checksum mismatch, Manual interrupt.
Implementation Details (Python):
- Concurrency:
concurrent.futures.ThreadPoolExecutor.
- Data Source/Sink: Mocking file operations or using
io.BytesIO for demonstration, but writing it to handle file paths makes it usable. Let's assume migrating files from one directory to another, as that's a concrete use case.
- Checksum:
hashlib.
- Throttling: A "Governor" class that monitors a rate limit (bytes/sec) or system load (psutil is great, but standard lib is better for portability). Let's stick to a configurable rate limit (bytes/sec) to keep it self-contained, or a simple adaptive delay. I will implement a Token Bucket for bandwidth throttling.
- Abort: A threading Event
stop_event.
Code Structure:
DataChunk: Represents the unit being moved.
MigrationTask: The logic for moving a single chunk.
Toolkit: The main controller handling the worker pool.
Governor: Handles throttling.
Validator: Handles checksums.
Refining the "Consistency Proof":
Usually, this means mathematical proof. In a migration context, it means verifying that H(Source)=H(Destination). I will log this verification as a "Proof Log".
Drafting the Code (Mental or Scratchpad):
class MigrationToolkit:
def __init__(self, src, dst, ...):
self.stop_event = threading.Event()
self.error_count = 0
self.max_errors = 5
def worker(self, item):
if self.stop_event.is_set(): return
# Throttle
self.governor.wait(bytes_size)
# Migrate
# Validate
if not valid:
self.abort("Checksum mismatch")
Adding "Parallelism" Nuance:
Reading from a single file in parallel is complex (seek locks). Migrating multiple files in parallel is easier. Let's frame this as a "Directory Migration Toolkit".
Throttling Implementation:
I'll implement a ThrottleController that measures the time taken vs bytes processed and inserts time.sleep to maintain a target MB/s rate.
Abort Triggers:
- Cumulative Error Threshold (e.g., if 5 files fail, stop everything).
- Hard Checksum Failure.
- External Signal (KeyboardInterrupt handled gracefully).
Polishing:
I need to make this code runnable and illustrative. I will create a synthetic data generator to make it "plug and play" for the user to test.
Feature Checklist & Implementation Plan:
- Parallel Engine:
ThreadPoolExecutor.
- Consistency/Checksum:
hashlib.sha256. Pre-calc source hash -> Copy -> Post-calc dest hash -> Compare.
- Throttling: A shared
RateLimiter object used by threads.
- Abort:
threading.Event. If a critical error occurs, set event, threads finish current tiny task and exit.
Let's write the actual code.
Self-Correction during coding:
Copying large files entirely into memory is bad. I should read in chunks (blocks).
Strategy:
Actually, to keep the complexity manageable for a single script, I'll define a Task as a file.
Inside the task:
- Calculate Source Hash (streaming).
- Copy file to Dest.
- Calculate Dest Hash (streaming read during copy or post-copy).
Wait, if I copy first, then check, I need to read the file twice. That's standard for validation.
To optimize: Calculate source hash. Open dest. Read source buffer, write dest buffer, update dest hash context. No, that hashes the write, not the actual data on disk (which might be cached). A strict validation reads back from disk.
Let's do: Copy -> Read Dest for Hash -> Compare with Source Hash.
Throttling logic:
A global limiter.acquire(bytes_processed).
The Output:
A clean Python script with comments explaining the "Proofs" and "Triggers".
Let's structure the response:
- Overview of the architecture.
- The Python Code.
- Explanation of the specific components (Throttling, Proofs, Abort).
Refining the Abort Trigger:
I'll add a HealthMonitor that checks system resources (optional, but cool) or just error rates. Let's stick to Error Rate limits for the abort trigger to ensure it runs everywhere without extra deps like psutil.
Let's build it.
- Class
ParallelMigrator: Main entry.
- Class
TransferJob: Represents a file.
- Class
Governor: Token bucket for bandwidth.
- Function
migrate_item: The worker function.
I will add dummy file creation at the end so the user can run it immediately to see it work.
(Self-Correction): The user asked for "Consistency Proofs". A simple boolean check is weak. I should output a "manifest" or log structure that serves as the proof. I'll create a migration_report.json.
Let's finalize the abort trigger logic:
If checksum_mismatch: ABORT IMMEDIATE (Data integrity is paramount).
If os_error: Log and continue (or increment error counter).
If error_counter > threshold: ABORT (Systemic failure).
Okay, ready to generate.
Here is a complete, standalone Python implementation of a Parallel Data Migration Toolkit. This tool is designed to move files from a source to a destination using a thread pool, featuring cryptographic verification, bandwidth throttling, and fault tolerance.
Architecture Overview
- Parallel Engine: Uses
concurrent.futures.ThreadPoolExecutor to migrate multiple files simultaneously.
- Consistency Proof (SHA-256): Ensures bit-perfect copies. It hashes the source file, copies the data, and hashes the result on the disk (not just the memory buffer) to guarantee the destination matches the source.
- Runtime Throttling: A Token Bucket Limiter controls the throughput (MB/s) to prevent network or disk saturation.
- Abort Triggers:
- Global Stop: If critical errors exceed a threshold, the entire operation halts.
- Hard Stop: Immediate termination on data corruption detection (checksum mismatch).
The Toolkit Code
import os
import shutil
import hashlib
import time
import threading
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict, Tuple, Optional
from dataclasses import dataclass, field
# ==========================================
# 1. Data Structures & Configuration
# ==========================================
@dataclass
class MigrationConfig:
source_dir: str
dest_dir: str
max_workers: int = 4
throttle_mbps: int = 0 # 0 = Unlimited
abort_on_error: bool = True
max_retries: int = 3
@dataclass
class TaskResult:
source_path: str
dest_path: str
success: bool
source_hash: str = None
dest_hash: str = None
size_bytes: int = 0
duration: float = 0.0
error: str = None
# ==========================================
# 2. Components
# ==========================================
class ThrottleController:
"""
A Token Bucket implementation to limit bandwidth.
"""
def __init__(self, rate_mbps: int):
self.rate_mbps = rate_mbps
self.lock = threading.Lock()
self.tokens = 0.0
self.last_update = time.time()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def consume(self, bytes_requested: int):
if self.rate_mbps <= 0:
return # Unlimited
while not self._stop_event.is_set():
with self.lock:
now = time.time()
elapsed = now - self.last_update
self.last_update = now
# Add tokens based on elapsed time (Rate in Bytes/s)
self.tokens += elapsed * (self.rate_mbps * 1024 * 1024)
# Cap tokens (simple burst allowance)
if self.tokens > (self.rate_mbps * 1024 * 1024):
self.tokens = self.rate_mbps * 1024 * 1024
if self.tokens >= bytes_requested:
self.tokens -= bytes_requested
return
# Wait if not enough tokens
time.sleep(0.01)
class AbortTrigger:
"""
Global abort controller.
Triggers if corruption is found or error threshold is exceeded.
"""
def __init__(self, threshold: int = 5):
self._stop_event = threading.Event()
self.error_count = 0
self.threshold = threshold
self.lock = threading.Lock()
def stop(self):
self._stop_event.set()
def is_triggered(self) -> bool:
return self._stop_event.is_set()
def register_error(self, is_critical: bool = False):
with self.lock:
if is_critical:
print("[CRITICAL] Data corruption detected. Triggering immediate abort.")
self.stop()
return
self.error_count += 1
if self.error_count >= self.threshold:
print(f"[ABORT] Error threshold ({self.threshold}) reached. Halting migration.")
self.stop()
# ==========================================
# 3. Core Logic
# ==========================================
class MigrationWorker:
@staticmethod
def _hash_file(filepath: str) -> str:
"""Generates SHA-256 hash of a file."""
sha256 = hashlib.sha256()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256.update(chunk)
return sha256.hexdigest()
@staticmethod
def migrate_file(
src: str,
dst: str,
throttle: ThrottleController,
aborter: AbortTrigger
) -> TaskResult:
start_time = time.time()
result = TaskResult(source_path=src, dest_path=dst, success=False)
try:
# 1. Abort Check
if aborter.is_triggered():
result.error = "Migration aborted by trigger."
return result
# 2. Pre-Calculation: Source Hash
# Note: In a high-speed LAN, hashing might be slower than copying.
# We do it here for strict consistency proofs.
source_hash = MigrationWorker._hash_file(src)
result.source_hash = source_hash
result.size_bytes = os.path.getsize(src)
# 3. Throttled Copy
# We copy chunk by chunk to respect the throttle controller
os.makedirs(os.path.dirname(dst), exist_ok=True)
with open(src, 'rb') as f_src, open(dst, 'wb') as f_dst:
while True:
if aborter.is_triggered():
raise InterruptedError("Migration aborted during transfer.")
# Read chunk
chunk = f_src.read(1024 * 1024) # 1MB chunks
if not chunk:
break
# Request bandwidth token
throttle.consume(len(chunk))
# Write chunk
f_dst.write(chunk)
# 4. Consistency Proof (Destination Checksum)
# We verify the file actually written to disk matches the source hash
dest_hash = MigrationWorker._hash_file(dst)
result.dest_hash = dest_hash
if source_hash != dest_hash:
# CRITICAL FAILURE: Data Corruption
aborter.register_error(is_critical=True)
raise IOError(f"Checksum Mismatch: Source {source_hash} vs Dest {dest_hash}")
result.success = True
except Exception as e:
result.error = str(e)
result.success = False
# Register generic error (disk full, permissions, etc)
if "Checksum Mismatch" not in str(e):
aborter.register_error()
result.duration = time.time() - start_time
return result
# ==========================================
# 4. Toolkit Orchestrator
# ==========================================
class DataMigrationToolkit:
def __init__(self, config: MigrationConfig):
self.config = config
self.throttle = ThrottleController(config.throttle_mbps)
self.aborter = AbortTrigger(threshold=5) # Stop after 5 generic errors
self.results: List[TaskResult] = []
def _gather_files(self) -> List[Tuple[str, str]]:
"""Scans directory recursively and maps source to destination paths."""
file_pairs = []
for root, _, files in os.walk(self.config.source_dir):
for file in files:
src_path = os.path.join(root, file)
rel_path = os.path.relpath(src_path, self.config.source_dir)
dst_path = os.path.join(self.config.dest_dir, rel_path)
file_pairs.append((src_path, dst_path))
return file_pairs
def execute(self):
print(f"--- Starting Migration ---")
print(f"Source: {self.config.source_dir}")
print(f"Target: {self.config.dest_dir}")
print(f"Workers: {self.config.max_workers} | Throttle: {self.config.throttle_mbps} MB/s")
files = self._gather_files()
total_size = sum(os.path.getsize(f[0]) for f in files)
print(f"Found {len(files)} files ({total_size / (1024*1024):.2f} MB).")
start_time = time.time()
with ThreadPoolExecutor(max_workers=self.config.max_workers) as executor:
# Submit jobs
future_to_file = {
executor.submit(
MigrationWorker.migrate_file,
src, dst, self.throttle, self.aborter
): (src, dst) for src, dst in files
}
# Process results as they complete
for future in as_completed(future_to_file):
if self.aborter.is_triggered():
# If aborted, we might want to cancel pending futures
# though as_completed only yields finished ones.
# We simply break the loop to stop processing new results/logic.
executor.shutdown(wait=False, cancel_futures=True)
break
result: TaskResult = future.result()
self.results.append(result)
status = "OK" if result.success else "FAIL"
print(f"[{status}] {os.path.basename(result.source_path)} "
f"({result.size_bytes/1024:.1f}KB) "
f"Hash: {result.source_hash[:8]}...")
self._generate_report(start_time)
def _generate_report(self, start_time):
duration = time.time() - start_time
success_count = sum(1 for r in self.results if r.success)
fail_count = len(self.results) - success_count
throughput = sum(r.size_bytes for r in self.results) / duration / (1024*1024)
print("\n--- Migration Report ---")
print(f"Duration: {duration:.2f}s")
print(f"Throughput: {throughput:.2f} MB/s")
print(f"Successful: {success_count}")
print(f"Failed: {fail_count}")
# Output consistency proof manifest
manifest_path = os.path.join(self.config.dest_dir, "migration_manifest.json")
with open(manifest_path, 'w') as f:
json.dump([r.__dict__ for r in self.results], f, indent=2)
print(f"Manifest saved to: {manifest_path}")
# ==========================================
# 5. Execution Simulation
# ==========================================
if __name__ == "__main__":
# Setup dummy data for demonstration
SRC = "./temp_source_data"
DST = "./temp_dest_data"
if not os.path.exists(SRC):
os.makedirs(SRC)
for i in range(10):
with open(f"{SRC}/file_{i}.txt", "w") as f:
f.write("This is test data " * 1000)
# Configure Migration
config = MigrationConfig(
source_dir=SRC,
dest_dir=DST,
max_workers=4,
throttle_mbps=5, # Limit to 5 MB/s
abort_on_error=True
)
toolkit = DataMigrationToolkit(config)
try:
toolkit.execute()
except KeyboardInterrupt:
print("\n[INTERRUPT] Manual stop requested.")
toolkit.throttle.stop()
toolkit.aborter.stop()
How to Use the Toolkit
- Configuration: Modify the
MigrationConfig dataclass at the bottom of the script (or pass arguments) to point to your actual Source and Destination directories.
- Throttling: Set
throttle_mbps to 0 for unlimited speed, or a specific integer (e.g., 50) to cap bandwidth usage at 50 MB/s.
- Parallelism: Adjust
max_workers based on your CPU cores or disk I/O capabilities (higher for network drives, lower for mechanical HDDs).
Key Features Explained
- Consistency Proof: The
_generate_report method creates a migration_manifest.json. This file acts as a cryptographic proof that the file exists at the destination and matches the source hash.
- Throttling Logic: The
ThrottleController uses a token bucket algorithm. Before writing a chunk of data, the worker must "consume" tokens. If the bucket is empty (bandwidth exceeded), the thread sleeps until tokens replenish.
- Abort Triggers:
- The
AbortTrigger class monitors error rates.
- If a Checksum Mismatch occurs, it is treated as a critical failure, causing an immediate stop of all operations to prevent further data corruption.
- If generic I/O errors (like "Permission Denied") occur 5 times (configurable), the migration stops gracefully.