Concurrent first use of streaming decode caches an incomplete discriminator map, so events decode as the wrong class
Maintainer antworten meist innerhalb von 1 Tag
Bewertung
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Anfängerfreundlichkeit
- 48/100
Rechercherichtung
Start by reading construct_type, _build_discriminated_union_meta, and _extract_field_schema_pv2, which the issue identifies as the fallback decoding path and source of the incomplete cached mapping. Reproduce with the supplied no-network script using concurrent threads in fresh subprocesses. Done when concurrent first-use decoding returns the expected event classes and nested response models, without caching an incomplete discriminator map.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Beschreibung
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
In a fresh process, if several threads decode Responses stream events at the same time, and an event fails strict validation, events can decode to the wrong class. For example, response.created and response.completed come back as ResponseAudioDeltaEvent, with response left as a plain dict. The bad mapping is cached, so the process stays broken.
Cause, as far as we can trace it: when strict validation fails, construct_type calls _build_discriminated_union_meta. That function reads each variant's __pydantic_core_schema__ through _extract_field_schema_pv2. Because SDK models use deferred Pydantic builds, a variant that another thread is still building has no usable schema yet, so it is silently skipped. The resulting incomplete mapping is then cached on the union as __discriminator__ and reused for the rest of the process.
Any event that fails strict validation can trigger this. In practice we've seen two triggers:
- A
reasoning.effortvalue that an older SDK didn't recognize. - A
response.text.formatof typejson_schemareturned without aschemafield. This still fails strict validation on the latest release (3.26.0), and the race reproduces there 20/20.
The fallback path exists to handle exactly this kind of mismatch, which is why the race matters in practice.
Workarounds
- Set
DEFER_PYDANTIC_BUILD=falsebefore importingopenai. This makes import slower. - Before any concurrent use, call
model_rebuild()on every model reachable fromopenai.types.responses, under a lock.
Suggested fix
Don't cache a discriminator mapping that may be incomplete. Either build the variant's schema before reading it, or skip caching whenever any variant's schema couldn't be read. Thread-safe lazy initialization in _build_discriminated_union_meta would also work.
To Reproduce
pip install openai httpx- Save the script from "Code snippets" as
repro.py. - Run
python repro.py. It needs no network or API key.
The script uses httpx.MockTransport to return synthetic SSE. It starts 8 threads behind a barrier, each with its own client, and checks the class of every decoded event. Each trial runs in a fresh subprocess because the cache lives for the whole process.
| Configuration | Fresh processes with mis-decoded events |
|---|---|
| openai 1.109.1, pydantic 2.13.4, Python 3.12, 8 threads | 20/20 |
| openai 3.24.0, pydantic 2.13.5, Python 3.14, 8 threads | 20/20 |
| openai 3.26.0 (latest), pydantic 2.13.5, Python 3.14, 8 threads | 20/20 |
openai 3.26.0, TRIGGER=json_schema, 8 threads |
20/20 |
openai 3.26.0, TRIGGER=json_schema, THREADS=1 |
0/20 |
openai 1.109.1, THREADS=1 |
0/20 |
openai 1.109.1, DEFER_PYDANTIC_BUILD=false |
0/20 |
Code snippets
"""Concurrent first-use Responses streaming decodes events as the wrong class.
Run: python repro.py (spawns fresh processes; the bug needs a cold process)
Requires: pip install openai httpx
"""
import json
import os
import subprocess
import sys
import threading
THREADS = int(os.environ.get("THREADS", "8"))
# TRIGGER=effort (default): unknown reasoning.effort value.
# TRIGGER=json_schema: text.format json_schema without a "schema" field.
TRIGGER = os.environ.get("TRIGGER", "effort")
def sse(events):
return "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in events).encode()
def response_obj(status):
return {
"id": "resp_1", "object": "response", "created_at": 0, "status": status,
"model": "gpt-test", "output": [], "parallel_tool_calls": True,
"tool_choice": "auto", "tools": [],
} | (
# Either payload fails strict validation, so the SDK uses its fallback
# discriminated-union decoding path.
{"text": {"format": {"type": "json_schema", "name": "out", "strict": True}}}
if TRIGGER == "json_schema"
else {"reasoning": {"effort": "not-a-known-effort"}}
)
BODY = sse([
{"type": "response.created", "sequence_number": 0, "response": response_obj("in_progress")},
{"type": "response.completed", "sequence_number": 1, "response": response_obj("completed")},
])
def worker(barrier, bad):
import httpx
from openai import OpenAI
transport = httpx.MockTransport(
lambda req: httpx.Response(200, headers={"content-type": "text/event-stream"}, content=BODY)
)
client = OpenAI(api_key="x", base_url="http://test/v1", http_client=httpx.Client(transport=transport))
barrier.wait()
for event in client.responses.create(model="gpt-test", input="hi", stream=True):
expected = {"response.created": "ResponseCreatedEvent",
"response.completed": "ResponseCompletedEvent"}[event.type]
if type(event).__name__ != expected:
bad.append(f"{event.type!r} decoded as {type(event).__name__}")
def child():
barrier, bad = threading.Barrier(THREADS), []
threads = [threading.Thread(target=worker, args=(barrier, bad)) for _ in range(THREADS)]
for t in threads: t.start()
for t in threads: t.join()
print(json.dumps(bad))
def main(runs=20):
import openai, pydantic
print(f"openai {openai.__version__}, pydantic {pydantic.VERSION}, python {sys.version.split()[0]}, trigger {TRIGGER}")
failures = 0
for i in range(runs):
out = subprocess.run([sys.executable, __file__, "--child"], capture_output=True, text=True)
bad = json.loads(out.stdout.strip().splitlines()[-1]) if out.returncode == 0 else [out.stderr[-500:]]
if bad:
failures += 1
print(f"run {i}: FAIL {sorted(set(bad))}")
print(f"{failures}/{runs} fresh processes mis-decoded events")
if __name__ == "__main__":
child() if "--child" in sys.argv else main()
OS
macOS
Python version
Python 3.12 and 3.14
Library version
openai v1.109.1, v3.24.0, and v3.26.0 (latest)
- Vorherrschende Sprache
- Python
- Sterne
- 32.2k
- Forks
- 5.8k
- Ø Merge
- 12 Std. 31 Min.
- Gemergte PRs (30 T.)
- 101
Entwicklungsumgebung
Startet den Dev-Container des Projekts im Browser, mit Ihrem eigenen GitHub-Konto.
- Kein Dockerfile und keine Docker-Compose-Datei
- Hat eine Pull-Request-Vorlage
- Beitragsleitfaden lesen
Erste Schritte
- Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
- Forken Sie das Repository und arbeiten Sie in einem Branch.
- Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.
Mehr aus openai/openai-python
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
openai/openai-python#4339 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
openai/openai-python#4338 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
`DeprecationWarning` thrown when calling websockets (17.1 and later)Evtl. vergeben @akhil9tiet hat das vor 1 Tag übernommen. Offenbug
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 65/100
openai/openai-python#4337 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parametersEvtl. vergeben @Rewaskc02-lang hat das vor 2 Tagen übernommen. Offen
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
openai/openai-python#4311 · 4 Kommentare ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
openai/openai-python#4310 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
Alle Issues in openai/openai-python
Ähnliche Issues
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 69/100
-
frontend testing
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 84/100
vendrabuck/HERD#1588 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Lessons: record the second case of L14 (security updates cover only pip)Evtl. vergeben @vishwanathj hat das heute übernommen. Offenarea/docs no-test-needed type/docs
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
vishwanathj/ocp_lab.ai#39 · 1 Kommentar ·
-
enhancement good first issue
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 88/100
laaielichter/Gulliver#228 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 68/100
Maintainer antworten meist innerhalb von 1 Tag