Fix for the discriminator cache race in #4036 (thread-safe model build), ready on a fork branch
維護者通常 1 天內回覆
還沒有人認領這個 Issue。
評估
研究方向
Read src/openai/_models.py and the concurrency regression tests in tests/test_models.py; compare the proposed fork branch and the related discussion in #4036. Start by checking how model builds and discriminator schema reads interact across the supported Pydantic versions. Done means concurrent first use no longer produces incomplete discriminator mappings or misdecoded events, with the regression tests passing and compatibility preserved.
由索引模型根據 Issue 內容生成。
描述
Confirm this is an issue with the Python library and not an underlying OpenAI API
- This is an issue with the Python library
Describe the bug
#4036 (concurrent first use of streaming decode caches an incomplete discriminator map) still reproduces on openai 3.55.1 (current main). I've put a fix on a fork branch that maintainers can pick up directly:
https://github.com/AkkiaS7/openai-python/tree/fix/thread-safe-model-build
It's one commit on top of main and only touches src/openai/_models.py and tests/test_models.py. It makes the first build of each model thread-safe on Pydantic < 2.14, which ports the fix already shipped in the Anthropic Python SDK (details below). The repo doesn't accept outside PRs, so I haven't opened one.
Root cause
Before Pydantic 2.14, model_rebuild() isn't thread-safe. As far as I can tell from Pydantic's source, when two threads rebuild the same model, one can delattr(cls, '__pydantic_core_schema__') while the other is building it. In the meantime, Variant.__pydantic_core_schema__ resolves through the MRO to the parent's schema, or is briefly missing. I haven't proven that exact interleaving. What I did observe: logging what _extract_field_schema_pv2 reads for the variants that get skipped shows a fully built schema whose cls is openai.BaseModel, the parent class, with no fields.
Pydantic 2.14 added a lock around model_rebuild() (pydantic.main._rebuild_lock), and the race didn't reproduce in my trials on 2.14.0 and 2.14.3.
Affected versions
The SDK allows pydantic>=1.10.13,<3, excluding 2.0–2.3. In my runs:
- Affected: the tested 2.8–2.13 releases (2.8.2, 2.9.2, 2.10.6, 2.11.10, 2.12.5, 2.13.5). Trials with mis-decoded events: 10/10 for 2.8.2 and 2.10.6, 30/30 for the others.
- Not reproduced: the sampled 2.4.2, 2.5.3, 2.6.4 and 2.7.4 releases, and 2.14.0 / 2.14.3.
- I didn't check where between 2.7 and 2.8 the change happened. Pydantic v1 wasn't tested for the race.
The fix (on the fork branch)
The Anthropic Python SDK has the same _models.py and already fixed this ("fix(client): make the first parse of each response model thread-safe", anthropics/anthropic-sdk-python@00a23c7). The branch above ports that fix:
- Pydantic < 2.14: override
BaseModel.model_rebuild()with one reentrant lock, which is reset afterfork. - Pydantic v2 schema reads: read a model's own core schema only after its build has finished.
- Pydantic ≥ 2.14: the override is skipped. The override only exists in the Pydantic v2 branch of
BaseModel.
Results with the port (Linux; Python 3.10.16 and the repo's locked pydantic 2.12.5 unless noted):
-
Repro: 0/30 on pydantic 2.4.2, 2.9.2, 2.13.5 and 2.14.3 (Python 3.11).
-
New tests: two concurrency regression tests.
- The discriminator-map test uses events and deliberately removes the variant's own core schema during a blocked build to simulate the inherited-parent-schema state. It does not reproduce Pydantic's actual deletion interleaving.
- The first-construct test uses events plus a short sleep to observe whether construction finishes before the blocked build is released.
- Each failed in 30 of 30 separate runs on unpatched
mainand passed in 30 of 30 with the port, withDEFER_PYDANTIC_BUILDbothfalseandtrue. They also passed 30/30 on pydantic 2.14.3, where the override isn't installed.
-
Lint and tests:
ruff checkandty checkpass. The pydantic v1 lane of the full suite passes. -
Full suite failures: the full suite ran on an earlier revision of the patch. The source was identical, and the discriminator-map test was changed afterwards. Both runs used
DEFER_PYDANTIC_BUILD=false(as inscripts/test) and pytest-xdist. Each of the two pydantic v2 runs had one failure, a different test each time:test_fractional_source_deadlines[async]: a 5-second subprocess timeout.test_google_auth_preserves_transport_timeout_phases[0.001-1.0-False]: refresh call count 2 vs 1.
Both passed when rerun on their own. I haven't run the full suite on unpatched
main, so I can't rule the port out for these. My guess is that they're timing-related, but I haven't verified it.
Notes on the patches proposed in #4036
Thanks to everyone who posted patches in #4036; they helped narrow this down. I tested both on openai 3.55.1 with pydantic 2.13.5, using the repro below (16 threads, a fresh process per trial, 30 trials). There are cases they don't cover yet, which is why the branch above makes the fix in model_rebuild() instead:
- Skip caching when the variant's schema isn't built (the
_has_built_model_schemacheck): the mapping was still incomplete and events still mis-decoded in 30/30 trials.- As noted under Root cause, the skipped variants weren't actually unbuilt: they read the parent's fully built schema.
- That schema passes the
model/model-fieldscheck, so the incomplete mapping is still cached.
- A lock around
_build_discriminated_union_meta: 0/30 when every thread only decodes stream events.- With a mixed workload, it still cached an incomplete mapping in 29/30 trials: half the threads decode, and the other half call
model_validateon the event classes. The second script is below. - The lock covers that function, but not rebuilds started elsewhere.
- With a mixed workload, it still cached an incomplete mapping in 29/30 trials: half the threads decode, and the other half call
Workarounds until a fix ships: upgrade to pydantic>=2.14, or set DEFER_PYDANTIC_BUILD=false before importing openai (slower import).
To Reproduce
python -m pip install "openai==3.55.1" "pydantic==2.13.5"- Save the script below as
repro.pyand runpython repro.py. It needs no network or API key, and each trial runs in a fresh process. - On affected versions, most trials report events decoded as
ResponseAudioDeltaEvent, and a cached mapping smaller than the number of union members. - Optional: for the mixed workload, save the second script as
repro_mixed.pyand runpython repro_mixed.py 30 16(30 trials, 16 threads).
Code snippets
"""Minimal reproduction: concurrent first use of a discriminated union in openai-python.
Each trial runs in a fresh subprocess so the discriminator cache and the
pydantic models are built for the first time. N threads wait on a barrier and
then call `construct_type` on the Responses stream event union at the same
time. The payloads intentionally fail strict validation (as partial events from
some OpenAI-compatible servers do), so `construct_type` falls back to the
discriminator mapping.
Usage:
python repro_discriminator_race.py --trials 30 --threads 16
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import threading
PAYLOADS = [
{"type": "response.created", "sequence_number": 0, "response": {"id": "r1", "status": "in_progress"}},
{"type": "response.in_progress", "sequence_number": 1, "response": {"id": "r1", "status": "in_progress"}},
{
"type": "response.output_item.added",
"sequence_number": 2,
"output_index": 0,
"item": {"type": "message", "id": "m1", "role": "assistant", "status": "in_progress"},
},
{
"type": "response.output_item.done",
"sequence_number": 3,
"output_index": 0,
"item": {"type": "message", "id": "m1", "role": "assistant", "status": "completed"},
},
{"type": "response.completed", "sequence_number": 4, "response": {"id": "r1", "status": "completed"}},
]
EXPECTED = {
"response.created": "ResponseCreatedEvent",
"response.in_progress": "ResponseInProgressEvent",
"response.output_item.added": "ResponseOutputItemAddedEvent",
"response.output_item.done": "ResponseOutputItemDoneEvent",
"response.completed": "ResponseCompletedEvent",
}
def child(threads: int) -> None:
import typing
import openai
import pydantic
from openai._models import DISCRIMINATOR_CACHE, construct_type
from openai.types.responses import ResponseStreamEvent
barrier = threading.Barrier(threads)
results: list[tuple[str, str]] = []
lock = threading.Lock()
def worker(i: int) -> None:
barrier.wait()
local = []
for payload in PAYLOADS[i % len(PAYLOADS) :] + PAYLOADS[: i % len(PAYLOADS)]:
event = construct_type(type_=ResponseStreamEvent, value=dict(payload))
local.append((payload["type"], type(event).__name__))
with lock:
results.extend(local)
ts = [threading.Thread(target=worker, args=(i,)) for i in range(threads)]
for t in ts:
t.start()
for t in ts:
t.join()
union = typing.get_args(ResponseStreamEvent)[0]
details = DISCRIMINATOR_CACHE.get(union)
print(
json.dumps(
{
"openai": openai.__version__,
"pydantic": pydantic.VERSION,
"mapping_size": len(details.mapping) if details else None,
"variants": len(typing.get_args(union)),
"misparsed": sorted({f"{t}->{c}" for t, c in results if EXPECTED[t] != c}),
}
)
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--trials", type=int, default=30)
parser.add_argument("--threads", type=int, default=16)
parser.add_argument("--child", action="store_true")
args = parser.parse_args()
if args.child:
child(args.threads)
return
bad = short = 0
last = {}
for n in range(1, args.trials + 1):
out = subprocess.run(
[sys.executable, __file__, "--child", "--threads", str(args.threads)],
capture_output=True,
text=True,
check=True,
)
line = out.stdout.strip().splitlines()[-1]
last = json.loads(line)
bad += bool(last["misparsed"])
short += last["mapping_size"] != last["variants"]
print(f"trial {n:02d}: {line}", flush=True)
print(
f"SUMMARY openai={last.get('openai')} pydantic={last.get('pydantic')} threads={args.threads} "
f"trials={args.trials} misparsed_trials={bad} incomplete_mapping_trials={short}"
)
if __name__ == "__main__":
main()
Mixed-workload script (decoding plus direct use of the event classes)
Run with python repro_mixed.py 30 16 (30 trials, 16 threads).
"""Mixed workload: half the threads decode stream events via construct_type (fallback path),
the other half use the event classes directly (first strict validation of each class).
Reports whether the cached discriminator mapping ends up incomplete. Fresh process per trial."""
import json, subprocess, sys, threading
def child(n):
import typing
from openai._models import DISCRIMINATOR_CACHE, construct_type
from openai.types.responses import ResponseStreamEvent
union = typing.get_args(ResponseStreamEvent)[0]
variants = typing.get_args(union)
b = threading.Barrier(n)
bad = []
def decode():
b.wait()
try:
e = construct_type(type_=ResponseStreamEvent, value={"type": "response.completed", "sequence_number": 0, "response": {"id": "r"}})
except Exception as exc:
bad.append(f"raised {type(exc).__name__}: {str(exc)[:80]}")
return
if type(e).__name__ != "ResponseCompletedEvent": bad.append(type(e).__name__)
def direct(i):
b.wait()
for v in variants[i::n//2] + variants:
try: v.model_validate({})
except Exception: pass
ts = [threading.Thread(target=decode) for _ in range(n//2)] + [threading.Thread(target=direct, args=(i,)) for i in range(n//2)]
[t.start() for t in ts]; [t.join() for t in ts]
d = DISCRIMINATOR_CACHE.get(union)
print(json.dumps({"mapping_size": len(d.mapping) if d else None, "variants": len(variants), "misparsed": sorted(set(bad))}))
if "--child" in sys.argv:
child(int(sys.argv[2]))
else:
trials = int(sys.argv[1]); n = int(sys.argv[2]); bad = 0
for i in range(trials):
r = json.loads(subprocess.run([sys.executable, __file__, "--child", str(n)], capture_output=True, text=True, check=True).stdout.splitlines()[-1])
bad += bool(r["misparsed"]) or r["mapping_size"] not in (None, r["variants"])
print(i, r, flush=True)
print(f"SUMMARY trials={trials} threads={n} bad={bad}")
OS
Linux
Python version
Python 3.11 (repro), Python 3.10.16 (test suite)
Library version
openai v3.55.1
- 主要語言
- Python
- 星號
- 32.2k
- 分支
- 5.8k
- 平均合併
- 12 小時 29 分鐘
- 30 天內合併 PR
- 112
環境準備
在瀏覽器裡用你自己的 GitHub 帳號啟動這個專案的開發容器。
- 沒有 Dockerfile 或 Docker Compose 檔案
- 有 Pull Request 範本
- 閱讀貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
openai/openai-python 的其他 Issue
-
難度 2/5 1-3 小時 新手友好度 76/100
openai/openai-python#4338 ·
維護者通常 1 天內回覆
-
bug
難度 2/5 1-3 小時 新手友好度 65/100
openai/openai-python#4337 ·
維護者通常 1 天內回覆
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parameters可能已有人在做 @Rewaskc02-lang 於 1 天前認領。 未關閉
難度 2/5 1-3 小時 新手友好度 78/100
openai/openai-python#4311 · 4 則留言 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 78/100
openai/openai-python#4310 · 1 則留言 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 82/100
openai/openai-python#4309 · 1 則留言 ·
維護者通常 1 天內回覆
查看 openai/openai-python 的全部 Issue
相似的 Issue
-
triage
難度 1/5 1-3 小時 新手友好度 88/100
kornia/kornia-rs#1416 · 1 則留言 ·
維護者通常 2 天內回覆
-
ui
難度 2/5 1-3 小時 新手友好度 78/100
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 76/100
PolicyEngine/ai-inequality#64 ·
維護者通常 1 天內回覆
-
LinearGaussianStateSpace.dist splits states and observations wrongly when the transition varies over time可能已有人在做 @PabloRoque 今天認領。 未關閉
難度 2/5 1-3 小時 新手友好度 88/100
pymc-devs/pymc-extras#839 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 76/100
維護者通常 1 天內回覆