Skip to content

BigQueryAgentAnalyticsPlugin Deadlock on Linux Multiprocessing #4636

Closed

Description

@evekhm

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

  1. Eager Initialization: BigQueryAgentAnalyticsPlugin.__init__ creates self.write_client = BigQueryWriteAsyncClient(...). This establishes a gRPC channel in the parent process.
  2. Fork Safety: On Linux, multiprocessing.Process (and ProcessPoolExecutor) defaults to fork(). The child process inherits the parent's address space.
  3. 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: spawn starts 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

  1. added
    bq
    on Feb 26, 2026
  2. added theissue type on Feb 26, 2026
  3. caohy1988 commented on Feb 28, 2026

    @caohy1988
  4. haiyuan-eng-google commented on Mar 2, 2026

    @haiyuan-eng-google
    Collaborator

    fixed

  5. evekhm commented on Mar 3, 2026

    @evekhm
    Author

    BigQuery Plugin TimeoutError Reproduction

    I've attached two minimal, standalone scripts to this issue to reproduce and demonstrate the issue (still) for a TimeoutError that occurs when using the ADK BigQueryAgentAnalyticsPlugin with Python's ProcessPoolExecutor on Linux.

    The Bug: minimal_bq_agent_multiprocessing.py

    When ADK Agents with the BigQuery plugin are executed across multiple workers using concurrent.futures.ProcessPoolExecutor on Linux, the background BigQuery Write API task silently hangs and eventually throws an asyncio.TimeoutError after 30 seconds.

    Why this happens:
    On Linux, ProcessPoolExecutor defaults to the fork start method. If any Google Cloud / gRPC objects are initialized in the parent process (e.g., by importing the root agent at the top level), the fork operation 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.py

    Expected 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.py

    This script is identical to the broken one, but applies the standard Python fix for gRPC multiprocessing issues: using the spawn context.

    By explicitly telling the executor to use mp_context=multiprocessing.get_context('spawn'), Linux launches a fresh Python interpreter for each worker instead of forking. 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.py

    Expected 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

  6. caohy1988 commented on Mar 4, 2026

    @caohy1988

    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 (commits 16819c98, f8cf4c9f):

    1. GRPC_ENABLE_FORK_SUPPORT=1 set before gRPC's C-core loads — fixes unary gRPC calls (table creation, schema checks) in forked children.
    2. os.register_at_fork handler — proactively resets all plugin instances in the child immediately after fork.
    3. Best-effort inherited channel cleanup in _reset_runtime_state().
    4. Actionable fork-detection warning logged at runtime guiding users to 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 with GRPC_ENABLE_FORK_SUPPORT=1. The env var only covers the C-core channel layer, not the Python-level grpc.aio PollerCompletionQueue, which is stored in an inaccessible Cython global and has no fork handler. This means:

    Scenario Result
    No fork / spawn multiprocessing Works (< 1s)
    fork + unary gRPC (schema ops) Works with our fix
    fork + bidi streaming (append_rows) Hangs — gRPC library limitation

    Your fix (spawn context) is the correct and recommended solution. We've updated the plugin's fork-detection warning to guide users toward this:

    "Fork detected ... configure the 'spawn' start method at your program entry-point before creating child processes: multiprocessing.set_start_method('spawn')"

    This is a gRPC-level limitation that can't be worked around from the plugin side. The spawn approach avoids it entirely by starting fresh Python interpreters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bq

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions