Skip to content

Commit 6b9072e

Browse files
authored
Compact dynamic cache keys (#3395)
* Compact dynamic cache keys * Use pydantic json for dynamic cache config
1 parent 3225c02 commit 6b9072e

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

src/datamodel_code_generator/dynamic.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import ast
1010
import builtins
11+
import hashlib
1112
import itertools
1213
import json
1314
import sys
@@ -169,10 +170,13 @@ def _make_cache_key(schema: Mapping[str, Any], config: GenerateConfig) -> str |
169170
Returns None if the schema is not JSON-serializable.
170171
"""
171172
try:
172-
key_data = {"schema": dict(schema), "config": config.model_dump(mode="json", exclude_defaults=True)}
173-
return json.dumps(key_data, sort_keys=True, separators=(",", ":"))
173+
schema_json = json.dumps(dict(schema), sort_keys=True, separators=(",", ":"))
174+
config_json = config.model_dump_json(exclude_defaults=True)
174175
except (TypeError, ValueError):
175176
return None
177+
schema_digest = hashlib.sha256(schema_json.encode()).hexdigest()
178+
config_digest = hashlib.sha256(config_json.encode()).hexdigest()
179+
return f"{schema_digest}:{len(schema_json)}:{config_digest}:{len(config_json)}"
176180

177181

178182
def _detect_schema_input_file_type(input_: Mapping[str, Any]) -> InputFileType:

tests/main/test_dynamic_models.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,21 @@ def test_non_serializable_schema_skips_cache() -> None:
370370
assert _make_cache_key(schema, make_config()) is None
371371

372372

373+
def test_dynamic_cache_key_does_not_retain_schema_payload() -> None:
374+
"""Test cache keys keep digests instead of the original schema text."""
375+
from datamodel_code_generator import dynamic as dcg
376+
377+
unique_description = "schema-payload-marker-that-should-not-be-in-cache-key"
378+
schema = make_object_schema({"name": {"type": "string", "description": unique_description}})
379+
380+
generate_dynamic_models(schema)
381+
382+
assert len(dcg._dynamic_models_cache) == 1
383+
cache_key = next(iter(dcg._dynamic_models_cache))
384+
assert unique_description not in cache_key
385+
assert len(cache_key) < 180
386+
387+
373388
def test_cache_hit_inside_lock() -> None:
374389
"""Test cache hit after acquiring lock (double-checked locking)."""
375390
from datamodel_code_generator import dynamic as dcg

0 commit comments

Comments
 (0)