Skip to content

v2.18 defers building Pydantic models until first use, which causes errors in a multithreaded context #2991

Open

Description

@jmazella-brr

Summary

  • Version 2.18 added defer_build=True for Pydantic validator models so the models are built on first use, not first import
  • Pydantic model_build() is not thread safe
  • When the first use of these models is in a threaded context, there is a race condition where the first thread triggers the model build and waits as other threads continue to execute. The other threads then trigger Pydantic errors because the model is not ready. Example error:
  Extra inputs are not permitted [type=extra_forbidden, input_value=1, input_type=int]
    For further information visit https://errors.pydantic.dev/2.13/v/extra_forbidden
max_output_tokens
Traceback (most recent call last):
  <original caller omitted>
  File "/venv/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3442, in invoke
    input_ = context.run(step.invoke, input_, config, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4175, in invoke
    key: future.result()
         ^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 456, in result
    return self.__get_result()
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 401, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.12/concurrent/futures/thread.py", line 59, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4158, in _invoke_step
    return context.run(
           ^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3444, in invoke
    input_ = context.run(step.invoke, input_, config)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_google_genai/chat_models.py", line 2791, in invoke
    return super().invoke(input, config, stop=stop, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 476, in invoke
    self.generate_prompt(
  File "/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 1849, in generate_prompt
    return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 1656, in generate
    self._generate_with_cache(
  File "/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 1998, in _generate_with_cache
    result = self._generate(messages, stop=stop, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/brr/brr/llm/client/llms/google_genai.py", line 77, in _generate
    return retry_decorator(super()._generate)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/tenacity/__init__.py", line 289, in wrapped_f
    return self(f, *args, **kw)
           ^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/tenacity/__init__.py", line 379, in __call__
    do = self.iter(retry_state=retry_state)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/tenacity/__init__.py", line 314, in iter
    return fut.result()
           ^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 449, in result
    return self.__get_result()
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 401, in __get_result
    raise self._exception
  File "/venv/lib/python3.12/site-packages/tenacity/__init__.py", line 382, in __call__
    result = fn(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_google_genai/chat_models.py", line 3366, in _generate
    request = self._prepare_request(
              ^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_google_genai/chat_models.py", line 3092, in _prepare_request
    params: GenerationConfig = self._prepare_params(
                               ^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/langchain_google_genai/chat_models.py", line 2835, in _prepare_params
    return GenerationConfig.model_validate(gen_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv/lib/python3.12/site-packages/pydantic/main.py", line 732, in model_validate
    return cls.__pydantic_validator__.validate_python(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Environment details

  • Programming language: Python
  • OS: All
  • Language runtime version: 3.12
  • Package version: >=2.18

Steps to reproduce

  1. Import a config, eg from google.genai.types import GenerateContentConfig
  2. Immediately spawn many threads that create new instances of GenerateContentConfig

Toy example:

def generate(model, contents):
    generate_content(GenerateContentConfig(max_output_tokens=32768, seed=42), model, contents)

from google.genai.types import GenerateContentConfig
with ThreadPoolExecutor(max_workers=max_workers) as executor:
    for model, contents in work_list:
        executor.submit(
            generate, model, contents
        )

Activity

  1. added
    type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.
    priority: p2Moderately-important priority. Fix may not be included in next release.
    on Sep 21, 2026
  2. Venkaiahbabuneelam commented on Sep 22, 2026

    @Venkaiahbabuneelam

    Hi @jmazella-brr, Thanks for reaching out us!

    You've accurately identified a race condition stemming from Pydantic v2's deferred model building (defer_build=True) in a multithreaded environment, where model_build() is not thread-safe. This causes validation errors when multiple threads attempt to initialize GenerateContentConfig concurrently for the first time.
    We tested the multithreaded scenario locally and we didn't encouner any errors, Please check and let us know if it resolves the issue for you.
    If issue is still presist can you please provide me full reproducible code for reference.

    Thanks

  3. jmazella-brr commented on Sep 24, 2026

    @jmazella-brr
    Author

    @Venkaiahbabuneelam Yes I am still seeing the problem. Here is a self contained test script that shows the issue:

    """Minimal reproduction for googleapis/python-genai#2991 targeting ValidationError."""
    
    import multiprocessing as mp
    import sys
    import threading
    import pydantic
    
    THREADS = 150
    MAX_ATTEMPTS = 40
    
    
    def _worker(result_queue):
        try:
            from google.genai.types import GenerateContentConfig
            # Rebuild parent models to make the original validation error more likely
            for config in (GenerateContentConfig,):
                for base in config.__mro__[1:]:
                    if issubclass(base, pydantic.BaseModel) and base is not pydantic.BaseModel:
                        base.model_rebuild()
            # Increase chances of hitting the race condition
            sys.setswitchinterval(1e-9)
    
            validation_errors = []
            lock = threading.Lock()
            start = threading.Event()
    
            def build():
                start.wait()
                try:
                    GenerateContentConfig(max_output_tokens=1, seed=42)
                except Exception as exc:
                    with lock:
                        validation_errors.append(
                            f"{type(exc).__name__}: {str(exc)}"
                        )
            threads = [threading.Thread(target=build) for _ in range(THREADS)]
            for t in threads:
                t.start()
            start.set()
            for t in threads:
                t.join()
    
            result_queue.put(validation_errors)
        except Exception as e:
            result_queue.put([f"Worker Error: {e}"])
    
    
    def main():
        ctx = mp.get_context("spawn")
        for attempt in range(1, MAX_ATTEMPTS + 1):
            print(f"Starting attempt {attempt}...")
            queue = ctx.Queue()
            process = ctx.Process(target=_worker, args=(queue,))
            process.start()
    
            try:
                errors = queue.get(timeout=60)
            except Exception:
                errors = "Process timed out"
    
            process.join()
    
            for error in errors:
                print(f"ERROR:\n    {error}")
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    

    Here's the output i saw running it :

    Starting attempt 1...
    ERROR:
        AttributeError: type object 'GenerateContentConfig' has no attribute '__pydantic_core_schema__'
    Starting attempt 2...
    Starting attempt 3...
    ERROR:
        AttributeError: type object 'GenerateContentConfig' has no attribute '__pydantic_core_schema__'
    Starting attempt 4...
    Starting attempt 5...
    Starting attempt 6...
    ERROR:
        ValidationError: 2 validation errors for BaseModel
    max_output_tokens
      Extra inputs are not permitted [type=extra_forbidden, input_value=1, input_type=int]
        For further information visit https://errors.pydantic.dev/2.13/v/extra_forbidden
    seed
      Extra inputs are not permitted [type=extra_forbidden, input_value=42, input_type=int]
        For further information visit https://errors.pydantic.dev/2.13/v/extra_forbidden
    Starting attempt 7...
    ERROR:
        AttributeError: type object 'GenerateContentConfig' has no attribute '__pydantic_core_schema__'
    Starting attempt 8...
    Starting attempt 9...
    Starting attempt 10...
    
    
  4. Venkaiahbabuneelam commented on Sep 25, 2026

    @Venkaiahbabuneelam

    Hi @jmazella-brr, Thank you for bringing this to our attention. We truly appreciate you flagging this issue.

    We are forwarding this issue to Our engineering team will investigate the thread-safety race condition caused by deferred Pydantic model building (defer_build=True) in multithreaded environments. We will update you here as soon as possible.
    Thanks

  5. added a commit that references this issue on Oct 2, 2026
  6. added a commit that references this issue on Oct 28, 2026
    292a2ba
  7. added 2 commits that reference this issue on Nov 5, 2026
    c766056
    e393dae
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions