KatInterview

Build a Concurrent Batch Transform Engine with Error Isolation

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencyerror-handlingthreading

Last 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

  1. Concurrency Control: Use up to max_workers threads to process jobs in parallel.
  2. Error Isolation: If a job fails (invalid input, exception during transformation), record the failure and continue processing other jobs.
  3. Order Preservation: Return results in the exact order jobs were submitted, regardless of completion order.
  4. 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 ≤ 32
  • 0 ≤ 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