Cache round-trip fails for Json fields and computed fields with forbidden extras
Describe the bug
store_cached_response() serializes the parsed model with model_dump_json() using the default round_trip=False. Some valid response models therefore cannot be read back by load_cached_response(), which revalidates that JSON.
For a Json[list[int]] field, the stored field becomes a JSON array, but validation requires a JSON-encoded string. Models with a computed field and extra="forbid" also fail because the computed output is stored and then rejected as an extra input.
Both sync and async request paths use these shared cache helpers. This reproduction exercises them directly and does not require a provider, model ID, messages, or API key.
Reproduction
from pydantic import BaseModel, Json
from instructor.cache import AutoCache, load_cached_response, store_cached_response
class Answer(BaseModel):
values: Json[list[int]]
answer = Answer.model_validate({"values": "[1, 2, 3]"})
cache = AutoCache()
store_cached_response(cache, "answer", answer)
restored = load_cached_response(cache, "answer", Answer)
assert restored == answerActual result:
1 validation error for Answer
values
JSON input should be string, bytes or bytearray
[type=json_type, input_value=[1, 2, 3], input_type=list]Expected: the cache restores the validated model, preserving its values.
Investigation and proposed fix
Use model.model_dump_json(round_trip=True) for the parsed-model portion of the cache payload. Pydantic's round-trip serialization preserves Json[T] in a form accepted by validation and omits computed output fields. The raw provider response can retain its existing serialization.
I reproduced this on main at e12f8b49203b0c1f253d27c1e709d0a09b9fc5a8, Instructor 1.17.1, Python 3.11.15, Pydantic 2.11.7, macOS arm64. Local regression cases fail for direct and nested Json fields and a computed field with forbidden extras under both strict and non-strict validation; ordinary-model controls pass (6 failed, 2 passed).
I plan to submit the focused fix and regression tests. This was found through code inspection and local reproduction, with Codex assistance.
Source: 567-labs/instructor