Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

PydanticUserError with defer_build=True and pydantic 2.12 in multiprocess forkserver workers

Abierto
#3,079 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@SanskaarUndale21 ya está trabajando en esto.

Desde el 28/4/2026.

  • #3132 de @SanskaarUndale21 — abierto

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
48/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Tranquilo
Stack tecnológico
python
Área
api, backend

Línea de trabajo

Comienza reproduciendo el fallo de forkserver con las versiones indicadas de Python, openai, pydantic y multiprocess. Sigue openai/_models.py a través de construct(), construct_type() y _get_extra_fields_type(), y después inspecciona pydantic/_internal/_mock_val_ser.py alrededor de _get_built(). Se considera terminado cuando la deserialización de chat completion siga siendo fiable entre los workers de forkserver con ambas configuraciones de DEFER_PYDANTIC_BUILD, y exista cobertura de regresión para el fallo.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Bug Report

Summary

openai SDK 2.7.1 with pydantic 2.12.4 raises intermittent PydanticUserError ("Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly") when deserializing chat completion responses in multiprocess forkserver worker processes.

Environment
  • openai==2.7.1
  • pydantic==2.12.4
  • pydantic-core==2.41.5
  • Python 3.12
  • Using multiprocess (dill-based fork of multiprocessing) with forkserver start method
  • Backend: vLLM serving client.chat.completions.create() responses
Reproduction

The error occurs when construct() calls _get_extra_fields_type(cls) which accesses cls.__pydantic_core_schema__["type"]. This triggers MockCoreSchema._get_built() → _attempt_rebuild() → model_rebuild(raise_errors=False, _parent_namespace_depth=5).

The hardcoded _parent_namespace_depth=5 walks 5 frames up the call stack to resolve forward references. When the call stack at that depth doesn't contain the openai types module namespace, model_rebuild silently fails and pydantic raises the error.

In a forkserver setup with ~700 workers processing millions of requests:

  • With DEFER_PYDANTIC_BUILD=true (default): ~0.6% error rate, growing over time. The lazy rebuild retries on each request, mostly succeeding.
  • With DEFER_PYDANTIC_BUILD=false: ~9.5% error rate. Eager build fails at import time for ~9.5% of forkserver workers, and since the failure is cached, ALL requests for those workers fail.
Traceback
openai/_models.py:231 construct()
→ openai/_models.py:405 _construct_field()
→ openai/_models.py:570 construct_type() (iterating choices list)
→ openai/_models.py:561 construct_type() → type_.construct(**value)
→ openai/_models.py:236 construct() → _get_extra_fields_type()
→ openai/_models.py:414 _get_extra_fields_type() → schema["type"] == "model"
→ pydantic/_internal/_mock_val_ser.py:41 __getitem__() → _get_built()
→ pydantic/_internal/_mock_val_ser.py:58 _get_built() → raises PydanticUserError
Related Issues
  • #1306 (DEFER_PYDANTIC_BUILD causes issues)
  • pydantic/pydantic#11849 (race condition with model instantiation)
Suggested Fix

Explicitly calling ChatCompletion.model_rebuild() (and related response types) before creating forkserver workers resolves the issue, since the correctly-built schema is then inherited by all worker processes. The SDK could do this internally — either eagerly at import time regardless of defer_build, or by catching the PydanticUserError in _get_extra_fields_type and calling model_rebuild() as a fallback.

Lenguaje dominante
Python
Estrellas
31.8k
Forks
7.3k
Merge medio
1 d 3 h
PR fusionados (30 d)
131

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openai/openai-python

Todos los issues de openai/openai-python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.