python
import heapq
import time
import threading
from collections import defaultdict, deque
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Callable, Any
from enum import Enum
import uuid
# Enum for job states
class JobState(Enum):
PENDING = "pending"
SCHEDULED = "scheduled"
PROCESSING = "processing"
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class BackfillJob:
tenant_id: str
sequence_id: int # Strictly increasing per tenant for ordering
payload: Any # Data to process (e.g., event batch)
retry_count: int = 0
max_retries: int = 3
created_at: float = field(default_factory=time.time)
job_id: str = field(default_factory=lambda: str(uuid.uuid4()))
def __lt__(self, other):
# Heap ordering: prioritize by (tenant_id, sequence_id) for ordering + starvation prevention
return (self.tenant_id, self.sequence_id) < (other.tenant_id, other.sequence_id)
@dataclass
class TenantState:
last_processed_seq: int = 0
pending_jobs: deque[int] = field(default_factory=deque) # Sequence IDs waiting
rate_limit_tokens: float = 100.0 # Token bucket for rate limiting
last_token_refill: float = field(default_factory=time.time)
token_refill_rate: float = 10.0 # Tokens per second (configurable per tenant)
starvation_counter: int = 0 # Tracks rounds without selection
active_workers: int = 0 # Number of concurrent jobs
class CorrectnessViolation(Exception):
"""Raised when correctness checks fail."""
pass
class TenantAwareBackfillOrchestrator:
"""
A tenant-aware backfill orchestrator that ensures:
- Strict ordering per tenant (process seq N only after N-1).
- Per-tenant rate limiting via token bucket.
- Anti-starvation via round-robin tenant selection with starvation counters.
- Correctness checks: idempotency (via seq uniqueness), duplicates, and post-processing verification.
Scalable design notes:
- In-memory for demo; use Redis for persistence/distribution (e.g., sorted sets for heaps, hashes for state).
- Workers can be threaded or external (e.g., via Celery/Kafka).
- For production: Add leader election (e.g., etcd), metrics (Prometheus), dead-letter queues.
"""
def __init__(
self,
worker_fn: Callable[[BackfillJob], bool], # User-provided processing function (returns success)
max_concurrent_per_tenant: int = 1,
check_fn: Optional[Callable[[BackfillJob, Any], bool]] = None, # Optional post-process verifier
refill_interval: float = 1.0 # Token bucket check interval (seconds)
):
self.worker_fn = worker_fn
self.check_fn = check_fn or (lambda job, result: True)
self.max_concurrent_per_tenant = max_concurrent_per_tenant
self.refill_interval = refill_interval
# Core data structures
self._tenant_states: Dict[str, TenantState] = {}
self._pending_heap: List[BackfillJob] = [] # Min-heap for scheduling (tenant,seq ordered)
self._job_by_id: Dict[str, BackfillJob] = {} # Quick lookup
self._lock = threading.RLock() # Thread-safety
self._running = False
self._scheduler_thread = None
def add_jobs(self, jobs: List[BackfillJob]) -> None:
"""Enqueue jobs. Validates ordering gaps and duplicates."""
with self._lock:
for job in jobs:
tenant_id = job.tenant_id
if tenant_id not in self._tenant_states:
self._tenant_states[tenant_id] = TenantState()
state = self._tenant_states[tenant_id]
# Correctness: Check for duplicates (same seq)
if job.sequence_id in state.pending_jobs or job.sequence_id <= state.last_processed_seq:
raise CorrectnessViolation(f"Duplicate or out-of-order seq {job.sequence_id} for tenant {tenant_id}")
# Detect gaps (warn, but allow for now; could auto-backfill)
if state.pending_jobs and job.sequence_id != max(state.pending_jobs) + 1:
print(f"Warning: Gap detected for tenant {tenant_id}: expected {max(state.pending_jobs)+1}, got {job.sequence_id}")
state.pending_jobs.append(job.sequence_id)
self._job_by_id[job.job_id] = job
heapq.heappush(self._pending_heap, job)
def _refill_tokens(self, state: TenantState) -> None:
"""Token bucket refill."""
now = time.time()
elapsed = now - state.last_token_refill
state.rate_limit_tokens = min(
100.0, # Max bucket size
state.rate_limit_tokens + elapsed * state.token_refill_rate
)
state.last_token_refill = now
def _select_next_tenant(self) -> Optional[str]:
"""Anti-starvation scheduler: Round-robin with starvation boost."""
eligible_tenants = [
t for t, state in self._tenant_states.items()
if (state.active_workers < self.max_concurrent_per_tenant and
state.rate_limit_tokens >= 1.0 and
state.pending_jobs)
]
if not eligible_tenants:
return None
# Boost starved tenants (haven't been picked in >5 rounds)
starved = [(t, self._tenant_states[t].starvation_counter) for t in eligible_tenants if self._tenant_states[t].starvation_counter > 5]
if starved:
starved.sort(key=lambda x: x[1], reverse=True)
return starved[0][0]
# Round-robin fallback (simple: pick first lexicographically for determinism)
return min(eligible_tenants)
def _schedule_next_job(self) -> Optional[BackfillJob]:
"""Select and pop next job respecting all constraints."""
with self._lock:
while self._pending_heap:
candidate = self._pending_heap[0]
state = self._tenant_states[candidate.tenant_id]
# Ordering check: Only schedule if it's the next expected seq
expected_seq = state.last_processed_seq + 1
if candidate.sequence_id != expected_seq:
# Pop and re-heap invalid (out-of-order); wait for predecessors
heapq.heappop(self._pending_heap)
continue
# Rate limit check
self._refill_tokens(state)
if state.rate_limit_tokens < 1.0:
return None
# Pop and schedule
job = heapq.heappop(self._pending_heap)
state.rate_limit_tokens -= 1.0
state.active_workers += 1
state.starvation_counter = 0 # Reset on selection
# Remove from pending deque (O(n), optimize with set for prod)
try:
state.pending_jobs.remove(job.sequence_id)
except ValueError:
pass # Already removed
return job
return None
def _process_job(self, job: BackfillJob) -> None:
"""Process job with retries, correctness checks."""
state = self._tenant_states[job.tenant_id]
try:
success = self.worker_fn(job)
if success:
# Correctness: Verify result
if not self.check_fn(job, None): # Pass result if worker_fn yields it
raise CorrectnessViolation(f"Verification failed for job {job.job_id}")
state.last_processed_seq = job.sequence_id
job_state = JobState.COMPLETED
else:
raise RuntimeError("Worker failed")
except Exception as e:
job.retry_count += 1
if job.retry_count >= job.max_retries:
job_state = JobState.FAILED
print(f"Job {job.job_id} failed permanently: {e}")
else:
job_state = JobState.PENDING
# Re-heap for retry (with backoff)
time.sleep(2 ** job.retry_count)
heapq.heappush(self._pending_heap, job)
else:
job_state = JobState.COMPLETED
# Update state
with self._lock:
state.active_workers -= 1
if job_state == JobState.COMPLETED:
del self._job_by_id[job.job_id] # Cleanup
# Increment starvation for non-selected tenants
for t_state in self._tenant_states.values():
if t_state != state:
t_state.starvation_counter += 1
def start(self) -> None:
"""Start scheduler loop in background thread."""
if self._running:
return
self._running = True
self._scheduler_thread = threading.Thread(target=self._scheduler_loop, daemon=True)
self._scheduler_thread.start()
def _scheduler_loop(self) -> None:
while self._running:
job = self._schedule_next_job()
if job:
# Spawn worker thread (or queue to pool)
worker_thread = threading.Thread(target=self._process_job, args=(job,))
worker_thread.daemon = True
worker_thread.start()
else:
time.sleep(self.refill_interval)
def stop(self) -> None:
self._running = False
if self._scheduler_thread:
self._scheduler_thread.join()
def get_status(self, tenant_id: str) -> Dict[str, Any]:
"""Metrics per tenant."""
with self._lock:
if tenant_id not in self._tenant_states:
return {}
state = self._tenant_states[tenant_id]
return {
"last_processed_seq": state.last_processed_seq,
"pending_count": len(state.pending_jobs),
"active_workers": state.active_workers,
"rate_limit_tokens": state.rate_limit_tokens,
"starvation_counter": state.starvation_counter,
}
# Example usage
def example_worker(job: BackfillJob) -> bool:
print(f"Processing tenant {job.tenant_id}, seq {job.sequence_id}: {job.payload[:50]}...")
# Simulate work + occasional failure
time.sleep(0.1)
return job.sequence_id % 10 != 0 # Fail 10% of jobs
def example_verifier(job: BackfillJob, result: Any) -> bool:
# Simulate idempotency check (e.g., DB unique constraint)
return True
if __name__ == "__main__":
orch = TenantAwareBackfillOrchestrator(
worker_fn=example_worker,
check_fn=example_verifier,
max_concurrent_per_tenant=2
)
# Add jobs for multiple tenants
tenant_a_jobs = [BackfillJob("A", i, f"data_A_{i}") for i in range(1, 21)]
tenant_b_jobs = [BackfillJob("B", i, f"data_B_{i}") for i in range(1, 11)]
orch.add_jobs(tenant_a_jobs + tenant_b_jobs)
print("Starting orchestrator...")
orch.start()
# Run for 10s
time.sleep(10)
print("Tenant A status:", orch.get_status("A"))
print("Tenant B status:", orch.get_status("B"))
orch.stop()
This provides a complete, runnable foundation! Test with the example.