Controlled report preparation with Python 3.11 TaskGroup
A Python exercise for collecting mandatory report inputs, cancelling sibling work after a failure, and preparing only complete results for publication.
Archive retrospective · Topic year 2022
In this article
Define when a report is ready
A sales report may obtain order rows from one system and a source manifest from another. Downloaded rows are insufficient to identify the source batch for a close. Publishing before the manifest is validated can admit a replay as fresh data. Define both inputs as mandatory parts of one preparation scope and produce a publishable result only after they complete. Capture invalid business data separately from failures in infrastructure. Python 3.11 was released on October 24, 2022. Its asyncio TaskGroup and the language's exception-group handling make this kind of shared lifetime explicit. This fixture has one order reader and one manifest check. Their lifetimes belong to report preparation. The step that makes a completed report visible remains outside that scope. The boundary leaves room for explicit checks of what is available to the caller after a preparation failure.
Observe starts and cleanup
Use an event to schedule the demonstration instead of guessing how two sleeps will behave. The order reader signals that it has started. The manifest checker waits for that signal before raising an error, so the failure arrives after the reader has entered its cleanup scope. In the rejection case the reader remains at a cancellable wait. A non-cancellation error in one task causes TaskGroup to cancel unfinished siblings and wait for them before leaving the context. The reader records its cleanup in a finally clause. A production reader might close a stream or release a temporary file handle in the same place. That cleanup event establishes that control reached the clause. It does not verify downloaded data. Calls that block an event loop or do not cooperate with cancellation can still delay completion. Measure the interval from the first failure to resource closure.
Reproduce both outcomes
The program first runs a valid preparation, then one with a missing batch identifier. The reader returns eighteen rows in the first case, the manifest supplies batch-42, and the result includes both. In the second case the manifest raises InvalidManifest while the reader is waiting. The task group cancels the reader and the preparation returns a rejection. Its tuple omits the batch ID and count. Both runs record that the reader closed. Run this script with Python 3.11 or later. It requires no network access. The explicit task assertion checks that the failed case exercised cancellation. The except-star clause handles the known data rejection. If another exception accompanies it, the unhandled part can still propagate to the caller. Separating these classes prevents an operator from treating a parser defect as routine source data. In a real report, explicitly verify that the two successful inputs describe the same cutoff.
import asyncio
class InvalidManifest(Exception):
pass
async def prepare(reject):
reader_started = asyncio.Event()
lifecycle = []
async def read_orders():
reader_started.set()
try:
if reject:
await asyncio.Event().wait()
return 18
finally:
lifecycle.append("reader closed")
async def check_manifest():
await reader_started.wait()
if reject:
raise InvalidManifest("missing batch identifier")
return "batch-42"
rejected = False
try:
async with asyncio.TaskGroup() as batch:
orders = batch.create_task(read_orders())
manifest = batch.create_task(check_manifest())
except* InvalidManifest:
rejected = True
if rejected:
assert orders.cancelled()
return ("rejected", tuple(lifecycle))
return ("ready", manifest.result(), orders.result(), tuple(lifecycle))
async def main():
good = await prepare(False)
bad = await prepare(True)
assert good == ("ready", "batch-42", 18, ("reader closed",))
assert bad == ("rejected", ("reader closed",))
print(good)
print(bad)
asyncio.run(main())
Design a publication boundary
A real reader might write intermediate results to disk or object storage. Cancelling an asyncio task cannot reverse bytes already written to a separate service. Give each preparation attempt a temporary workspace and define which artifacts are removed immediately and which are found by later cleanup. When all tasks finish, check counts, cutoff times, and the batch identity again before promoting anything. The publication step can write a transaction-backed record or update a pointer using the guarantees of the chosen store. A file replacement operation and a multi-call object-store transfer have different semantics. Exercise a failure during that promotion to check what a reader can still open. A valid previous report should remain addressable until a complete new report can be selected. Give each publication a unique batch identity if a successful attempt may be retried after the response is lost.
Separate timeouts from invalid inputs
A five-minute report budget has to cover preparation, cleanup, verification, and publication. Leave some time available for the final stages instead of assigning the entire budget to the upstream reads. Record validation duration, remote wait, and time from cancellation to resource closure independently. A bad manifest normally needs repaired input. A temporary connection failure may justify a retry within the remaining budget. Test an external timeout as well as a source-data failure, since task cancellation can also come from shutdown or the supervising job. Catch only the exception group members that the application knows how to classify. An unexpected failure should remain visible to the supervising process. Record the source identity and the attempt ID alongside diagnostic events. That context helps explain whether repeated failures concern one malformed batch or multiple independent requests. These checks belong beside the deterministic fixture when real I/O is introduced.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment