Complete worked example
python
import asyncio
def concurrent_labels(items):
if not isinstance(items, list) or len(items) > 20 or any(not isinstance(item, str) for item in items):
raise ValueError("text list required")
async def run():
semaphore = asyncio.Semaphore(2)
active, peak = 0, 0
async def job(item):
nonlocal active, peak
async with semaphore:
active += 1
peak = max(peak, active)
try:
await asyncio.sleep(0)
if item == "FAIL":
raise ValueError("controlled job failure")
return item.upper()
finally:
active -= 1
async with asyncio.TaskGroup() as group:
tasks = [group.create_task(job(item)) for item in items]
return {"labels": [task.result() for task in tasks], "peak": peak}
return asyncio.run(run())- Reasoning
- Run cooperative jobs under one shared semaphore while retaining input order and propagating an incomplete group failure. Compare the stated values and failure boundary before changing the implementation.