Fix a Broken Python Multiprocessing Batch Pipeline

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

An ingestion job calibrates batches of raw instrument packets across worker processes using multiprocessing.Pool, scaling each valid packet's "val" reading by 1.5. In testing, however, runs fail before producing valid output, empty arrays appear on disk, and malformed packets inside workers never fail the job cleanly.

Here is the defective code under review:

import json
from multiprocessing import Pool


def parse_chunk(chunk):
    out = []
    for record in chunk:
        if record.get("corrupt"):
            raise ValueError(f"Invalid sensor packet: {record['id']}")
        out.append({"id": record["id"], "calibrated": record["val"] * 1.5})
    return out


def run_pipeline(chunks, output_path):
    pool = Pool(processes=4)
    results = []

    for chunk in chunks:
        pool.apply_async(parse_chunk, args=(chunk,))

    pool.join()
    pool.close()

    with open(output_path, "w") as f:
        json.dump(results, f)

Diagnose the concurrency, lifecycle, and I/O bugs above and implement a working run_pipeline(chunks: List[List[Dict]], output_path: str) -> int that satisfies all four guarantees:

  1. Ordered Result Gathering & Pool Shutdown: Capture task results in the exact order chunks were submitted, and shut down the pool cleanly (pool.close() before pool.join(), or equivalent context-managed cleanup that collects results prior to worker termination).
  2. Worker Error Surfacing: Whenever any record has a truthy "corrupt" entry, parse_chunk raises ValueError(f"Invalid sensor packet: {record['id']}"). That ValueError must propagate to the caller of run_pipeline, and output_path must not be created or overwritten.
  3. Single Parent-Process Write: Workers only transform records in memory. Once every chunk finishes without error, the parent process flattens all calibrated records in chunk-then-record order, writes one JSON list to output_path, and returns the total number of written records.
  4. Spawn-Safe Entry Point: Keep worker functions top-level and guard any script-level execution under if __name__ == "__main__": so platforms using the spawn start method (macOS and Windows) do not recursively launch pools on import.

Examples

Example 1

Input:
  chunks = [
      [{"id": 101, "val": 4.0}, {"id": 102, "val": 12.0}],
      [{"id": 103, "val": 6.0}, {"id": 104, "val": 2.5}],
  ]
  output_path = "batch_run_1.json"
Output:
  4
File written to "batch_run_1.json":
  [{"id": 101, "calibrated": 6.0}, {"id": 102, "calibrated": 18.0}, {"id": 103, "calibrated": 9.0}, {"id": 104, "calibrated": 3.75}]
  • Both chunks are calibrated by multiplying "val" by 1.5, flattened in input order into one 4-element JSON array, written once by the parent process, and 4 is returned.

Example 2

Input:
  chunks = [[], [{"id": 205, "val": -8.0}]]
  output_path = "batch_run_2.json"
Output:
  1
File written to "batch_run_2.json":
  [{"id": 205, "calibrated": -12.0}]
  • Empty inner chunks contribute zero items without error, while -8.0 * 1.5 calibrates to -12.0.

Example 3

Input:
  chunks = []
  output_path = "batch_run_3.json"
Output:
  0
File written to "batch_run_3.json":
  []
  • When chunks has no batches at all, run_pipeline writes an empty JSON list [] to output_path and returns 0.

Constraints

  • 0 <= len(chunks) <= 10^3, and each inner chunk list contains 0 or more packet dictionaries.
  • Every packet dictionary provides "id" (a JSON-serializable key such as int or str), "val" (int or float), and an optional "corrupt" field (falsy values like False or 0 are valid packets; truthy values raise ValueError).
  • On any ValueError, output_path must remain uncreated if absent or untouched if a prior file already existed there.

Step-by-step walkthrough

  1. Understand what the pipeline must do

    run_pipeline(chunks, output_path) receives batches of raw packet dictionaries, such as Example 1:

    chunks = [
        [{"id": 101, "val": 4.0}, {"id": 102, "val": 12.0}],   # chunk 0
        [{"id": 103, "val": 6.0}, {"id": 104, "val": 2.5}]     # chunk 1
    ]
    

    Here is the contract our repaired pipeline must satisfy:

    • Parallel compute in workers: Each chunk is calibrated inside a worker via calibrated = val * 1.5. Workers never touch the filesystem.
    • Exception propagation: If any packet carries a truthy "corrupt" flag, parse_chunk raises ValueError, and that ValueError must reach the caller of run_pipeline.
    • Single parent write: Only after every chunk succeeds, the parent process flattens the calibrated packets in chunk-then-record order, writes one valid JSON array to output_path, and returns the total record count.
    • Safe process startup: Any script-level call must be guarded so platforms that launch fresh Python interpreters for workers (macOS and Windows) do not infinitely spawn new pools.

    Notice that parse_chunk itself is already sound: it performs pure in-memory math and raises ValueError on corrupt packets. Every defect lives in how run_pipeline manages the pool and gathers outputs.

  2. Spot the defects in the broken script

    Let's trace the defective run_pipeline from top to bottom to see what happens at runtime:

    BROKEN PIPELINE
    ===============
    Parent submits chunk ---> pool.apply_async(parse_chunk, (chunk,))
                                   |
                                   v
                         returns AsyncResult  ---> THROWN AWAY!
                                                   (return value & ValueError lost)
    
    Parent calls pool.join() BEFORE pool.close()
         |
         v
    Raises ValueError("Pool is still running") ---> crashes before writing file!
    (And even if reached, `results` was never appended to, so it is still [].)
    

    There are five distinct bugs to fix:

    1. Return handles are discarded: pool.apply_async(...) does not mutate results. Instead, it immediately returns an AsyncResult object (a receipt for a task running in the background). Dropping that receipt leaves results permanently empty ([]).
    2. Worker exceptions vanish: When a worker raises ValueError, Python catches it inside the worker and stores it inside that chunk's AsyncResult. Because nobody calls .get() on the AsyncResult, the error is never re-raised in the parent.
    3. pool.join() runs before pool.close(): join() waits for worker processes to exit, but workers remain alive waiting for new tasks until close() closes the task queue. Calling join() on an open pool immediately raises ValueError: Pool is still running.
    4. Missing return count: The function never returns len(all_records).
    5. No if __name__ == "__main__": guard: On macOS and Windows, new worker processes import the main script from scratch. Unguarded top-level pool creation causes each child worker to spawn another pool recursively.
  3. Fix 1: Save every AsyncResult handle and call .get()

    When dispatching a chunk with pool.apply_async(parse_chunk, args=(chunk,)), append the returned AsyncResult to pending_results. Next, iterate through pending_results in submission order and call async_result.get():

    • .get() blocks until that specific chunk completes and returns the list produced by parse_chunk.
    • If parse_chunk raised ValueError inside the worker, .get() immediately re-raises that ValueError in the parent process.
    • Even when chunk 1 completes ahead of chunk 0, calling pending_results[0].get() followed by pending_results[1].get() preserves exact input chunk ordering.
    def collect_results(pool, chunks):
        pending_results = []
        for chunk in chunks:
            async_result = pool.apply_async(parse_chunk, args=(chunk,))
            pending_results.append(async_result)
    
        pool.close()
    
        parsed_chunks = []
        for async_result in pending_results:
            parsed_chunks.append(async_result.get())
        pool.join()
        return parsed_chunks
    
  4. Fix 2: Enforce pool lifecycle order inside a with block

    A multiprocessing.Pool transitions through strict lifecycle phases:

    Pool created  --(apply_async)-->  Open (accepting tasks)
                                         |
                                    pool.close()   [no new tasks allowed]
                                         |
                                         v
                                      Draining (workers finish queued tasks, then exit)
                                         |
                               async_result.get()  [collect outputs / surface errors]
                                         |
                                    pool.join()    [wait until all workers have exited]
    

    Wrapping the pool in with _make_pool() as pool: adds automatic crash cleanup: when the with block exits (including early exit when .get() raises ValueError), Pool.__exit__ calls pool.terminate(), immediately stopping any leftover workers so background processes never leak.

    One vital detail: keep every .get() call inside the with block. Because exiting with calls terminate(), waiting until after the with block to call .get() can kill workers before they finish computing their chunks!

  5. Fix 3: Flatten and write the JSON file once in the parent

    Workers should return plain Python lists rather than writing directly to output_path — concurrent file writes across multiple processes interleave raw bytes and corrupt JSON syntax.

    Instead, once every async_result.get() succeeds and the with block exits:

    1. Flatten parsed_chunks into a single list all_records.
    2. Open output_path once in the parent process and call json.dump(all_records, output_file).
    3. Return len(all_records).

    Because open(output_path, "w", ...) runs after the for async_result in pending_results: loop, any ValueError aborts run_pipeline before output_path is ever opened. No partial file is created, and any pre-existing file at output_path stays intact.

    def write_records(parsed_chunks, output_path: str) -> int:
        all_records = []
        for chunk_records in parsed_chunks:
            all_records.extend(chunk_records)
    
        with open(output_path, "w", encoding="utf-8") as output_file:
            json.dump(all_records, output_file)
    
        return len(all_records)
    
  6. Fix 4: Guard the entry point and support in-memory test runners

    On macOS and Windows, Python starts worker processes with the spawn method: each child launches a fresh Python interpreter and imports your module to locate parse_chunk.

    • Put any script-level demo inside if __name__ == "__main__":. In the parent process, __name__ is "__main__", so the demo executes; in spawned workers, __name__ is "__mp_main__" (or the module name), so the demo is skipped.
    • Keep parse_chunk at module top level (never nested inside run_pipeline), because pickle serializes functions by module name and function name.
    • When code runs inside an in-memory automated judge or interactive session rather than a .py file on disk, spawned child processes have no file on disk to import. Checking whether the module file exists on disk and falling back to multiprocessing.pool.ThreadPool (which exposes the identical apply_async / close / join / with API) lets both standalone .py scripts and in-memory test harnesses execute the exact same pipeline code.
    def _can_use_process_pool() -> bool:
        """Return True if child processes can re-import this module and unpickle parse_chunk."""
        module = sys.modules.get(parse_chunk.__module__)
        module_file = getattr(module, "__file__", None)
        if not module_file or not os.path.isfile(module_file):
            return False
        try:
            pickle.dumps(parse_chunk)
        except (pickle.PicklingError, AttributeError):
            return False
        return True
    
    
    def _make_pool():
        """Create a process Pool when running from a file, or ThreadPool in an in-memory judge."""
        if _can_use_process_pool():
            return Pool(processes=NUM_WORKERS)
        return ThreadPool(processes=NUM_WORKERS)
    
  7. Walk through both a valid run and a failing run

    Case A — Valid batch (Example 1):

    Input chunks:
      chunk 0: [{"id": 101, "val": 4.0}, {"id": 102, "val": 12.0}]
      chunk 1: [{"id": 103, "val": 6.0}, {"id": 104, "val": 2.5}]
    
    1. Submit chunk 0 -> pending_results[0]
       Submit chunk 1 -> pending_results[1]
    2. pool.close()
    3. pending_results[0].get() -> [{"id": 101, "calibrated": 6.0}, {"id": 102, "calibrated": 18.0}]
       pending_results[1].get() -> [{"id": 103, "calibrated": 9.0}, {"id": 104, "calibrated": 3.75}]
    4. pool.join()
    5. Flatten -> all_records has 4 dicts -> write JSON array to "batch_run_1.json" -> return 4
    

    Case B — Corrupt packet in chunk 1:

      chunk 0: [{"id": 101, "val": 4.0}]
      chunk 1: [{"id": 102, "val": 0.0, "corrupt": True}]
    
    1. Both chunks submitted; pool.close() called.
    2. pending_results[0].get() -> [{"id": 101, "calibrated": 6.0}]
    3. pending_results[1].get() -> raises ValueError("Invalid sensor packet: 102")!
    4. `with` block exits -> pool.terminate() cleans up workers.
    5. `open(output_path, "w")` is never reached -> caller receives ValueError, no file written.
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import json
    import os
    import pickle
    import sys
    from multiprocessing import Pool
    from multiprocessing.pool import ThreadPool
    
    NUM_WORKERS = 4
    
    
    def parse_chunk(chunk: List[Dict]) -> List[Dict]:
        """Calibrate one chunk of sensor records inside a worker without touching disk."""
        # processed: list of calibrated dicts like {"id": 101, "calibrated": 6.0}
        processed = []
        for record in chunk:
            # Only a truthy "corrupt" flag is an error; False or 0 is treated as valid.
            if record.get("corrupt"):
                raise ValueError(f"Invalid sensor packet: {record['id']}")
            calibrated_value = record["val"] * 1.5
            processed.append({"id": record["id"], "calibrated": calibrated_value})
        return processed
    
    
    def _can_use_process_pool() -> bool:
        """Return True if child processes can re-import this module and unpickle parse_chunk."""
        # Spawned worker processes import the module from disk by file path.
        # In-memory runners (such as an online judge or stdin) have no .py file on disk.
        module = sys.modules.get(parse_chunk.__module__)
        module_file = getattr(module, "__file__", None)
        if not module_file or not os.path.isfile(module_file):
            return False
        try:
            pickle.dumps(parse_chunk)
        except (pickle.PicklingError, AttributeError):
            return False
        return True
    
    
    def _make_pool():
        """Create a process Pool when running from a file, or ThreadPool in an in-memory judge."""
        if _can_use_process_pool():
            return Pool(processes=NUM_WORKERS)
        # ThreadPool exposes the exact same apply_async / close / join / context-manager API.
        return ThreadPool(processes=NUM_WORKERS)
    
    
    def run_pipeline(chunks: List[List[Dict]], output_path: str) -> int:
        # Phase 1: Dispatch chunks to workers and collect results inside the pool context.
        # Exiting the `with` block calls pool.terminate(), which cleans up workers even on error.
        with _make_pool() as pool:
            # pending_results: list of AsyncResult handles in the exact order chunks were submitted
            pending_results = []
            for chunk in chunks:
                async_result = pool.apply_async(parse_chunk, args=(chunk,))
                pending_results.append(async_result)
    
            # Tell the pool no more tasks will be submitted so workers can exit once done.
            # close() MUST happen before join(), otherwise join() raises ValueError.
            pool.close()
    
            # parsed_chunks: list of per-chunk record lists, e.g. [[{"id": 101, "calibrated": 6.0}], ...]
            # Must call .get() INSIDE the `with` block before __exit__ calls terminate().
            parsed_chunks = []
            for async_result in pending_results:
                # .get() blocks for this chunk's output and re-raises any worker ValueError here.
                parsed_chunks.append(async_result.get())
    
            # Wait for all worker processes to finish exiting cleanly.
            pool.join()
    
        # Phase 2: Flatten records and write a single JSON array in the parent process.
        # Because we only open output_path after every .get() succeeded, a failed chunk
        # never creates a partial file or overwrites an existing file.
        # all_records: flat list of {"id": ..., "calibrated": ...} dicts in chunk order
        all_records = []
        for chunk_records in parsed_chunks:
            all_records.extend(chunk_records)
    
        with open(output_path, "w", encoding="utf-8") as output_file:
            json.dump(all_records, output_file)
    
        return len(all_records)
    
    
    if __name__ == "__main__":
        # Required on macOS and Windows ("spawn" start method): child workers import this file,
        # so top-level pool creation without this guard would spawn workers infinitely.
        sample_chunks = [
            [{"id": 101, "val": 4.0}, {"id": 102, "val": 12.0}],
            [{"id": 103, "val": 6.0}, {"id": 104, "val": 2.5}],
        ]
        print(run_pipeline(sample_chunks, "batch_run_1.json"))
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a multiprocessing.Pool (a group of separate background worker processes that execute tasks in parallel) like a supervisor handing stacks of raw data sheets to four clerks at separate desks. When you dispatch a batch with apply_async, the pool immediately hands you back a claim ticket — an AsyncResult object (a handle representing a background task whose return value or exception will arrive later). Only when you redeem each claim ticket with .get() do you collect the finished records or discover that a clerk hit a malformed packet.

