_ensure_strict_json_schema hits RecursionError on cyclic $ref with siblings, drops inherited allOf properties, and skips oneOf/prefixItems

未关闭
#4,272 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
55/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
tooling

调研方向

All three defects are in src/openai/lib/_pydantic.py, in _ensure_strict_json_schema and its caller to_strict_json_schema. Start by running the three repro snippets from the issue to confirm the RecursionError, the dropped Base.properties["a"], and the untouched oneOf/prefixItems objects. Fix each path minimally, then re-run the snippets plus the existing _pydantic tests; done means all three outputs match strict-schema expectations without regressing current behavior.

由索引模型根据 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

openai.lib._pydantic._ensure_strict_json_schema (to_strict_json_schema, src/openai/lib/_pydantic.py) has three schema-transformation bugs on main:

  1. RecursionError on self-referential $ref with sibling keywords (_pydantic.py:100-114):
    When a $ref entry carries a sibling keyword (e.g., "description"), _ensure_strict_json_schema resolves the target definition in-place via json_schema.update({**resolved, **json_schema}), deletes "$ref", and recursively calls _ensure_strict_json_schema(json_schema, ...) without tracking active $ref targets. If the referenced $defs object contains a self-reference that also carries a sibling keyword, to_strict_json_schema enters unbounded recursion and raises RecursionError.

  2. Silent loss of inherited properties / required when flattening single-entry allOf (_pydantic.py:78-83, 108-110):
    When an object schema extends a base definition via single-entry allOf: [{"$ref": "#/$defs/Base"}] alongside local "properties": {"b": ...}, lines 80–82 call json_schema.update(_ensure_strict_json_schema(all_of[0], ...)), which places "$ref": "#/$defs/Base" onto json_schema. Lines 108–110 then execute json_schema.update({**resolved, **json_schema}), where json_schema["properties"] ({"b": ...}) and json_schema["required"] (["b"]) overwrite resolved["properties"] ({"a": ...}) and resolved["required"] (["a"]). Because additionalProperties: False is enforced, every valid instance containing inherited field "a" ({"a": 1, "b": 2}) is rejected.

  3. Missing strict traversal of oneOf (Pydantic discriminated unions) and prefixItems (tuples) (_pydantic.py:64-88):
    _ensure_strict_json_schema recurses into properties, items (when dict), anyOf, and allOf, but never traverses oneOf (emitted by Pydantic v2 for discriminated unions Field(discriminator=...)) or prefixItems (emitted by Pydantic v2 for tuple[SubModel, int]). Any inline object schemas inside oneOf or prefixItems are left without additionalProperties: false or full required arrays, causing strict structured-output / tool-schema validation failures.

To Reproduce
from typing import Literal, Union
from pydantic import BaseModel, Field
from openai.lib._pydantic import _ensure_strict_json_schema, to_strict_json_schema

# 1. RecursionError on recursive $ref with sibling description:
cyclic_schema = {
    "$defs": {
        "Node": {
            "type": "object",
            "properties": {
                "val": {"type": "integer"},
                "next": {
                    "anyOf": [
                        {"$ref": "#/$defs/Node", "description": "Next node"},
                        {"type": "null"},
                    ]
                },
            },
        }
    },
    "$ref": "#/$defs/Node",
}
try:
    _ensure_strict_json_schema(cyclic_schema, path=(), root=cyclic_schema)
except RecursionError:
    print("Hit RecursionError")

# 2. Inherited properties deleted when flattening single-entry allOf:
allof_schema = {
    "$defs": {
        "Base": {
            "type": "object",
            "properties": {"a": {"type": "integer"}},
            "required": ["a"],
        }
    },
    "type": "object",
    "allOf": [{"$ref": "#/$defs/Base"}],
    "properties": {"b": {"type": "integer"}},
    "required": ["b"],
}
strict_allof = _ensure_strict_json_schema(allof_schema, path=(), root=allof_schema)
print(strict_allof["properties"].keys())
# Actual: dict_keys(['b']) — 'a' from Base was overwritten and forbidden by additionalProperties: False!

# 3. Inline object inside oneOf / prefixItems misses additionalProperties: False and full required:
oneof_schema = {
    "type": "object",
    "properties": {
        "choice": {
            "oneOf": [
                {"type": "object", "properties": {"kind": {"const": "a"}, "opt": {"type": "integer"}}},
            ]
        },
        "pair": {
            "type": "array",
            "prefixItems": [
                {"type": "object", "properties": {"x": {"type": "integer"}}},
                {"type": "integer"},
            ],
        },
    },
}
strict_oneof = _ensure_strict_json_schema(oneof_schema, path=(), root=oneof_schema)
print(strict_oneof["properties"]["choice"]["oneOf"][0])
# Missing 'additionalProperties': False and 'required': ['kind', 'opt']
print(strict_oneof["properties"]["pair"]["prefixItems"][0])
# Missing 'additionalProperties': False and 'required': ['x']
OS

Windows / Linux (OS-independent)

Python version

Python 3.12

Library version

openai v3.3.0 / main (3dae6090cc)

主要语言
Python
星标
32.2k
派生
5.8k
平均合并
12 小时 29 分钟
30 天内合并 PR
112

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

openai/openai-python 的其他 Issue

查看 openai/openai-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。