googleapis / googleapis/python-genai

AsyncClient resource cleanup creates unawaited asyncio tasks

Open
#1,709 2 comments 0 reactions 1 assignee Assigned to @kkorpal View on GitHub
priority: p2 type: bug
Dominant language
Python
Stars
4k
Forks
1k
Avg merge
2d 11h
Merged PRs (30d)
40

Description

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.