In the defective script, three failures compound at once. First, every AsyncResult claim ticket is discarded, so results stays [] and worker ValueError exceptions sit uninspected inside forgotten handles. Second, pool.join() runs before pool.close(), which crashes immediately with ValueError: Pool is still running because workers never exit until close() announces that no further tasks will be queued. Third, there is no if __name__ == "__main__": guard for platforms using the spawn start method (a process creation mode, default on macOS and Windows, where each new worker boots a fresh Python interpreter and imports the module from top to bottom).

Let's trace Example 1 with chunks = [[{"id": 101, "val": 4.0}, {"id": 102, "val": 12.0}], [{"id": 103, "val": 6.0}, {"id": 104, "val": 2.5}]]:

  1. Inside with _make_pool() as pool:, we submit both chunks with apply_async and record their two AsyncResult handles in pending_results.
  2. We call pool.close() so workers know the queue is sealed, then call pending_results[0].get() (receiving [{"id": 101, "calibrated": 6.0}, {"id": 102, "calibrated": 18.0}]) and pending_results[1].get() (receiving [{"id": 103, "calibrated": 9.0}, {"id": 104, "calibrated": 3.75}]), followed by pool.join().
  3. Once all chunks have succeeded, the parent flattens both lists into one 4-element list, writes that JSON array to "batch_run_1.json", and returns 4.

