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:
- Ordered Result Gathering & Pool Shutdown: Capture task results in the exact order
chunkswere submitted, and shut down the pool cleanly (pool.close()beforepool.join(), or equivalent context-managed cleanup that collects results prior to worker termination). - Worker Error Surfacing: Whenever any record has a truthy
"corrupt"entry,parse_chunkraisesValueError(f"Invalid sensor packet: {record['id']}"). ThatValueErrormust propagate to the caller ofrun_pipeline, andoutput_pathmust not be created or overwritten. - 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. - Spawn-Safe Entry Point: Keep worker functions top-level and guard any script-level execution under
if __name__ == "__main__":so platforms using thespawnstart 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"by1.5, flattened in input order into one 4-element JSON array, written once by the parent process, and4is 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.5calibrates to-12.0.
Example 3
Input:
chunks = []
output_path = "batch_run_3.json"
Output:
0
File written to "batch_run_3.json":
[]
- When
chunkshas no batches at all,run_pipelinewrites an empty JSON list[]tooutput_pathand returns0.
Constraints
0 <= len(chunks) <= 10^3, and each inner chunk list contains0or more packet dictionaries.- Every packet dictionary provides
"id"(a JSON-serializable key such asintorstr),"val"(intorfloat), and an optional"corrupt"field (falsy values likeFalseor0are valid packets; truthy values raiseValueError). - On any
ValueError,output_pathmust remain uncreated if absent or untouched if a prior file already existed there.
Step-by-step walkthrough
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_chunkraisesValueError, and thatValueErrormust reach the caller ofrun_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_chunkitself is already sound: it performs pure in-memory math and raisesValueErroron corrupt packets. Every defect lives in howrun_pipelinemanages the pool and gathers outputs.- Parallel compute in workers: Each chunk is calibrated inside a worker via
Spot the defects in the broken script
Let's trace the defective
run_pipelinefrom 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:
- Return handles are discarded:
pool.apply_async(...)does not mutateresults. Instead, it immediately returns anAsyncResultobject (a receipt for a task running in the background). Dropping that receipt leavesresultspermanently empty ([]). - Worker exceptions vanish: When a worker raises
ValueError, Python catches it inside the worker and stores it inside that chunk'sAsyncResult. Because nobody calls.get()on theAsyncResult, the error is never re-raised in the parent. pool.join()runs beforepool.close():join()waits for worker processes to exit, but workers remain alive waiting for new tasks untilclose()closes the task queue. Callingjoin()on an open pool immediately raisesValueError: Pool is still running.- Missing return count: The function never returns
len(all_records). - 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.
- Return handles are discarded:
Fix 1: Save every AsyncResult handle and call .get()
When dispatching a chunk with
pool.apply_async(parse_chunk, args=(chunk,)), append the returnedAsyncResulttopending_results. Next, iterate throughpending_resultsin submission order and callasync_result.get():.get()blocks until that specific chunk completes and returns the list produced byparse_chunk.- If
parse_chunkraisedValueErrorinside the worker,.get()immediately re-raises thatValueErrorin the parent process. - Even when chunk 1 completes ahead of chunk 0, calling
pending_results[0].get()followed bypending_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_chunksFix 2: Enforce pool lifecycle order inside a with block
A
multiprocessing.Pooltransitions 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 thewithblock exits (including early exit when.get()raisesValueError),Pool.__exit__callspool.terminate(), immediately stopping any leftover workers so background processes never leak.One vital detail: keep every
.get()call inside thewithblock. Because exitingwithcallsterminate(), waiting until after thewithblock to call.get()can kill workers before they finish computing their chunks!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 thewithblock exits:- Flatten
parsed_chunksinto a single listall_records. - Open
output_pathonce in the parent process and calljson.dump(all_records, output_file). - Return
len(all_records).
Because
open(output_path, "w", ...)runs after thefor async_result in pending_results:loop, anyValueErrorabortsrun_pipelinebeforeoutput_pathis ever opened. No partial file is created, and any pre-existing file atoutput_pathstays 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)- Flatten
Fix 4: Guard the entry point and support in-memory test runners
On macOS and Windows, Python starts worker processes with the
spawnmethod: each child launches a fresh Python interpreter and imports your module to locateparse_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_chunkat module top level (never nested insiderun_pipeline), becausepickleserializes functions by module name and function name. - When code runs inside an in-memory automated judge or interactive session rather than a
.pyfile on disk, spawned child processes have no file on disk to import. Checking whether the module file exists on disk and falling back tomultiprocessing.pool.ThreadPool(which exposes the identicalapply_async/close/join/withAPI) lets both standalone.pyscripts 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)- Put any script-level demo inside
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 4Case 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.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}]]:
- Inside
with _make_pool() as pool:, we submit both chunks withapply_asyncand record their twoAsyncResulthandles inpending_results. - We call
pool.close()so workers know the queue is sealed, then callpending_results[0].get()(receiving[{"id": 101, "calibrated": 6.0}, {"id": 102, "calibrated": 18.0}]) andpending_results[1].get()(receiving[{"id": 103, "calibrated": 9.0}, {"id": 104, "calibrated": 3.75}]), followed bypool.join(). - 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 returns4.
Complexity
- Time:
O(C + R)total work across parent and workers, whereCis the number of chunks andRis the total number of packets across all chunks. We submitCtasks, calibrate each of theRpackets once across up toNUM_WORKERSprocesses, serialize each chunk and its result once viapickle(Python's built-in module for converting objects into byte streams so they can cross process boundaries), and flatten and write theRcalibrated records once in the parent, plus a fixed startup/shutdown overhead for the pool. - Space:
O(C + R)in the parent process.pending_resultsandparsed_chunksholdCentries, andparsed_chunksplusall_recordshold allRcalibrated records in memory so thatoutput_pathis only opened after every chunk succeeds.
Edge cases
chunks == [](Example 3, zero chunks): No tasks are submitted,all_recordsis[], the parent writes[]tooutput_path, andrun_pipelinereturns0.- 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'sAsyncResultre-raisesValueErrorin the parent, exiting thewithblock terminates any remaining workers, andoutput_pathis never opened or overwritten. - Falsy
"corrupt"flags (Falseor0):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_resultsin submission order preserves exact input ordering.
Common mistakes
- Discarding the return value of
pool.apply_async(...):apply_asyncreturns anAsyncResulthandle rather than mutating a list; ignoring that handle loses both computed records and raised worker exceptions. - Calling
pool.join()beforepool.close(): Workers remain open for new work untilclose()(orterminate()) runs, so CPython immediately raisesValueError: Pool is still running. - Calling
.get()after exitingwith Pool(...) as pool:: Exiting aPoolcontext manager callspool.terminate(), abruptly killing unfinished tasks; always call.get()inside thewithblock. - Having workers append directly to
output_path: Concurrent writes from separate OS processes interleave bytes and corrupt the JSON array. - Opening
output_pathwith"w"before calling.get(): Opening in write mode truncates any existing file immediately, leaving an empty or partial file behind when a worker raisesValueError. - Defining
parse_chunkas a nested function orlambda:picklelooks up functions by module-level import path, so nested functions and lambdas fail withPicklingError.
Alternative approaches
pool.map(parse_chunk, chunks)insidewith _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. Explicitapply_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 whereexecutor.submitreturns aFutureobject (the standard-library counterpart toAsyncResultwhose.result()retrieves the output or re-raises the exception) and exiting thewithblock waits cleanly for pending tasks.
Follow-up questions
- How would you redesign the pipeline when
chunksis an unbounded or multi-million-item iterator that cannot fit in RAM all at once? An OOM (out-of-memory) failure occurs whenparsed_chunksandall_recordsaccumulate too many records in RAM, so instead stream batches lazily withpool.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 viaos.replace(temp_path, output_path)(an OS operation that swaps the finished file into place all at once), removingtemp_pathin anexceptblock if any chunk fails. - What happens in
multiprocessing.Poolif a child process dies from a fatal signal likeSIGSEGVor an OS OOM kill instead of raising a Python exception, and how do you defend against it? When a worker dies abruptly from aSIGSEGV(a segmentation fault from invalid native-code memory access) or an OS OOM kill,multiprocessing.Poolstarts a replacement worker process, yet the killed task'sAsyncResultnever resolves, causing an unguarded.get()to block forever. You can prevent indefinite hangs by passing a timeout (async_result.get(timeout=30), raisingmultiprocessing.TimeoutError), or migrate toconcurrent.futures.ProcessPoolExecutor, which detects abrupt child exits and immediately fails pending futures withBrokenProcessPool. PassingmaxtasksperchildtoPoolalso recycles worker processes periodically so gradual native memory leaks do not grow into OOM kills. - When would you choose
multiprocessing.Pool.imapoverconcurrent.futures.ProcessPoolExecutor(or vice versa) in modern Python?Pool.imap(andimap_unordered) shines when lazily streaming massive iterators with built-inchunksizebatching to minimize IPC (inter-process communication) overhead, though it can hang if a worker is killed by a fatal signal.ProcessPoolExecutoroffers standardFutureobjects (supporting callbacks,as_completed, cancellation of queued work, andasynciointegration) and reliably raisesBrokenProcessPoolwhen a child crashes abruptly. For large streams inProcessPoolExecutor, submit work in bounded sliding windows or useexecutor.map(..., chunksize=...)(buffersizewas also introduced in Python 3.14 to bound in-flight 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?
- 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 would you choose `multiprocessing.Pool.imap` over `concurrent.futures.ProcessPoolExecutor` (or vice versa) in modern Python?
Similar questions
- Stream Alignment and Versioned Reconciliation for Late Telemetry
- Diagnosing Live Recall Drops and Training-Serving Skew in Telemetry ML
- Incremental Island Counts
- Greedy Speculative Decoding and Latency Benchmark
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target