Aggregate Parallel Pipeline Results Safely
Arrays & HashingAuto-graded · 16 test casesLast updated
Fix async pool usage so results are collected in order, worker errors surface, and one JSON file is written.
Task
You are given a broken batch-processing routine. It is meant to split a list of chunks of raw sensor records across a pool of worker processes, transform each record, and then write every transformed record as a single JSON array to a file. The current code loses results, swallows worker failures, and can leave the output file empty or missing.
Implement run_pipeline(chunks, output_path) so it does the following, reliably:
- Parallel transform with collection. Each chunk is a list of records. A record is a dict with keys
"id"(any JSON-serializable value) and"val"(a number). A record may also contain the key"corrupt"; ifrecord["corrupt"]is truthy, the chunk must be treated as invalid and processing must fail (see rule 2). - Exception propagation. If any chunk contains a corrupt record, a
ValueErrormust be raised fromrun_pipelinerather than being swallowed. In that case the output file must not be created or modified by this call. - Single writer. Worker processes only compute; the parent process must collect all transformed records, flatten them in the original input order (chunks in the order given, records in the order within each chunk), and write exactly one JSON array to
output_path. - Correct transform. For each valid record, the transformed record is a dict
{"id": record["id"], "calibrated": record["val"] * 1.5}. No other keys appear in the output.
Return the total number of records written.
Notes:
- The parent should write the file using
json.dumpof a Python list of transformed dicts. - Preserve input order in the output array.
- If
chunksis empty, write an empty JSON list[]and return0. - A chunk containing zero records contributes nothing.
- Missing keys (
"id"or"val") are allowed to propagate as errors; the output file then must not be written.
Constraints
0 <= len(chunks)- Each chunk is a list of dict records; total record count is
0 <= N. "val"is a finite number;"id"is JSON-serializable.output_pathis a writable file path.- The function must be safe to run at module level (guard any driver code with
if __name__ == "__main__":). - Do not write to the file from worker processes.
Examples
Example 1
Input: run_pipeline([[{'id': 1, 'val': 10}, {'id': 2, 'val': 20}], [{'id': 3, 'val': 30}]], 'telemetry_sample_1.json')
Output: 3
Example 2
Input: run_pipeline([], 'telemetry_sample_2.json')
Output: 0
Example 3
Input: run_pipeline([[{'id': 1, 'val': 7.5}]], 'telemetry_sample_3.json')
Output: 1
Hints
Hint 1
A pool's async results are only available if you keep the AsyncResult handles; a blocking map collects and re-raises for you.
Hint 2
Pool.close() must be called before Pool.join(); using a context manager avoids getting the order wrong.
Hint 3
Flatten the per-chunk results in the parent, then open the file once and json.dump the flattened list.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The buggy version dispatches tasks with apply_async but throws away the returned AsyncResult objects, so no worker return values are ever collected. It also calls join() before close(), which raises immediately, and it never calls .get(), so worker-side exceptions vanish. The fix is to use pool.map, which blocks until all chunks finish, returns the results in input order, and re-raises any exception raised inside a worker.
The parent process handles all I/O:
- Enter a
with Pool(processes=4) as pool:block, which handles shutdown correctly (no manual close/join ordering mistakes). - Call
pool.map(parse_chunk, chunks). This runs the transform in parallel and returns one list per chunk, in order. - Flatten the lists in the parent into a single list.
- Open
output_pathonce andjson.dumpthe flattened list. - Return the count of records.
If a chunk holds a corrupt record, parse_chunk raises ValueError inside a worker; pool.map re-raises it in the parent, the with block terminates the pool, and the open(...) line is never reached — so the file is untouched. The parse_chunk function must stay at module top level so it can be pickled and shipped to workers.
Why it is correct
- Completeness:
mapreturns only after every chunk is processed, and flattening collects every transformed record. - Order:
mappreserves input order, so the output array matches the input ordering of chunks and records. - Errors: Worker exceptions propagate out of
map; the output file is written only aftermapsucceeds. - Single writer: Only the parent opens the file, so no interleaved or partial writes occur.
- Empty input:
mapover an empty list returns[], which is written as[]and returns0.
Complexity
- Time: O(N) total work over N records (distributed across up to 4 workers), plus O(N) parent overhead for unpickling and flattening.
- Space: O(N) in the parent, since all transformed records are held in memory before writing.