# RuntimeError: Semaphore released too many times

- **ID:** `python/asyncio-invalid-state-semaphore`
- **Domain:** python
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A semaphore was released more times than it was acquired, often due to releasing in a finally block without checking if acquired.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |
| 3.10 | active | — | — |

## Workarounds

1. **Use context manager for semaphore to ensure proper acquire/release** (95% success)
   ```
   async with semaphore: await some_coroutine()
   ```
2. **Use a try-finally block with a flag to track acquisition** (90% success)
   ```
   acquired = await semaphore.acquire(); try: await some_coroutine(); finally: if acquired: semaphore.release()
   ```

## Dead Ends

- **Increasing the initial semaphore value** — This masks the bug but does not fix the logic; over-release still occurs. (60% fail)
- **Using semaphore.acquire() without await** — acquire() returns a coroutine; not awaiting it leads to incorrect behavior. (80% fail)
