#3046·agentscope

[Bug]: schema flattening leaves dangling $defs references in discriminator.mapping

Author: Jay0130-aCreated Sep 30, 2026Updated Sep 30, 2026
Labelstriage/confirmed

Prerequisites

  • I have searched the existing issues and discussions, and this is not a duplicate.
  • This is a bug, not a usage question. (For questions, please use Discussions instead.)

Background / Description

_flatten_json_schema (src/agentscope/_utils/_common.py) documents that it "resolves every such reference by substituting the full definition inline, then drops the $defs / definitions sections so the output is a flat, self-contained schema".

For a Pydantic discriminated union — Annotated[Union[A, B], Field(discriminator="kind")], the standard way to type a "one of these variants" tool parameter — that invariant does not hold. The references for a discriminated union live in two places:

  1. inside oneOf, as objects carrying a $ref key, and
  2. inside discriminator.mapping, as plain strings ({"ring": "#/$defs/Ring", "disc": "#/$defs/Disc"}).

_resolve_ref only rewrites dicts that contain a $ref key; a string value falls through if not isinstance(obj, dict): return obj untouched. The $defs section is popped unconditionally at the top, so the result keeps #/$defs/Ring strings that point into a section that no longer exists in the document.

Consequence, stated narrowly: the output is not self-contained by the function's own contract. I have not observed a specific provider rejecting it — the reason the helper exists is precisely that some providers cannot process $defs / $ref at all, so a surviving pointer is at best ignored and at worst an invalid-schema error.

The other union/$ref shapes I probed do flatten cleanly, so the gap is specific to discriminator.mapping:

--- discriminated-union: has $defs left=False residual pointers=['#/$defs/Disc', '#/$defs/Ring']
--- plain-union:            residual pointers=[]
--- recursive-model:        residual pointers=[]
--- dict-of-models:         residual pointers=[]
--- list-of-models:         residual pointers=[]
--- additionalProperties-model: residual pointers=[]

Reachability in this repository (so this is not a hypothetical shape):

  • the helper is applied to real tool parameters in src/agentscope/model/_gemini/_model.py:574 and src/agentscope/model/_openai_chat/_model.py:629 (_flatten_json_schema(func["parameters"]));
  • those parameters come from Pydantic models — src/agentscope/tool/_adapters.py:105 (input_schema.model_json_schema()) and src/agentscope/tool/_utils.py:175 (base_model.model_json_schema());
  • discriminated unions are already used in the codebase, e.g. src/agentscope/app/middleware/_protocol/_base.py:218 (Annotated[AgentEvent, Field(discriminator="type")]).

Error Messages

$ python repro.py
has $defs left: False | residual pointers: ['#/$defs/Disc', '#/$defs/Ring']
Traceback (most recent call last):
  File "D:\code\agentscope-src\repro.py", line 21, in <module>
    assert not pointers, f"flattened schema still references removed $defs: {pointers}"
AssertionError: flattened schema still references removed $defs: ['#/$defs/Disc', '#/$defs/Ring']

Steps to Reproduce

  1. Code, saved as repro.py:
python
import json
import re
from typing import Annotated, Literal, Union

from pydantic import BaseModel, Field

from agentscope._utils._common import _flatten_json_schema


class Ring(BaseModel):
    kind: Literal["ring"]
    radius: float


class Disc(BaseModel):
    kind: Literal["disc"]
    diameter: float


class ShapeTool(BaseModel):
    shape: Annotated[Union[Ring, Disc], Field(discriminator="kind")]


raw = ShapeTool.model_json_schema()
flat = _flatten_json_schema(raw)

pointers = sorted(set(re.findall(r"#/\$defs/[A-Za-z0-9_]+", json.dumps(flat))))
print("has $defs left:", "$defs" in flat, "| residual pointers:", pointers)
assert not pointers, f"flattened schema still references removed $defs: {pointers}"
  1. Run: python repro.py (needs pip install -e . plus pydantic).

  2. See the assertion fail. The same model without the discriminator (shape: Union[Ring, Disc]) flattens with no residual pointer, which isolates the cause to discriminator.mapping.

Environment

  • AgentScope Version: 2.0.10 (dev, current main)
  • Python Version: 3.11.9
  • OS: Windows 10 (10.0.19045)
  • pydantic: 2.13.5

Suggested fix / Notes

Narrow fix consistent with what the function already does for oneOf: when walking a discriminator object, resolve a mapping value that is a local definition pointer (#/$defs/<name> / #/definitions/<name>) into the same inlined schema instead of leaving the pointer behind. JSON Schema 2020-12 permits a discriminator.mapping value to be a schema object, so the information is preserved rather than dropped.

Test placement: there is no dedicated unit test for _flatten_json_schema — it is only reached indirectly through tests/model_gemini_test.py — so a focused test would help regardless of which fix lands.

Related but distinct: #2999 / PR #3000 cover a different hole in the same helper ($ref fragments that use JSON Pointer escapes, ~1 / ~0). Same consequence class, different cause and different code site, and both would edit _resolve_ref, so whichever lands second needs a rebase. Reporting separately to keep each change atomic, per the contributing guide's "keep PRs atomic" rule.

Source: agentscope-ai/agentscope