googleapis / googleapis/python-genai

AsyncClient resource cleanup creates unawaited asyncio tasks

Aperta
#1,709 2 commenti 0 reazioni 1 assegnatario Assegnata a @kkorpal Vedi su GitHub
priority: p2 type: bug
Lingua principale
Python
Stelle
4k
Fork
1k
Merge medio
2g 12h
PR unite (30g)
41

Descrizione

This is a **client library issue**. The `AsyncClient.__del__` method in the genai Python client library creates unawaited asyncio tasks during garbage collection.

#### Environment details
- Programming language: Python
- OS: macOS (Darwin 24.6.0), also reproduces on Linux
- Language runtime version: Python 3.12.7
- Package version: google-genai==1.50.1

#### Steps to reproduce
1. Create a genai.Client instance
2. Properly close it with `await client.aio.aclose()`
3. Let the client be garbage collected
4. Observe asyncio warning: "Task was destroyed but it is pending!"

**Minimal reproduction code:**
```python
import asyncio
import google.genai as genai
async def test_client_cleanup():
# Create a client
client = genai.Client(
vertexai=True,
project="your-project-id",
location="us-central1"
)
# Use the client
await client.aio.models.generate_content(
model="gemini-2.5-flash",
contents="Hello"
)

# Properly close the async client
await client.aio.aclose()

# When client is garbage collected, __del__ creates unawaited task

asyncio.run(test_client_cleanup())
```

Error output:
asyncio - ERROR - Task was destroyed but it is pending!
task: >

Root cause
In google/genai/client.py (lines 134-138), the AsyncClient.__del__ method:

def __del__(self) -> None:
try:
asyncio.get_running_loop().create_task(self.aclose())
except Exception:
pass

This creates an asyncio task but never awaits it. Even when users properly call await client.aio.aclose(), the __del__ method still runs during garbage collection and creates another unawaited task.

Expected behavior
When a client is properly closed with await client.aio.aclose(), no warnings should occur during
garbage collection.

Actual behavior
The warning appears even after proper cleanup, making it difficult to identify real asyncio issues in
production applications.

Context

This issue is particularly problematic in long-running async applications (FastAPI, aiohttp servers)
that use the genai client, where proper resource cleanup is critical for stability.

Thanks

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.