Repository navigation
Description
Component: BigQueryAgentAnalyticsPlugin
Severity: High (Breaks common multiprocessing patterns on Linux)
Environment: Linux (where multiprocessing defaults to fork), Python 3.10+
Summary
The BigQueryAgentAnalyticsPlugin causes deadlocks and TimeoutErrors when used with concurrent.futures.ProcessPoolExecutor on Linux.
This occurs because the plugin initializes a BigQueryWriteAsyncClient (and its underlying gRPC channel) immediately in its init method. The standard Python grpc library is not fork-safe. When a process forks (default start method on Linux), the child process inherits the parent's memory, including the already-open (and now broken) gRPC channel, leading to hangs or timeouts when the child tries to use it.
Root Cause Analysis
- Eager Initialization:
BigQueryAgentAnalyticsPlugin.__init__createsself.write_client = BigQueryWriteAsyncClient(...). This establishes a gRPC channel in the parent process. - Fork Safety: On Linux,
multiprocessing.Process(andProcessPoolExecutor) defaults tofork(). The child process inherits the parent's address space. - gRPC Deadlock: The inherited gRPC channel is in a bad state in the child process. Any attempt to use it (even just waiting for connectivity) results in a deadlock or
TimeoutError(after 30s).
Why It Works on macOS / Windows
- macOS / Windows: The default multiprocessing start method is
spawn. - Spawn Behavior:
spawnstarts a fresh Python interpreter process. The module is re-imported, and the BigQueryAgentAnalyticsPlugin is re-instantiated, creating a new, clean gRPC channel in the child process. This is safe. - Linux: Defaults to
fork. The child inherits the existing, unsafe parent channel.
Reproduction Code (Broken on Linux)
This pattern is common in agent applications where plugins are instantiated globally or at the module level.
# broken_example.py
from google.adk.plugins.bigquery_agent_analytics_plugin import BigQueryAgentAnalyticsPlugin, BigQueryLoggerConfig
import concurrent.futures
import asyncio
# 1. Global/Module-level instantiation creates gRPC channel in PARENT process
plugin = BigQueryAgentAnalyticsPlugin(
project_id="my-project",
dataset_id="logging",
table_id="events",
config=BigQueryLoggerConfig(enabled=True)
)
async def worker_task():
# 3. Child process attempts to use the INHERITED parent plugin/channel
# RESULT: HANGS or TIMEOUTS on Linux (fork)
await plugin.log_event(...)
def worker_wrapper():
asyncio.run(worker_task())
if __name__ == "__main__":
# 2. ProcessPoolExecutor uses fork() on Linux by default
with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor:
executor.submit(worker_wrapper)Workaround (User Side)
Users can force Linux to use spawn instead of fork to match macOS behavior and avoid the issue.
# fixed_example.py
import multiprocessing
import concurrent.futures
if __name__ == "__main__":
# FORCE 'spawn' context to create fresh processes/channels
mp_context = multiprocessing.get_context('spawn')
with concurrent.futures.ProcessPoolExecutor(max_workers=2, mp_context=mp_context) as executor:
executor.submit(worker_wrapper)Recommended Library Fix
The plugin should lazily initialize the gRPC client. Do not create self.write_client in [init]
Initialize it only when needed (inside the running process).
Proposed Change:
class BigQueryAgentAnalyticsPlugin(BasePlugin):
def __init__(self, ...):
# self.write_client = BigQueryWriteAsyncClient(...) <-- REMOVE THIS
self._write_client = None
@property
async def write_client(self):
if self._write_client is None:
# Create channel ONLY when needed (inside the correct process)
self._write_client = BigQueryWriteAsyncClient(...)
return self._write_client
Activity
Fix BigQuery write deadlock on Linux (use 'spawn' content)
fix: add fork-safety and auto-create analytics views to BQ plugin
Fix BigQuery write deadlock on Linux (use 'spawn' content)
caohy1988 commentedon Feb 28, 2026
BigQueryAgentAnalyticsPluginso that forked child processes detect stale gRPC channels and re-initialize instead of deadlocking. Uses the standardos.getpid()pattern (same as SQLAlchemy, gRPC-python).feat: Enhance BQ plugin with fork safety, auto views, and trace conti…
haiyuan-eng-google commentedon Mar 2, 2026
fixed
evekhm commentedon Mar 3, 2026
BigQuery Plugin TimeoutError Reproduction
I've attached two minimal, standalone scripts to this issue to reproduce and demonstrate the issue (still) for a
TimeoutErrorthat occurs when using the ADKBigQueryAgentAnalyticsPluginwith Python'sProcessPoolExecutoron Linux.The Bug:
minimal_bq_agent_multiprocessing.pyWhen ADK Agents with the BigQuery plugin are executed across multiple workers using
concurrent.futures.ProcessPoolExecutoron Linux, the background BigQuery Write API task silently hangs and eventually throws anasyncio.TimeoutErrorafter 30 seconds.Why this happens:
On Linux,
ProcessPoolExecutordefaults to theforkstart method. If any Google Cloud / gRPC objects are initialized in the parent process (e.g., by importing the root agent at the top level), theforkoperation copies this state into the child workers. However, it does not copy the background threads managing the gRPC channels. This results in the child's gRPC connections being permanently corrupted, causing the BQ plugin's flush operations to hang indefinitely.How to run the reproduction:
# Requires an environment with ADK installed python3 minimal_bq_agent_multiprocessing.pyExpected Output: The LLM query will finish immediately, but the script will hang for 30 seconds before printing
Error: TimeoutError().The Fix:
minimal_bq_agent_multiprocessing_fixed.pyThis script is identical to the broken one, but applies the standard Python fix for gRPC multiprocessing issues: using the
spawncontext.By explicitly telling the executor to use
mp_context=multiprocessing.get_context('spawn'), Linux launches a fresh Python interpreter for each worker instead offorking. This allows the child process to initialize its own clean gRPC connections.How to run the fix:
# Requires an environment with ADK installed python3 minimal_bq_agent_multiprocessing_fixed.pyExpected Output: The LLM query will finish, and the BQ plugin will successfully log the event to BigQuery and exit immediately without any hangs or timeouts.
bq_plugin_timeout_repro.zip
caohy1988 commentedon Mar 4, 2026
Thanks for the excellent reproduction scripts @evekhm — they were very helpful for diagnosing this.
You're right that the root cause is gRPC corruption after
fork(). We've added defense-in-depth mitigations in PR #4695 (commits16819c98,f8cf4c9f):GRPC_ENABLE_FORK_SUPPORT=1set before gRPC's C-core loads — fixes unary gRPC calls (table creation, schema checks) in forked children.os.register_at_forkhandler — proactively resets all plugin instances in the child immediately after fork._reset_runtime_state().spawn.However, our testing confirmed what your repro demonstrates: gRPC bidirectional streaming (used by the BigQuery Storage Write API's
append_rows) is fundamentally not fork-safe — even withGRPC_ENABLE_FORK_SUPPORT=1. The env var only covers the C-core channel layer, not the Python-levelgrpc.aioPollerCompletionQueue, which is stored in an inaccessible Cython global and has no fork handler. This means:spawnmultiprocessingfork+ unary gRPC (schema ops)fork+ bidi streaming (append_rows)Your fix (
spawncontext) is the correct and recommended solution. We've updated the plugin's fork-detection warning to guide users toward this:This is a gRPC-level limitation that can't be worked around from the plugin side. The
spawnapproach avoids it entirely by starting fresh Python interpreters.feat: Enhance BQ plugin with fork safety, auto views, and trace conti…