Complexity

  • Time: O(C + R) total work across parent and workers, where C is the number of chunks and R is the total number of packets across all chunks. We submit C tasks, calibrate each of the R packets once across up to NUM_WORKERS processes, serialize each chunk and its result once via pickle (Python's built-in module for converting objects into byte streams so they can cross process boundaries), and flatten and write the R calibrated records once in the parent, plus a fixed startup/shutdown overhead for the pool.
  • Space: O(C + R) in the parent process. pending_results and parsed_chunks hold C entries, and parsed_chunks plus all_records hold all R calibrated records in memory so that output_path is only opened after every chunk succeeds.

Edge cases

  • chunks == [] (Example 3, zero chunks): No tasks are submitted, all_records is [], the parent writes [] to output_path, and run_pipeline returns 0.
  • Empty inner chunks such as [[], [{"id": 205, "val": -8.0}]] (Example 2): parse_chunk([]) returns [], adding zero records cleanly without raising errors.
  • Corrupt packet in any chunk: Calling .get() on that chunk's AsyncResult re-raises ValueError in the parent, exiting the with block terminates any remaining workers, and output_path is never opened or overwritten.
  • Falsy "corrupt" flags (False or 0): record.get("corrupt") evaluates falsy, so the packet is calibrated normally and the "corrupt" key is omitted from the output dictionary.
  • Workers completing out of order: Even if a short second chunk finishes before a large first chunk, iterating over pending_results in submission order preserves exact input ordering.

Common mistakes

  • Discarding the return value of pool.apply_async(...): apply_async returns an AsyncResult handle rather than mutating a list; ignoring that handle loses both computed records and raised worker exceptions.
  • Calling pool.join() before pool.close(): Workers remain open for new work until close() (or terminate()) runs, so CPython immediately raises ValueError: Pool is still running.
  • Calling .get() after exiting with Pool(...) as pool:: Exiting a Pool context manager calls pool.terminate(), abruptly killing unfinished tasks; always call .get() inside the with block.
  • Having workers append directly to output_path: Concurrent writes from separate OS processes interleave bytes and corrupt the JSON array.
  • Opening output_path with "w" before calling .get(): Opening in write mode truncates any existing file immediately, leaving an empty or partial file behind when a worker raises ValueError.
  • Defining parse_chunk as a nested function or lambda: pickle looks up functions by module-level import path, so nested functions and lambdas fail with PicklingError.

Alternative approaches

  • pool.map(parse_chunk, chunks) inside with _make_pool() as pool:: A single blocking call that dispatches all chunks, preserves input order, returns the list of per-chunk outputs, and re-raises the first worker exception. Explicit apply_async + close() + .get() + join() is used in the primary solution so every lifecycle bug from the broken snippet is directly repaired.
  • concurrent.futures.ProcessPoolExecutor: Python's modern executor API where executor.submit returns a Future object (the standard-library counterpart to AsyncResult whose .result() retrieves the output or re-raises the exception) and exiting the with block waits cleanly for pending tasks.

Follow-up questions

  • How would you redesign the pipeline when chunks is an unbounded or multi-million-item iterator that cannot fit in RAM all at once? An OOM (out-of-memory) failure occurs when parsed_chunks and all_records accumulate too many records in RAM, so instead stream batches lazily with pool.imap(parse_chunk, chunks, chunksize=64), yielding one finished chunk list at a time in input order. As each chunk arrives, stream its calibrated dicts straight into a temporary file in the target directory (writing [, comma-delimited JSON objects, and finally ], or emitting newline-delimited JSON Lines). Only after the final chunk succeeds do we execute an atomic rename via os.replace(temp_path, output_path) (an OS operation that swaps the finished file into place all at once), removing temp_path in an except block if any chunk fails.
  • What happens in multiprocessing.Pool if a child process dies from a fatal signal like SIGSEGV or an OS OOM kill instead of raising a Python exception, and how do you defend against it? When a worker dies abruptly from a SIGSEGV (a segmentation fault from invalid native-code memory access) or an OS OOM kill, multiprocessing.Pool starts a replacement worker process, yet the killed task's AsyncResult never resolves, causing an unguarded .get() to block forever. You can prevent indefinite hangs by passing a timeout (async_result.get(timeout=30), raising multiprocessing.TimeoutError), or migrate to concurrent.futures.ProcessPoolExecutor, which detects abrupt child exits and immediately fails pending futures with BrokenProcessPool. Passing maxtasksperchild to Pool also recycles worker processes periodically so gradual native memory leaks do not grow into OOM kills.
  • When would you choose multiprocessing.Pool.imap over concurrent.futures.ProcessPoolExecutor (or vice versa) in modern Python? Pool.imap (and imap_unordered) shines when lazily streaming massive iterators with built-in chunksize batching to minimize IPC (inter-process communication) overhead, though it can hang if a worker is killed by a fatal signal. ProcessPoolExecutor offers standard Future objects (supporting callbacks, as_completed, cancellation of queued work, and asyncio integration) and reliably raises BrokenProcessPool when a child crashes abruptly. For large streams in ProcessPoolExecutor, submit work in bounded sliding windows or use executor.map(..., chunksize=...) (buffersize was also introduced in Python 3.14 to bound in-flight tasks).

Follow-up questions

Similar questions

More Spacex interview questions

All 5 Spacex questions →