Build a Concurrent Batch Transform Engine with Error Isolation
Data Structure DesignModel answerLast updated
Create a worker-pool-based processor that applies transformation pipelines to 2D integer grids, ensuring failures in individual items don't affect others.
Problem
Build a batch processor that runs transformation pipelines on 2D integer grids using a fixed-size worker pool. Each item in the batch is processed independently, and errors in one item must not affect others.
Your task is to implement ParallelImageProcessor, which accepts a list of jobs and processes them concurrently. Each job contains a grid and a sequence of transformation functions to apply.
Class Interface
from dataclasses import dataclass
from typing import Callable, List, Optional
@dataclass
class ImageJob:
job_id: str
image: List[List[int]]
transforms: List[Callable[[List[List[int]]], List[List[int]]]]
@dataclass
class JobResult:
job_id: str
success: bool
image: Optional[List[List[int]]]
error: Optional[str]
class ParallelImageProcessor:
def __init__(self, max_workers: int):
"""Initialize with a fixed concurrency limit."""
pass
def process_batch(self, jobs: List[ImageJob]) -> List[JobResult]:
"""Process all jobs and return results in the same order as input."""
pass
Requirements
- Concurrency Control: Use up to
max_workersthreads to process jobs in parallel. - Error Isolation: If a job fails (invalid input, exception during transformation), record the failure and continue processing other jobs.
- Order Preservation: Return results in the exact order jobs were submitted, regardless of completion order.
- Input Protection: Transformations must not modify the original input grids.
Input Validation
A grid is valid when:
- It's a non-empty list of rows
- All rows have the same positive length (no ragged matrices)
- Every element is an integer in
[0, 255](not booleans)
Validate both input grids and the output of each transformation. If validation fails at any step, mark the job as failed.
Constraints
1 ≤ max_workers ≤ 320 ≤ len(jobs) ≤ 1000- Valid grids have dimensions
1 ≤ H, W ≤ 1000
Example
def flip(grid):
return [[255 - val for val in row] for row in grid]
def crash(grid):
raise RuntimeError("Transform failed")
jobs = [
ImageJob("A", [[10, 20], [30, 40]], [flip]),
ImageJob("B", [[100]], [crash]),
]
processor = ParallelImageProcessor(max_workers=2)
results = processor.process_batch(jobs)
# Expected output:
# [
# JobResult(job_id="A", success=True, image=[[245, 235], [225, 215]], error=None),
# JobResult(job_id="B", success=False, image=None, error="Transform failed"),
# ]
Hints
Hint 1
Each job should run in complete isolation—wrap all job logic in exception handling so one failure can't crash the batch
Hint 2
Use a list of futures to maintain input order rather than processing results as they complete
Hint 3
Make a deep copy of the input grid before applying transforms to prevent mutations from leaking back to the caller
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Concurrent Transform Pipeline with Fault Isolation
Approach
This problem tests your ability to design robust concurrent systems. The core challenges are:
- Isolated execution units: Each job must be self-contained so exceptions can't propagate between jobs
- Order preservation: Results must match input order, not completion order
- Defensive copying: Transformations receive copies, not references to original data
We'll use ThreadPoolExecutor rather than ProcessPoolExecutor because transformation functions may be lambdas or closures that can't be pickled for inter-process communication. Since we're working with arbitrary Python callables that could hold the GIL, threads are the appropriate choice.
Architecture
Job Execution Flow:
- Validate the input grid (structure and value ranges)
- Create a deep copy to protect the original
- Apply each transformation sequentially, validating after each step
- Catch all exceptions and convert them to failed results
Worker Pattern:
- Submit all jobs to the executor immediately, capturing a future for each
- Store futures in a list that mirrors input order
- Retrieve results from futures in submission order (not completion order)
Error Categories:
- Input validation failures: Empty grids, ragged rows, invalid pixel values, non-integer types
- Transform exceptions: Any exception raised during transformation execution
- Output validation failures: Transform returns invalid structure or out-of-range values
Implementation Details
Validation Logic:
Check that every grid is a non-empty list of equal-length non-empty lists containing only integers in [0, 255]. Explicitly reject bool types even though isinstance(True, int) returns True in Python—use type(p) is not int to enforce strict type checking.
Run validation on the input and after each transform. This ensures every transform receives well-formed data and guarantees a transform that produces corrupt output is treated as a failure rather than silently returning bad data.
Deep Copying:
Use [list(row) for row in image] to create a new list of new row lists. Since integers are immutable, this achieves a full deep copy. A shallow list(image) would share row references with the original.
Order Preservation:
Build the futures list in input order: futures[i] corresponds to jobs[i]. When collecting results, iterate through futures sequentially rather than using as_completed(), which would return results in completion order.
Exception Handling:
Wrap all job logic in try/except Exception. Catch Exception rather than BaseException to allow KeyboardInterrupt and SystemExit to propagate normally. Convert any caught exception to a JobResult with success=False and the exception message.
Python Code
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Callable, List, Optional
Image = List[List[int]]
@dataclass
class ImageJob:
job_id: str
image: Image
transforms: List[Callable[[Image], Image]]
@dataclass
class JobResult:
job_id: str
success: bool
image: Optional[Image]
error: Optional[str]
class ParallelImageProcessor:
def __init__(self, max_workers: int):
if not isinstance(max_workers, int) or not (1 <= max_workers <= 32):
raise ValueError("max_workers must be between 1 and 32")
self.max_workers = max_workers
def process_batch(self, jobs: List[ImageJob]) -> List[JobResult]:
if not jobs:
return []
# Use min to avoid creating more workers than jobs
worker_count = min(self.max_workers, len(jobs))
with ThreadPoolExecutor(max_workers=worker_count) as executor:
# Submit in order and keep future handles
futures = [executor.submit(self._execute_job, job) for job in jobs]
# Collect in submission order
results = []
for job, future in zip(jobs, futures):
try:
results.append(future.result())
except Exception as e:
# Safety net—should never execute if _execute_job is correct
results.append(JobResult(
job.job_id, False, None, self._format_error(e)
))
return results
def _execute_job(self, job: ImageJob) -> JobResult:
"""Execute a single job in a worker. Never raises."""
try:
# Validate input
self._validate_grid(job.image, "input")
# Deep copy to prevent mutation
current = [list(row) for row in job.image]
# Apply transform pipeline
for idx, transform_fn in enumerate(job.transforms):
current = transform_fn(current)
self._validate_grid(current, f"transform {idx} output")
return JobResult(job.job_id, True, current, None)
except Exception as e:
return JobResult(job.job_id, False, None, self._format_error(e))
@staticmethod
def _validate_grid(grid, context: str) -> None:
"""Raise ValueError if grid is invalid."""
if not isinstance(grid, list) or len(grid) == 0:
raise ValueError(f"{context}: grid must be non-empty list")
expected_width = None
for row_idx, row in enumerate(grid):
if not isinstance(row, list) or len(row) == 0:
raise ValueError(f"{context}: row {row_idx} must be non-empty list")
if expected_width is None:
expected_width = len(row)
elif len(row) != expected_width:
raise ValueError(f"{context}: row {row_idx} has inconsistent width")
for col_idx, pixel in enumerate(row):
if type(pixel) is not int or not (0 <= pixel <= 255):
raise ValueError(
f"{context}: pixel at ({row_idx},{col_idx}) must be int in [0,255]"
)
@staticmethod
def _format_error(exc: Exception) -> str:
"""Extract error message, fallback to exception type name."""
return str(exc) or type(exc).__name__
Complexity Analysis
For a batch with job j having dimensions H_j × W_j and T_j transforms:
- Time (sequential work): O(Σ_j (T_j + 1) · H_j · W_j) for validation and copying, plus the cost of executing transforms
- Wall-clock time: Sequential work divided by
max_workersin the ideal case (actual parallelism depends on Python's GIL and transform implementations) - Space: O(Σ_j H_j · W_j) for result storage, plus O(max_workers · max(H·W)) for in-flight working copies
Edge Cases and Design Decisions
Empty batch: Return empty list immediately without creating thread pool.
Invalid max_workers: Raise ValueError at construction time—this is a programming error, not a runtime job failure.
Grid validation failures: Empty grid, single empty row, ragged rows, non-list rows, boolean values, floats, or values outside [0,255] all produce descriptive error messages.
Transform output validation: A transform returning None or malformed data fails the job rather than corrupting downstream processing.
Empty transform list: Valid—returns a copy of the input with success=True.
Duplicate job IDs: Allowed—we preserve position-based ordering, not ID-based.
In-place mutation: If a transform mutates its input, only our private copy is affected.
What Makes This Solution Strong
- Bulletproof isolation: Worker function never raises—all exceptions become failed results
- Correct ordering: Futures list preserves submission order without sorting or reordering logic
- True immutability: Row-level copy plus integer immutability guarantees no shared state
- Comprehensive validation: Checks input, validates after every transform step, catches multiple failure modes with clear error messages
- Resource efficiency: Uses
min(max_workers, len(jobs))to avoid creating idle threads