jsonschema-mojo 0.2.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jsonschema_mojo/__init__.py +45 -0
- jsonschema_mojo/_native.py +270 -0
- jsonschema_mojo/_reference.py +217 -0
- jsonschema_mojo/core.py +601 -0
- jsonschema_mojo-0.2.5.dist-info/METADATA +206 -0
- jsonschema_mojo-0.2.5.dist-info/RECORD +7 -0
- jsonschema_mojo-0.2.5.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""jsonschema-mojo: a drop-in faster replacement for the `jsonschema` package.
|
|
2
|
+
|
|
3
|
+
Same call shapes, same pass/fail outcomes, same failing paths — powered by a
|
|
4
|
+
Mojo kernel where the platform supports it (macOS arm64, Linux x86_64), with
|
|
5
|
+
a vendored pure-Python fallback everywhere else (including Windows).
|
|
6
|
+
|
|
7
|
+
import jsonschema_mojo
|
|
8
|
+
|
|
9
|
+
jsonschema_mojo.validate({"name": "Ada"}, schema) # like jsonschema.validate
|
|
10
|
+
validator = jsonschema_mojo.Validator(schema) # reuse a compiled schema
|
|
11
|
+
for error in validator.iter_errors(instance):
|
|
12
|
+
print(error.json_path, error.message)
|
|
13
|
+
|
|
14
|
+
Draft 2020-12 subset: type, properties, required, items,
|
|
15
|
+
additionalProperties, enum, const, minimum, maximum, exclusiveMinimum,
|
|
16
|
+
exclusiveMaximum, minLength, maxLength, pattern, minItems, maxItems,
|
|
17
|
+
uniqueItems, minProperties, maxProperties, multipleOf (plus boolean
|
|
18
|
+
subschemas). Schemas using other validation keywords raise
|
|
19
|
+
UnsupportedSchemaError rather than silently diverging.
|
|
20
|
+
|
|
21
|
+
Set JSONSCHEMA_MOJO_DISABLE_NATIVE=1 to force the pure-Python fallback.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from jsonschema_mojo._native import backend_info, native_available
|
|
25
|
+
from jsonschema_mojo.core import (
|
|
26
|
+
Draft202012Validator,
|
|
27
|
+
UnsupportedSchemaError,
|
|
28
|
+
ValidationError,
|
|
29
|
+
Validator,
|
|
30
|
+
iter_errors,
|
|
31
|
+
validate,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__version__ = "0.2.5" # x-release-please-version
|
|
35
|
+
__all__ = [
|
|
36
|
+
"Draft202012Validator",
|
|
37
|
+
"UnsupportedSchemaError",
|
|
38
|
+
"ValidationError",
|
|
39
|
+
"Validator",
|
|
40
|
+
"backend_info",
|
|
41
|
+
"iter_errors",
|
|
42
|
+
"native_available",
|
|
43
|
+
"validate",
|
|
44
|
+
"__version__",
|
|
45
|
+
]
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""ctypes loader for the jsonschemamojo native kernel, with an ABI handshake.
|
|
2
|
+
|
|
3
|
+
Resolution order:
|
|
4
|
+
|
|
5
|
+
1. ``$JSONSCHEMA_MOJO_NATIVE_LIB`` (explicit path override, for development)
|
|
6
|
+
2. the shared library bundled in this wheel under ``jsonschema_mojo/_native/``
|
|
7
|
+
3. the repository development build output ``kernels/jsonschema/build/``
|
|
8
|
+
|
|
9
|
+
If the library cannot be found, fails to load, or reports an ABI version this
|
|
10
|
+
package does not understand, :class:`NativeUnavailable` is raised and the
|
|
11
|
+
caller falls back to the vendored pure-Python reference implementation.
|
|
12
|
+
Set ``JSONSCHEMA_MOJO_DISABLE_NATIVE=1`` to force that fallback (used by the
|
|
13
|
+
differential test suite).
|
|
14
|
+
|
|
15
|
+
Stable C ABI (v1)::
|
|
16
|
+
|
|
17
|
+
int32_t jsonschemamojo_abi_version(void)
|
|
18
|
+
void* jsonschemamojo_schema_compile(const char* text, int64_t len)
|
|
19
|
+
int32_t jsonschemamojo_schema_flags(void* handle)
|
|
20
|
+
void jsonschemamojo_schema_destroy(void* handle)
|
|
21
|
+
int32_t jsonschemamojo_validate(void* handle, const char* inst,
|
|
22
|
+
int64_t inst_len, uint8_t* out,
|
|
23
|
+
int64_t out_cap, int32_t* meta)
|
|
24
|
+
|
|
25
|
+
``validate`` appends error/deferral records to ``out`` (see
|
|
26
|
+
``core._decode_records`` for the wire format) and reports counts, overflow,
|
|
27
|
+
and instance-feature flags through ``meta``.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import ctypes
|
|
33
|
+
import os
|
|
34
|
+
import sys
|
|
35
|
+
import threading
|
|
36
|
+
|
|
37
|
+
# Must equal ABI_VERSION in kernels/jsonschema/src/jsonschemamojo.mojo. A
|
|
38
|
+
# mismatch means the installed wheel and the resolved shared library disagree;
|
|
39
|
+
# fall back.
|
|
40
|
+
ABI_VERSION = 1
|
|
41
|
+
|
|
42
|
+
# schema_flags() / meta[4] bits, mirrored from the kernel.
|
|
43
|
+
FLAG_BIG_NUMBER = 1 << 0
|
|
44
|
+
|
|
45
|
+
_ENV_LIB = "JSONSCHEMA_MOJO_NATIVE_LIB"
|
|
46
|
+
_ENV_DISABLE = "JSONSCHEMA_MOJO_DISABLE_NATIVE"
|
|
47
|
+
|
|
48
|
+
# meta[] slots written by jsonschemamojo_validate.
|
|
49
|
+
_META_STATUS = 0
|
|
50
|
+
_META_N_ERR = 1
|
|
51
|
+
_META_N_DEFER = 2
|
|
52
|
+
_META_OVERFLOW = 3
|
|
53
|
+
_META_BIG_NUMBER = 4
|
|
54
|
+
_META_OUT_LEN = 5
|
|
55
|
+
|
|
56
|
+
_INITIAL_OUT_CAP = 64 * 1024
|
|
57
|
+
_MAX_OUT_GROWTH_ROUNDS = 12
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class NativeUnavailable(RuntimeError): # noqa: N818
|
|
61
|
+
"""The native jsonschemamojo kernel could not be found, loaded, or verified."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _lib_basename() -> str:
|
|
65
|
+
if sys.platform == "darwin":
|
|
66
|
+
return "libjsonschemamojo.dylib"
|
|
67
|
+
if sys.platform.startswith("linux"):
|
|
68
|
+
return "libjsonschemamojo.so"
|
|
69
|
+
if sys.platform.startswith("win"):
|
|
70
|
+
return "jsonschemamojo.dll" # no Mojo toolchain builds this today
|
|
71
|
+
return "libjsonschemamojo.so"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _candidate_paths() -> list[tuple[str, str]]:
|
|
75
|
+
"""(source_label, path) candidates, in resolver order."""
|
|
76
|
+
out: list[tuple[str, str]] = []
|
|
77
|
+
override = os.environ.get(_ENV_LIB)
|
|
78
|
+
if override:
|
|
79
|
+
out.append((f"env {_ENV_LIB}", override))
|
|
80
|
+
here = os.path.dirname(__file__)
|
|
81
|
+
out.append(("bundled in wheel", os.path.join(here, "_native", _lib_basename())))
|
|
82
|
+
out.append(
|
|
83
|
+
(
|
|
84
|
+
"repo-dev build output",
|
|
85
|
+
os.path.abspath(
|
|
86
|
+
os.path.join(here, "..", "..", "..", "kernels", "jsonschema", "build", _lib_basename())
|
|
87
|
+
),
|
|
88
|
+
)
|
|
89
|
+
)
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _bind_abi(lib: ctypes.CDLL) -> None:
|
|
94
|
+
u8p = ctypes.POINTER(ctypes.c_uint8)
|
|
95
|
+
i32p = ctypes.POINTER(ctypes.c_int32)
|
|
96
|
+
lib.jsonschemamojo_abi_version.argtypes = []
|
|
97
|
+
lib.jsonschemamojo_abi_version.restype = ctypes.c_int32
|
|
98
|
+
lib.jsonschemamojo_schema_compile.argtypes = [ctypes.c_char_p, ctypes.c_int64]
|
|
99
|
+
lib.jsonschemamojo_schema_compile.restype = ctypes.c_void_p
|
|
100
|
+
lib.jsonschemamojo_schema_flags.argtypes = [ctypes.c_void_p]
|
|
101
|
+
lib.jsonschemamojo_schema_flags.restype = ctypes.c_int32
|
|
102
|
+
lib.jsonschemamojo_schema_destroy.argtypes = [ctypes.c_void_p]
|
|
103
|
+
lib.jsonschemamojo_schema_destroy.restype = None
|
|
104
|
+
lib.jsonschemamojo_validate.argtypes = [
|
|
105
|
+
ctypes.c_void_p, # schema handle
|
|
106
|
+
ctypes.c_char_p, # instance JSON text (NUL-free: dumps escapes it)
|
|
107
|
+
ctypes.c_int64, # instance text length
|
|
108
|
+
u8p, # output buffer
|
|
109
|
+
ctypes.c_int64, # output buffer capacity
|
|
110
|
+
i32p, # meta[8]
|
|
111
|
+
]
|
|
112
|
+
lib.jsonschemamojo_validate.restype = ctypes.c_int32
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
_LOCK = threading.Lock()
|
|
116
|
+
_LIB: ctypes.CDLL | None = None
|
|
117
|
+
_LIB_SOURCE: str | None = None
|
|
118
|
+
_LOAD_ERROR: str | None = None
|
|
119
|
+
|
|
120
|
+
# Per-thread scratch for validation records: allocating and zeroing a fresh
|
|
121
|
+
# 64 KiB buffer per call would dominate small-document latency. Buffers are
|
|
122
|
+
# thread-local (ctypes releases the GIL during the native call) and grow to
|
|
123
|
+
# the largest capacity ever needed.
|
|
124
|
+
_TLS = threading.local()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _scratch_buffer(cap: int):
|
|
128
|
+
buf = getattr(_TLS, "record_buffer", None)
|
|
129
|
+
if buf is None or len(buf) < cap:
|
|
130
|
+
buf = (ctypes.c_uint8 * cap)()
|
|
131
|
+
_TLS.record_buffer = buf
|
|
132
|
+
return buf
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _load() -> ctypes.CDLL:
|
|
136
|
+
"""Resolve, dlopen, and ABI-handshake the native kernel. Never caches failure."""
|
|
137
|
+
global _LIB, _LIB_SOURCE, _LOAD_ERROR
|
|
138
|
+
if os.environ.get(_ENV_DISABLE) == "1":
|
|
139
|
+
raise NativeUnavailable(f"native kernel disabled by {_ENV_DISABLE}=1")
|
|
140
|
+
if _LIB is not None:
|
|
141
|
+
return _LIB
|
|
142
|
+
with _LOCK:
|
|
143
|
+
if _LIB is not None:
|
|
144
|
+
return _LIB
|
|
145
|
+
errors: list[str] = []
|
|
146
|
+
for label, path in _candidate_paths():
|
|
147
|
+
try:
|
|
148
|
+
if not path or not os.path.exists(path):
|
|
149
|
+
continue
|
|
150
|
+
try:
|
|
151
|
+
lib = ctypes.CDLL(path)
|
|
152
|
+
except OSError as exc:
|
|
153
|
+
errors.append(f"{label} ({path}): {exc}")
|
|
154
|
+
continue
|
|
155
|
+
try:
|
|
156
|
+
_bind_abi(lib)
|
|
157
|
+
abi = int(lib.jsonschemamojo_abi_version())
|
|
158
|
+
except Exception as exc: # missing/renamed symbol = wrong lib
|
|
159
|
+
errors.append(f"{label} ({path}): ABI not recognized: {exc}")
|
|
160
|
+
continue
|
|
161
|
+
if abi != ABI_VERSION:
|
|
162
|
+
errors.append(
|
|
163
|
+
f"{label} ({path}): native ABI v{abi} != wrapper ABI v{ABI_VERSION}"
|
|
164
|
+
)
|
|
165
|
+
continue
|
|
166
|
+
_LIB, _LIB_SOURCE = lib, f"{label} ({path})"
|
|
167
|
+
_LOAD_ERROR = None
|
|
168
|
+
return lib
|
|
169
|
+
except OSError as exc:
|
|
170
|
+
errors.append(f"{label}: {exc}")
|
|
171
|
+
_LOAD_ERROR = "; ".join(errors) or "no native kernel found on any resolver path"
|
|
172
|
+
raise NativeUnavailable(_LOAD_ERROR)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def native_available() -> bool:
|
|
176
|
+
"""True if the native kernel can validate right now. Never raises."""
|
|
177
|
+
try:
|
|
178
|
+
_load()
|
|
179
|
+
return True
|
|
180
|
+
except NativeUnavailable:
|
|
181
|
+
return False
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def backend_info() -> dict:
|
|
185
|
+
"""Diagnostics for the active backend. Never raises."""
|
|
186
|
+
info = {
|
|
187
|
+
"native_available": False,
|
|
188
|
+
"native_source": None,
|
|
189
|
+
"abi_version_expected": ABI_VERSION,
|
|
190
|
+
"abi_version_native": None,
|
|
191
|
+
"disabled_by_env": os.environ.get(_ENV_DISABLE) == "1",
|
|
192
|
+
"platform": sys.platform,
|
|
193
|
+
"error": None,
|
|
194
|
+
}
|
|
195
|
+
try:
|
|
196
|
+
lib = _load()
|
|
197
|
+
except NativeUnavailable as exc:
|
|
198
|
+
info["error"] = str(exc)
|
|
199
|
+
return info
|
|
200
|
+
info["native_available"] = True
|
|
201
|
+
info["native_source"] = _LIB_SOURCE
|
|
202
|
+
info["abi_version_native"] = int(lib.jsonschemamojo_abi_version())
|
|
203
|
+
return info
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class NativeSchema:
|
|
207
|
+
"""Owned handle to a natively compiled schema. Not thread-safe to close twice."""
|
|
208
|
+
|
|
209
|
+
def __init__(self, schema_text: bytes) -> None:
|
|
210
|
+
lib = _load() # raises NativeUnavailable
|
|
211
|
+
handle = lib.jsonschemamojo_schema_compile(schema_text, len(schema_text))
|
|
212
|
+
if not handle:
|
|
213
|
+
raise NativeUnavailable(
|
|
214
|
+
"native kernel rejected the schema JSON; "
|
|
215
|
+
"falling back to the pure-Python reference"
|
|
216
|
+
)
|
|
217
|
+
self._lib = lib
|
|
218
|
+
self._handle = handle
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def flags(self) -> int:
|
|
222
|
+
if self._handle is None:
|
|
223
|
+
raise NativeUnavailable("native schema is closed")
|
|
224
|
+
return int(self._lib.jsonschemamojo_schema_flags(self._handle))
|
|
225
|
+
|
|
226
|
+
def validate_records(self, instance_text: bytes) -> tuple[bytes, int, int, bool]:
|
|
227
|
+
"""Validate one serialized instance.
|
|
228
|
+
|
|
229
|
+
Returns ``(record_payload, n_errors, n_defers, big_number)``. Raises
|
|
230
|
+
NativeUnavailable if the native walk itself failed (the caller then
|
|
231
|
+
re-validates with the pure-Python reference).
|
|
232
|
+
"""
|
|
233
|
+
if self._handle is None:
|
|
234
|
+
raise NativeUnavailable("native schema is closed")
|
|
235
|
+
cap = _INITIAL_OUT_CAP
|
|
236
|
+
for _ in range(_MAX_OUT_GROWTH_ROUNDS):
|
|
237
|
+
buf = _scratch_buffer(cap)
|
|
238
|
+
meta = (ctypes.c_int32 * 8)()
|
|
239
|
+
rc = self._lib.jsonschemamojo_validate(
|
|
240
|
+
self._handle, instance_text, len(instance_text), buf, cap, meta
|
|
241
|
+
)
|
|
242
|
+
if rc != 0:
|
|
243
|
+
raise NativeUnavailable(f"native validation failed with status {rc}")
|
|
244
|
+
if meta[_META_STATUS] != 0:
|
|
245
|
+
raise NativeUnavailable(
|
|
246
|
+
f"native instance parse failed with status {meta[_META_STATUS]}"
|
|
247
|
+
)
|
|
248
|
+
if meta[_META_OVERFLOW]:
|
|
249
|
+
cap *= 4 # records are complete only up to overflow; retry bigger
|
|
250
|
+
continue
|
|
251
|
+
out_len = int(meta[_META_OUT_LEN])
|
|
252
|
+
payload = bytes(bytearray(buf[:out_len]))
|
|
253
|
+
return (
|
|
254
|
+
payload,
|
|
255
|
+
int(meta[_META_N_ERR]),
|
|
256
|
+
int(meta[_META_N_DEFER]),
|
|
257
|
+
bool(meta[_META_BIG_NUMBER]),
|
|
258
|
+
)
|
|
259
|
+
raise NativeUnavailable("native error-record buffer did not converge")
|
|
260
|
+
|
|
261
|
+
def close(self) -> None:
|
|
262
|
+
handle, self._handle = self._handle, None
|
|
263
|
+
if handle and self._lib is not None:
|
|
264
|
+
self._lib.jsonschemamojo_schema_destroy(handle)
|
|
265
|
+
|
|
266
|
+
def __del__(self) -> None: # best-effort; never raise during GC
|
|
267
|
+
try:
|
|
268
|
+
self.close()
|
|
269
|
+
except Exception: # noqa: BLE001, S110
|
|
270
|
+
pass
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Vendored pure-Python validator for the supported draft 2020-12 subset.
|
|
2
|
+
|
|
3
|
+
This is the portability fallback (Windows, missing/unloadable native kernel,
|
|
4
|
+
instances the native path cannot represent exactly) and the correctness
|
|
5
|
+
oracle of the package: it mirrors the published `jsonschema` package's
|
|
6
|
+
observable behaviour on Python objects, including its edge cases:
|
|
7
|
+
|
|
8
|
+
* ``1.0`` satisfies ``"integer"`` (floats with integral values count);
|
|
9
|
+
* booleans are never numbers, and ``True``/``False`` never equal ``1``/``0``
|
|
10
|
+
for ``const``/``enum``/``uniqueItems`` (numbers do compare across
|
|
11
|
+
int/float form, so ``1 == 1.0``);
|
|
12
|
+
* ``"array"`` means ``list`` (not tuple), ``"object"`` means ``dict``;
|
|
13
|
+
* ``multipleOf`` uses Python's floored ``%`` for integer divisors and the
|
|
14
|
+
``int(quotient) != quotient`` test for float divisors, with an exact
|
|
15
|
+
Fraction fallback when the quotient overflows;
|
|
16
|
+
* errors are yielded in schema-dict insertion order, like the reference.
|
|
17
|
+
|
|
18
|
+
Yields ``(keyword, instance_path, schema_path)`` records — the same shape
|
|
19
|
+
the native backend decodes — so both backends build identical error objects
|
|
20
|
+
through ``core._render_error``.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import numbers
|
|
26
|
+
import re
|
|
27
|
+
from fractions import Fraction
|
|
28
|
+
|
|
29
|
+
Record = tuple[str, tuple, tuple]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def is_type(instance, type_name: str) -> bool:
|
|
33
|
+
if type_name == "null":
|
|
34
|
+
return instance is None
|
|
35
|
+
if type_name == "boolean":
|
|
36
|
+
return isinstance(instance, bool)
|
|
37
|
+
if type_name == "integer":
|
|
38
|
+
# bool inherits from int, so ensure bools aren't reported as ints;
|
|
39
|
+
# floats with integral values count as integers (draft 2020-12).
|
|
40
|
+
if isinstance(instance, bool):
|
|
41
|
+
return False
|
|
42
|
+
return isinstance(instance, int) or (
|
|
43
|
+
isinstance(instance, float) and instance.is_integer()
|
|
44
|
+
)
|
|
45
|
+
if type_name == "number":
|
|
46
|
+
return isinstance(instance, numbers.Number) and not isinstance(instance, bool)
|
|
47
|
+
if type_name == "string":
|
|
48
|
+
return isinstance(instance, str)
|
|
49
|
+
if type_name == "array":
|
|
50
|
+
return isinstance(instance, list)
|
|
51
|
+
if type_name == "object":
|
|
52
|
+
return isinstance(instance, dict)
|
|
53
|
+
raise ValueError(f"unknown type name {type_name!r}") # gated upstream
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _unbool(element, _true=object(), _false=object()):
|
|
57
|
+
if element is True:
|
|
58
|
+
return _true
|
|
59
|
+
if element is False:
|
|
60
|
+
return _false
|
|
61
|
+
return element
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def equal(one, two) -> bool:
|
|
65
|
+
"""JSON Schema equality: evades bool inheriting from int, recurses."""
|
|
66
|
+
if one is two:
|
|
67
|
+
return True
|
|
68
|
+
if isinstance(one, str) or isinstance(two, str):
|
|
69
|
+
return one == two
|
|
70
|
+
if isinstance(one, list) and isinstance(two, list):
|
|
71
|
+
return len(one) == len(two) and all(equal(i, j) for i, j in zip(one, two))
|
|
72
|
+
if isinstance(one, dict) and isinstance(two, dict):
|
|
73
|
+
return len(one) == len(two) and all(
|
|
74
|
+
key in two and equal(value, two[key]) for key, value in one.items()
|
|
75
|
+
)
|
|
76
|
+
return _unbool(one) == _unbool(two)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def uniq(container) -> bool:
|
|
80
|
+
"""True when all elements are unique under `equal` (sort, else pairwise)."""
|
|
81
|
+
try:
|
|
82
|
+
sort = sorted(_unbool(i) for i in container)
|
|
83
|
+
for i, j in zip(sort, sort[1:]):
|
|
84
|
+
if equal(i, j):
|
|
85
|
+
return False
|
|
86
|
+
except TypeError:
|
|
87
|
+
seen = []
|
|
88
|
+
for e in container:
|
|
89
|
+
e = _unbool(e)
|
|
90
|
+
for i in seen:
|
|
91
|
+
if equal(i, e):
|
|
92
|
+
return False
|
|
93
|
+
seen.append(e)
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def iter_errors(schema, instance) -> "list[Record]":
|
|
98
|
+
return list(_walk(schema, instance, (), ()))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _walk(schema, instance, ipath: tuple, spath: tuple):
|
|
102
|
+
if schema is True:
|
|
103
|
+
return
|
|
104
|
+
if schema is False:
|
|
105
|
+
yield ("false", ipath, spath)
|
|
106
|
+
return
|
|
107
|
+
# Iterate in schema-dict insertion order, like the reference validator.
|
|
108
|
+
for keyword, value in schema.items():
|
|
109
|
+
if keyword == "type":
|
|
110
|
+
types = [value] if isinstance(value, str) else value
|
|
111
|
+
if not any(is_type(instance, t) for t in types):
|
|
112
|
+
yield ("type", ipath, spath + ("type",))
|
|
113
|
+
elif keyword == "enum":
|
|
114
|
+
if all(not equal(each, instance) for each in value):
|
|
115
|
+
yield ("enum", ipath, spath + ("enum",))
|
|
116
|
+
elif keyword == "const":
|
|
117
|
+
if not equal(instance, value):
|
|
118
|
+
yield ("const", ipath, spath + ("const",))
|
|
119
|
+
elif keyword == "minimum":
|
|
120
|
+
if is_type(instance, "number") and instance < value:
|
|
121
|
+
yield ("minimum", ipath, spath + ("minimum",))
|
|
122
|
+
elif keyword == "maximum":
|
|
123
|
+
if is_type(instance, "number") and instance > value:
|
|
124
|
+
yield ("maximum", ipath, spath + ("maximum",))
|
|
125
|
+
elif keyword == "exclusiveMinimum":
|
|
126
|
+
if is_type(instance, "number") and instance <= value:
|
|
127
|
+
yield ("exclusiveMinimum", ipath, spath + ("exclusiveMinimum",))
|
|
128
|
+
elif keyword == "exclusiveMaximum":
|
|
129
|
+
if is_type(instance, "number") and instance >= value:
|
|
130
|
+
yield ("exclusiveMaximum", ipath, spath + ("exclusiveMaximum",))
|
|
131
|
+
elif keyword == "multipleOf":
|
|
132
|
+
if not is_type(instance, "number"):
|
|
133
|
+
continue
|
|
134
|
+
if isinstance(value, float):
|
|
135
|
+
quotient = instance / value
|
|
136
|
+
try:
|
|
137
|
+
failed = int(quotient) != quotient
|
|
138
|
+
except OverflowError:
|
|
139
|
+
# Exact path for quotients too large to truncate to int.
|
|
140
|
+
failed = (Fraction(instance) / Fraction(value)).denominator != 1
|
|
141
|
+
else:
|
|
142
|
+
failed = bool(instance % value)
|
|
143
|
+
if failed:
|
|
144
|
+
yield ("multipleOf", ipath, spath + ("multipleOf",))
|
|
145
|
+
elif keyword == "minLength":
|
|
146
|
+
if is_type(instance, "string") and len(instance) < value:
|
|
147
|
+
yield ("minLength", ipath, spath + ("minLength",))
|
|
148
|
+
elif keyword == "maxLength":
|
|
149
|
+
if is_type(instance, "string") and len(instance) > value:
|
|
150
|
+
yield ("maxLength", ipath, spath + ("maxLength",))
|
|
151
|
+
elif keyword == "pattern":
|
|
152
|
+
if is_type(instance, "string") and not re.search(value, instance):
|
|
153
|
+
yield ("pattern", ipath, spath + ("pattern",))
|
|
154
|
+
elif keyword == "minItems":
|
|
155
|
+
if is_type(instance, "array") and len(instance) < value:
|
|
156
|
+
yield ("minItems", ipath, spath + ("minItems",))
|
|
157
|
+
elif keyword == "maxItems":
|
|
158
|
+
if is_type(instance, "array") and len(instance) > value:
|
|
159
|
+
yield ("maxItems", ipath, spath + ("maxItems",))
|
|
160
|
+
elif keyword == "uniqueItems":
|
|
161
|
+
if value and is_type(instance, "array") and not uniq(instance):
|
|
162
|
+
yield ("uniqueItems", ipath, spath + ("uniqueItems",))
|
|
163
|
+
elif keyword == "minProperties":
|
|
164
|
+
if is_type(instance, "object") and len(instance) < value:
|
|
165
|
+
yield ("minProperties", ipath, spath + ("minProperties",))
|
|
166
|
+
elif keyword == "maxProperties":
|
|
167
|
+
if is_type(instance, "object") and len(instance) > value:
|
|
168
|
+
yield ("maxProperties", ipath, spath + ("maxProperties",))
|
|
169
|
+
elif keyword == "required":
|
|
170
|
+
if not is_type(instance, "object"):
|
|
171
|
+
continue
|
|
172
|
+
for prop in value:
|
|
173
|
+
if prop not in instance:
|
|
174
|
+
yield ("required", ipath, spath + ("required",))
|
|
175
|
+
elif keyword == "properties":
|
|
176
|
+
if not is_type(instance, "object"):
|
|
177
|
+
continue
|
|
178
|
+
for prop, subschema in value.items():
|
|
179
|
+
if prop in instance:
|
|
180
|
+
yield from _walk(
|
|
181
|
+
subschema,
|
|
182
|
+
instance[prop],
|
|
183
|
+
ipath + (prop,),
|
|
184
|
+
spath + ("properties", prop),
|
|
185
|
+
)
|
|
186
|
+
elif keyword == "items":
|
|
187
|
+
if not is_type(instance, "array"):
|
|
188
|
+
continue
|
|
189
|
+
if value is False:
|
|
190
|
+
if len(instance) > 0:
|
|
191
|
+
yield ("items", ipath, spath + ("items",))
|
|
192
|
+
else:
|
|
193
|
+
for index, element in enumerate(instance):
|
|
194
|
+
yield from _walk(
|
|
195
|
+
value,
|
|
196
|
+
element,
|
|
197
|
+
ipath + (index,),
|
|
198
|
+
spath + ("items",),
|
|
199
|
+
)
|
|
200
|
+
elif keyword == "additionalProperties":
|
|
201
|
+
if not is_type(instance, "object"):
|
|
202
|
+
continue
|
|
203
|
+
properties = schema.get("properties", {})
|
|
204
|
+
extras = [k for k in instance if k not in properties]
|
|
205
|
+
if value is False:
|
|
206
|
+
if extras:
|
|
207
|
+
yield ("additionalProperties", ipath, spath + ("additionalProperties",))
|
|
208
|
+
elif value is not True:
|
|
209
|
+
for extra in extras:
|
|
210
|
+
yield from _walk(
|
|
211
|
+
value,
|
|
212
|
+
instance[extra],
|
|
213
|
+
ipath + (extra,),
|
|
214
|
+
spath + ("additionalProperties",),
|
|
215
|
+
)
|
|
216
|
+
# Anything else was rejected by the subset gate (or is an inert
|
|
217
|
+
# annotation the reference also ignores).
|
jsonschema_mojo/core.py
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
"""Drop-in JSON Schema validation (draft 2020-12 subset), Mojo-accelerated.
|
|
2
|
+
|
|
3
|
+
Public surface mirrors the `jsonschema` package: ``validate(instance,
|
|
4
|
+
schema)``, ``Validator(schema).iter_errors(instance)`` /
|
|
5
|
+
``.validate(instance)`` / ``.is_valid(instance)``, and ``ValidationError``
|
|
6
|
+
with the same attributes (``message``, ``absolute_path``, ``json_path``,
|
|
7
|
+
``validator``, ``validator_value``, ``instance``, ``schema``,
|
|
8
|
+
``absolute_schema_path``, ``context``).
|
|
9
|
+
|
|
10
|
+
Validation runs on the native Mojo kernel when its shared library is
|
|
11
|
+
available (macOS arm64 / Linux x86_64 wheels) and the schema/instance pair
|
|
12
|
+
is exactly representable, and transparently falls back to the vendored
|
|
13
|
+
pure-Python reference implementation otherwise. Both backends must agree
|
|
14
|
+
with the `jsonschema` package; the differential suite asserts pass/fail and
|
|
15
|
+
failing-path-set parity on both paths.
|
|
16
|
+
|
|
17
|
+
Documented divergences from the `jsonschema` package (parity contract is
|
|
18
|
+
pass/fail outcome + the set of failing instance JSON paths):
|
|
19
|
+
|
|
20
|
+
* Error *ordering* is not part of the contract. The native backend emits
|
|
21
|
+
errors in a fixed canonical keyword order; the reference orders errors by
|
|
22
|
+
schema-dict insertion order (and set-iteration order for
|
|
23
|
+
additionalProperties). ``validate()`` raises the best match by the same
|
|
24
|
+
relevance heuristic (deepest path wins).
|
|
25
|
+
* Error message *text* parity is best-effort: messages for every supported
|
|
26
|
+
keyword use the reference's templates and are asserted exact in the test
|
|
27
|
+
suite; ``str(error)`` is the message only (the reference appends
|
|
28
|
+
schema/instance excerpts).
|
|
29
|
+
* Schemas using keywords outside the supported subset raise
|
|
30
|
+
``UnsupportedSchemaError`` instead of being applied ($ref, allOf/anyOf/
|
|
31
|
+
oneOf/not, if/then/else, patternProperties, prefixItems, contains,
|
|
32
|
+
propertyNames, dependent*, unevaluated*, format assertion, ...).
|
|
33
|
+
Annotation keywords ($schema, $id, $defs/definitions, title, description,
|
|
34
|
+
default, examples, deprecated, readOnly/writeOnly, $comment, $anchor,
|
|
35
|
+
$dynamicAnchor, $vocabulary, format, content*) are ignored, matching the
|
|
36
|
+
reference's default (no format checker) behaviour.
|
|
37
|
+
* The native path validates the JSON-document projection of the instance
|
|
38
|
+
(what ``json.dumps`` produces). Instances containing tuples, non-string
|
|
39
|
+
dict keys, Decimals, non-finite floats, or integers beyond ±2**53 are not
|
|
40
|
+
JSON documents; they are detected (serialization failure or a kernel
|
|
41
|
+
big-number flag) and validated by the exact pure-Python fallback, which
|
|
42
|
+
mirrors the reference on arbitrary Python objects.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import json
|
|
48
|
+
import re
|
|
49
|
+
import struct
|
|
50
|
+
from collections import deque
|
|
51
|
+
from fractions import Fraction
|
|
52
|
+
|
|
53
|
+
from jsonschema_mojo import _reference
|
|
54
|
+
from jsonschema_mojo._native import (
|
|
55
|
+
FLAG_BIG_NUMBER,
|
|
56
|
+
NativeSchema,
|
|
57
|
+
NativeUnavailable,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"Draft202012Validator",
|
|
62
|
+
"UnsupportedSchemaError",
|
|
63
|
+
"ValidationError",
|
|
64
|
+
"Validator",
|
|
65
|
+
"iter_errors",
|
|
66
|
+
"validate",
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
_TYPE_NAMES = frozenset(
|
|
70
|
+
{"null", "boolean", "object", "array", "number", "integer", "string"}
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
_SUPPORTED_KEYWORDS = frozenset(
|
|
74
|
+
{
|
|
75
|
+
"type",
|
|
76
|
+
"properties",
|
|
77
|
+
"required",
|
|
78
|
+
"items",
|
|
79
|
+
"additionalProperties",
|
|
80
|
+
"enum",
|
|
81
|
+
"const",
|
|
82
|
+
"minimum",
|
|
83
|
+
"maximum",
|
|
84
|
+
"exclusiveMinimum",
|
|
85
|
+
"exclusiveMaximum",
|
|
86
|
+
"minLength",
|
|
87
|
+
"maxLength",
|
|
88
|
+
"pattern",
|
|
89
|
+
"minItems",
|
|
90
|
+
"maxItems",
|
|
91
|
+
"uniqueItems",
|
|
92
|
+
"minProperties",
|
|
93
|
+
"maxProperties",
|
|
94
|
+
"multipleOf",
|
|
95
|
+
}
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# Keywords with no validation effect under the reference's default
|
|
99
|
+
# configuration (annotations and inert structure): ignored, as the
|
|
100
|
+
# reference ignores them.
|
|
101
|
+
_INERT_KEYWORDS = frozenset(
|
|
102
|
+
{
|
|
103
|
+
"$schema",
|
|
104
|
+
"$id",
|
|
105
|
+
"$anchor",
|
|
106
|
+
"$comment",
|
|
107
|
+
"$defs",
|
|
108
|
+
"$dynamicAnchor",
|
|
109
|
+
"$vocabulary",
|
|
110
|
+
"definitions",
|
|
111
|
+
"title",
|
|
112
|
+
"description",
|
|
113
|
+
"default",
|
|
114
|
+
"deprecated",
|
|
115
|
+
"readOnly",
|
|
116
|
+
"writeOnly",
|
|
117
|
+
"examples",
|
|
118
|
+
"format",
|
|
119
|
+
"contentEncoding",
|
|
120
|
+
"contentMediaType",
|
|
121
|
+
"contentSchema",
|
|
122
|
+
}
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# Kernel error-record keyword codes (bit positions), mirrored from
|
|
126
|
+
# kernels/jsonschema/src/jsonschemamojo.mojo.
|
|
127
|
+
_KW_BY_CODE = (
|
|
128
|
+
"type", # 0
|
|
129
|
+
"properties", # 1
|
|
130
|
+
"required", # 2
|
|
131
|
+
"items", # 3
|
|
132
|
+
"additionalProperties", # 4
|
|
133
|
+
"enum", # 5
|
|
134
|
+
"const", # 6
|
|
135
|
+
"minimum", # 7
|
|
136
|
+
"maximum", # 8
|
|
137
|
+
"exclusiveMinimum", # 9
|
|
138
|
+
"exclusiveMaximum", # 10
|
|
139
|
+
"minLength", # 11
|
|
140
|
+
"maxLength", # 12
|
|
141
|
+
"pattern", # 13
|
|
142
|
+
"minItems", # 14
|
|
143
|
+
"maxItems", # 15
|
|
144
|
+
"uniqueItems", # 16
|
|
145
|
+
"minProperties", # 17
|
|
146
|
+
"maxProperties", # 18
|
|
147
|
+
"multipleOf", # 19
|
|
148
|
+
"false", # 20
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
_REC_ERROR = 0
|
|
152
|
+
_REC_DEFER = 1
|
|
153
|
+
|
|
154
|
+
_JSON_PATH_COMPATIBLE_PROPERTY = re.compile("^[a-zA-Z][a-zA-Z0-9_]*$")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class UnsupportedSchemaError(ValueError): # noqa: N818
|
|
158
|
+
"""The schema uses a keyword or value shape outside the supported subset."""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class ValidationError(Exception):
|
|
162
|
+
"""An instance was invalid under a provided schema.
|
|
163
|
+
|
|
164
|
+
Attribute-compatible with ``jsonschema.exceptions.ValidationError`` for
|
|
165
|
+
the supported subset. ``__str__`` is the message (the reference class
|
|
166
|
+
appends schema/instance excerpts; message text itself is identical).
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
def __init__(
|
|
170
|
+
self,
|
|
171
|
+
message: str,
|
|
172
|
+
*,
|
|
173
|
+
path,
|
|
174
|
+
schema_path,
|
|
175
|
+
validator,
|
|
176
|
+
validator_value,
|
|
177
|
+
instance,
|
|
178
|
+
schema,
|
|
179
|
+
) -> None:
|
|
180
|
+
super().__init__(message)
|
|
181
|
+
self.message = message
|
|
182
|
+
self.path = deque(path)
|
|
183
|
+
self.absolute_path = deque(path)
|
|
184
|
+
self.schema_path = deque(schema_path)
|
|
185
|
+
self.absolute_schema_path = deque(schema_path)
|
|
186
|
+
self.validator = validator
|
|
187
|
+
self.validator_value = validator_value
|
|
188
|
+
self.instance = instance
|
|
189
|
+
self.schema = schema
|
|
190
|
+
self.context: list = []
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def json_path(self) -> str:
|
|
194
|
+
path = "$"
|
|
195
|
+
for elem in self.absolute_path:
|
|
196
|
+
if isinstance(elem, int):
|
|
197
|
+
path += "[" + str(elem) + "]"
|
|
198
|
+
elif _JSON_PATH_COMPATIBLE_PROPERTY.match(elem):
|
|
199
|
+
path += "." + elem
|
|
200
|
+
else:
|
|
201
|
+
escaped = elem.replace("\\", "\\\\").replace("'", "\\'")
|
|
202
|
+
path += "['" + escaped + "']"
|
|
203
|
+
return path
|
|
204
|
+
|
|
205
|
+
def __str__(self) -> str:
|
|
206
|
+
return self.message
|
|
207
|
+
|
|
208
|
+
def __repr__(self) -> str:
|
|
209
|
+
return f"<ValidationError: {self.message!r}>"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
# --------------------------------------------------------------------------
|
|
213
|
+
# Subset gate
|
|
214
|
+
# --------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _check_schema(schema, spath: str = "$") -> None:
|
|
218
|
+
"""Reject schemas outside the supported subset. Never silently ignores a
|
|
219
|
+
validation-affecting keyword (the reference would apply it)."""
|
|
220
|
+
if isinstance(schema, bool):
|
|
221
|
+
return
|
|
222
|
+
if not isinstance(schema, dict):
|
|
223
|
+
raise UnsupportedSchemaError(
|
|
224
|
+
f"schema at {spath} must be an object or boolean, "
|
|
225
|
+
f"got {type(schema).__name__}"
|
|
226
|
+
)
|
|
227
|
+
for key, value in schema.items():
|
|
228
|
+
if not isinstance(key, str):
|
|
229
|
+
raise UnsupportedSchemaError(
|
|
230
|
+
f"schema at {spath} has a non-string key {key!r}"
|
|
231
|
+
)
|
|
232
|
+
loc = f"{spath}.{key}"
|
|
233
|
+
if key in _INERT_KEYWORDS:
|
|
234
|
+
continue
|
|
235
|
+
if key not in _SUPPORTED_KEYWORDS:
|
|
236
|
+
raise UnsupportedSchemaError(
|
|
237
|
+
f"keyword {key!r} at {spath} is outside the supported "
|
|
238
|
+
"draft 2020-12 subset (see jsonschema_mojo's README)"
|
|
239
|
+
)
|
|
240
|
+
if key == "type":
|
|
241
|
+
names = [value] if isinstance(value, str) else value
|
|
242
|
+
if (
|
|
243
|
+
not isinstance(names, list)
|
|
244
|
+
or not names
|
|
245
|
+
or any(not isinstance(t, str) or t not in _TYPE_NAMES for t in names)
|
|
246
|
+
):
|
|
247
|
+
raise UnsupportedSchemaError(
|
|
248
|
+
f"'type' at {loc} must be one of {sorted(_TYPE_NAMES)} "
|
|
249
|
+
"or a non-empty list of those"
|
|
250
|
+
)
|
|
251
|
+
elif key == "properties":
|
|
252
|
+
if not isinstance(value, dict):
|
|
253
|
+
raise UnsupportedSchemaError(f"'properties' at {loc} must be an object")
|
|
254
|
+
for prop_name, subschema in value.items():
|
|
255
|
+
if not isinstance(prop_name, str):
|
|
256
|
+
raise UnsupportedSchemaError(
|
|
257
|
+
f"'properties' at {loc} has a non-string key {prop_name!r}"
|
|
258
|
+
)
|
|
259
|
+
_check_schema(subschema, f"{loc}.{prop_name}")
|
|
260
|
+
elif key == "required":
|
|
261
|
+
if not isinstance(value, list) or any(
|
|
262
|
+
not isinstance(p, str) for p in value
|
|
263
|
+
):
|
|
264
|
+
raise UnsupportedSchemaError(
|
|
265
|
+
f"'required' at {loc} must be a list of strings"
|
|
266
|
+
)
|
|
267
|
+
elif key in ("items", "additionalProperties"):
|
|
268
|
+
if not isinstance(value, (dict, bool)):
|
|
269
|
+
raise UnsupportedSchemaError(
|
|
270
|
+
f"{key!r} at {loc} must be a schema (object or boolean)"
|
|
271
|
+
)
|
|
272
|
+
_check_schema(value, loc)
|
|
273
|
+
elif key == "enum":
|
|
274
|
+
if not isinstance(value, list):
|
|
275
|
+
raise UnsupportedSchemaError(f"'enum' at {loc} must be a list")
|
|
276
|
+
elif key == "const":
|
|
277
|
+
pass # any JSON value
|
|
278
|
+
elif key in ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"):
|
|
279
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
280
|
+
raise UnsupportedSchemaError(f"{key!r} at {loc} must be a number")
|
|
281
|
+
elif key in (
|
|
282
|
+
"minLength",
|
|
283
|
+
"maxLength",
|
|
284
|
+
"minItems",
|
|
285
|
+
"maxItems",
|
|
286
|
+
"minProperties",
|
|
287
|
+
"maxProperties",
|
|
288
|
+
):
|
|
289
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
290
|
+
raise UnsupportedSchemaError(
|
|
291
|
+
f"{key!r} at {loc} must be a non-negative integer"
|
|
292
|
+
)
|
|
293
|
+
elif key == "pattern":
|
|
294
|
+
if not isinstance(value, str):
|
|
295
|
+
raise UnsupportedSchemaError(f"'pattern' at {loc} must be a string")
|
|
296
|
+
elif key == "multipleOf":
|
|
297
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
298
|
+
raise UnsupportedSchemaError(f"'multipleOf' at {loc} must be a number")
|
|
299
|
+
if value == 0:
|
|
300
|
+
raise UnsupportedSchemaError(
|
|
301
|
+
f"'multipleOf' at {loc} must be non-zero"
|
|
302
|
+
)
|
|
303
|
+
elif key == "uniqueItems":
|
|
304
|
+
if not isinstance(value, bool):
|
|
305
|
+
raise UnsupportedSchemaError(f"'uniqueItems' at {loc} must be a boolean")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# --------------------------------------------------------------------------
|
|
309
|
+
# Native record decoding
|
|
310
|
+
# --------------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _dumps(obj) -> bytes:
|
|
314
|
+
"""Canonical JSON text for the kernel: ASCII-only, no NaN/Infinity."""
|
|
315
|
+
return json.dumps(
|
|
316
|
+
obj, ensure_ascii=True, allow_nan=False, separators=(",", ":")
|
|
317
|
+
).encode("ascii")
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _decode_segment(mv: memoryview, pos: int):
|
|
321
|
+
tag = mv[pos]
|
|
322
|
+
pos += 1
|
|
323
|
+
if tag == 1:
|
|
324
|
+
(index,) = struct.unpack_from("<q", mv, pos)
|
|
325
|
+
return index, pos + 8
|
|
326
|
+
(length,) = struct.unpack_from("<I", mv, pos)
|
|
327
|
+
pos += 4
|
|
328
|
+
key = bytes(mv[pos : pos + length]).decode("utf-8", errors="surrogatepass")
|
|
329
|
+
return key, pos + length
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _decode_records(payload: bytes) -> list[tuple[int, str, tuple, tuple]]:
|
|
333
|
+
"""Decode the kernel's record stream: (kind, keyword, ipath, spath)."""
|
|
334
|
+
mv = memoryview(payload)
|
|
335
|
+
pos = 0
|
|
336
|
+
out = []
|
|
337
|
+
while pos < len(mv):
|
|
338
|
+
kind = mv[pos]
|
|
339
|
+
kw = _KW_BY_CODE[mv[pos + 1]]
|
|
340
|
+
n_inst, n_schema = struct.unpack_from("<HH", mv, pos + 2)
|
|
341
|
+
pos += 6
|
|
342
|
+
ipath = []
|
|
343
|
+
for _ in range(n_inst):
|
|
344
|
+
seg, pos = _decode_segment(mv, pos)
|
|
345
|
+
ipath.append(seg)
|
|
346
|
+
spath = []
|
|
347
|
+
for _ in range(n_schema):
|
|
348
|
+
seg, pos = _decode_segment(mv, pos)
|
|
349
|
+
spath.append(seg)
|
|
350
|
+
out.append((kind, kw, tuple(ipath), tuple(spath)))
|
|
351
|
+
return out
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _navigate(obj, path: tuple):
|
|
355
|
+
for seg in path:
|
|
356
|
+
obj = obj[seg]
|
|
357
|
+
return obj
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
# --------------------------------------------------------------------------
|
|
361
|
+
# Error message rendering (reference templates)
|
|
362
|
+
# --------------------------------------------------------------------------
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _message(kw: str, inst_sub, subschema, missing_prop) -> str:
|
|
366
|
+
if kw == "false":
|
|
367
|
+
return f"False schema does not allow {inst_sub!r}"
|
|
368
|
+
value = subschema[kw]
|
|
369
|
+
if kw == "type":
|
|
370
|
+
types = [value] if isinstance(value, str) else value
|
|
371
|
+
reprs = ", ".join(repr(t) for t in types)
|
|
372
|
+
return f"{inst_sub!r} is not of type {reprs}"
|
|
373
|
+
if kw == "required":
|
|
374
|
+
return f"{missing_prop!r} is a required property"
|
|
375
|
+
if kw == "minimum":
|
|
376
|
+
return f"{inst_sub!r} is less than the minimum of {value!r}"
|
|
377
|
+
if kw == "maximum":
|
|
378
|
+
return f"{inst_sub!r} is greater than the maximum of {value!r}"
|
|
379
|
+
if kw == "exclusiveMinimum":
|
|
380
|
+
return f"{inst_sub!r} is less than or equal to the minimum of {value!r}"
|
|
381
|
+
if kw == "exclusiveMaximum":
|
|
382
|
+
return f"{inst_sub!r} is greater than or equal to the maximum of {value!r}"
|
|
383
|
+
if kw == "multipleOf":
|
|
384
|
+
return f"{inst_sub!r} is not a multiple of {value}"
|
|
385
|
+
if kw in ("minLength", "minItems"):
|
|
386
|
+
word = "should be non-empty" if value == 1 else "is too short"
|
|
387
|
+
return f"{inst_sub!r} {word}"
|
|
388
|
+
if kw in ("maxLength", "maxItems"):
|
|
389
|
+
word = "is expected to be empty" if value == 0 else "is too long"
|
|
390
|
+
return f"{inst_sub!r} {word}"
|
|
391
|
+
if kw == "pattern":
|
|
392
|
+
return f"{inst_sub!r} does not match {value!r}"
|
|
393
|
+
if kw == "uniqueItems":
|
|
394
|
+
return f"{inst_sub!r} has non-unique elements"
|
|
395
|
+
if kw == "minProperties":
|
|
396
|
+
word = "should be non-empty" if value == 1 else "does not have enough properties"
|
|
397
|
+
return f"{inst_sub!r} {word}"
|
|
398
|
+
if kw == "maxProperties":
|
|
399
|
+
word = "is expected to be empty" if value == 0 else "has too many properties"
|
|
400
|
+
return f"{inst_sub!r} {word}"
|
|
401
|
+
if kw == "enum":
|
|
402
|
+
return f"{inst_sub!r} is not one of {value!r}"
|
|
403
|
+
if kw == "const":
|
|
404
|
+
return f"{value!r} was expected"
|
|
405
|
+
if kw == "additionalProperties":
|
|
406
|
+
properties = subschema.get("properties", {})
|
|
407
|
+
extras = sorted((k for k in inst_sub if k not in properties), key=str)
|
|
408
|
+
verb = "was" if len(extras) == 1 else "were"
|
|
409
|
+
joined = ", ".join(repr(each) for each in extras)
|
|
410
|
+
return f"Additional properties are not allowed ({joined} {verb} unexpected)"
|
|
411
|
+
if kw == "items":
|
|
412
|
+
# Only reachable when `items` is false: one aggregate error.
|
|
413
|
+
count = len(inst_sub)
|
|
414
|
+
rest = inst_sub if count != 1 else inst_sub[0]
|
|
415
|
+
return f"Expected at most 0 items but found {count} extra: {rest!r}"
|
|
416
|
+
raise ValueError(f"no message template for keyword {kw!r}") # unreachable
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _best_match(errors: list[ValidationError]) -> ValidationError:
|
|
420
|
+
"""Mirror the reference's relevance heuristic for the supported subset:
|
|
421
|
+
the deepest error wins (the weak/strong keyword classes and the
|
|
422
|
+
type-match tiebreak are all constant within the subset); ties break by
|
|
423
|
+
path (numeric segments numerically, like the reference)."""
|
|
424
|
+
|
|
425
|
+
def key(error: ValidationError):
|
|
426
|
+
return (
|
|
427
|
+
-len(error.absolute_path),
|
|
428
|
+
tuple(
|
|
429
|
+
(0, part) if isinstance(part, int) else (1, part)
|
|
430
|
+
for part in error.absolute_path
|
|
431
|
+
),
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
return max(errors, key=key)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
# --------------------------------------------------------------------------
|
|
438
|
+
# Validator
|
|
439
|
+
# --------------------------------------------------------------------------
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class Validator:
|
|
443
|
+
"""Draft 2020-12 (subset) validator. API-compatible with the reference's
|
|
444
|
+
``Draft202012Validator`` for the supported keywords."""
|
|
445
|
+
|
|
446
|
+
def __init__(self, schema) -> None:
|
|
447
|
+
_check_schema(schema)
|
|
448
|
+
self.schema = schema
|
|
449
|
+
self._native: NativeSchema | None = None
|
|
450
|
+
self._backend = "fallback"
|
|
451
|
+
try:
|
|
452
|
+
schema_text = _dumps(schema)
|
|
453
|
+
except (TypeError, ValueError, OverflowError):
|
|
454
|
+
schema_text = None # not JSON-representable: always fall back
|
|
455
|
+
if schema_text is not None:
|
|
456
|
+
native = None
|
|
457
|
+
try:
|
|
458
|
+
native = NativeSchema(schema_text)
|
|
459
|
+
except NativeUnavailable:
|
|
460
|
+
native = None
|
|
461
|
+
if native is not None:
|
|
462
|
+
if native.flags & FLAG_BIG_NUMBER:
|
|
463
|
+
# Schema numbers must be exact; the kernel flags >15-digit
|
|
464
|
+
# integer literals and we validate with the fallback.
|
|
465
|
+
native.close()
|
|
466
|
+
else:
|
|
467
|
+
self._native = native
|
|
468
|
+
self._backend = "native"
|
|
469
|
+
|
|
470
|
+
@property
|
|
471
|
+
def backend(self) -> str:
|
|
472
|
+
"""Which engine serves this instance: "native" or "fallback"."""
|
|
473
|
+
return self._backend
|
|
474
|
+
|
|
475
|
+
# -- validation -------------------------------------------------------
|
|
476
|
+
|
|
477
|
+
def _records(self, instance) -> list[tuple[str, tuple, tuple]]:
|
|
478
|
+
"""(keyword, instance_path, schema_path) records from the active backend."""
|
|
479
|
+
if self._native is not None:
|
|
480
|
+
try:
|
|
481
|
+
instance_text = _dumps(instance)
|
|
482
|
+
except (TypeError, ValueError, OverflowError):
|
|
483
|
+
instance_text = None # not a JSON document: exact fallback
|
|
484
|
+
if instance_text is not None:
|
|
485
|
+
try:
|
|
486
|
+
payload, _n_err, _n_defer, big = self._native.validate_records(
|
|
487
|
+
instance_text
|
|
488
|
+
)
|
|
489
|
+
except NativeUnavailable:
|
|
490
|
+
payload = None
|
|
491
|
+
if payload is not None and not big:
|
|
492
|
+
return self._resolve_defers(_decode_records(payload), instance)
|
|
493
|
+
return _reference.iter_errors(self.schema, instance)
|
|
494
|
+
|
|
495
|
+
def _resolve_defers(self, records, instance) -> list[tuple[str, tuple, tuple]]:
|
|
496
|
+
"""Evaluate kernel-deferred checks (regex patterns, exact multipleOf
|
|
497
|
+
edge cases) with the original Python objects, in record order."""
|
|
498
|
+
out = []
|
|
499
|
+
for kind, kw, ipath, spath in records:
|
|
500
|
+
if kind == _REC_ERROR:
|
|
501
|
+
out.append((kw, ipath, spath))
|
|
502
|
+
continue
|
|
503
|
+
inst_sub = _navigate(instance, ipath)
|
|
504
|
+
subschema = _navigate(self.schema, spath[:-1])
|
|
505
|
+
if kw == "pattern":
|
|
506
|
+
if not re.search(subschema["pattern"], inst_sub):
|
|
507
|
+
out.append((kw, ipath, spath))
|
|
508
|
+
elif kw == "multipleOf":
|
|
509
|
+
divisor = subschema["multipleOf"]
|
|
510
|
+
if isinstance(divisor, float):
|
|
511
|
+
quotient = inst_sub / divisor
|
|
512
|
+
try:
|
|
513
|
+
failed = int(quotient) != quotient
|
|
514
|
+
except OverflowError:
|
|
515
|
+
failed = (
|
|
516
|
+
Fraction(inst_sub) / Fraction(divisor)
|
|
517
|
+
).denominator != 1
|
|
518
|
+
else:
|
|
519
|
+
failed = bool(inst_sub % divisor)
|
|
520
|
+
if failed:
|
|
521
|
+
out.append((kw, ipath, spath))
|
|
522
|
+
return out
|
|
523
|
+
|
|
524
|
+
# -- public API (mirrors the reference Validator) ---------------------
|
|
525
|
+
|
|
526
|
+
def iter_errors(self, instance):
|
|
527
|
+
records = self._records(instance)
|
|
528
|
+
# required errors: the record does not name the missing property;
|
|
529
|
+
# assign missing properties (in `required` order) per occurrence.
|
|
530
|
+
occurrence: dict[tuple, int] = {}
|
|
531
|
+
errors = []
|
|
532
|
+
for kw, ipath, spath in records:
|
|
533
|
+
key = (kw, ipath, spath)
|
|
534
|
+
n = occurrence.get(key, 0)
|
|
535
|
+
occurrence[key] = n + 1
|
|
536
|
+
missing_prop = None
|
|
537
|
+
if kw == "required":
|
|
538
|
+
inst_sub = _navigate(instance, ipath)
|
|
539
|
+
subschema = _navigate(self.schema, spath[:-1])
|
|
540
|
+
missing = [p for p in subschema["required"] if p not in inst_sub]
|
|
541
|
+
missing_prop = missing[min(n, len(missing) - 1)]
|
|
542
|
+
errors.append(
|
|
543
|
+
self._render(kw, ipath, spath, instance, missing_prop)
|
|
544
|
+
)
|
|
545
|
+
return iter(errors)
|
|
546
|
+
|
|
547
|
+
def _render(self, kw, ipath, spath, instance, missing_prop) -> ValidationError:
|
|
548
|
+
inst_sub = _navigate(instance, ipath)
|
|
549
|
+
if kw == "false":
|
|
550
|
+
# Boolean-false subschema: the reference yields the error at the
|
|
551
|
+
# *containing* keyword's level (its descend does not append the
|
|
552
|
+
# final path segments), but the message/instance use the rejected
|
|
553
|
+
# child value. Records carry full paths for navigation; the
|
|
554
|
+
# displayed paths drop the last segment.
|
|
555
|
+
subschema = _navigate(self.schema, spath)
|
|
556
|
+
validator_value = None
|
|
557
|
+
ipath = ipath[:-1]
|
|
558
|
+
spath = spath[:-1]
|
|
559
|
+
else:
|
|
560
|
+
subschema = _navigate(self.schema, spath[:-1])
|
|
561
|
+
validator_value = subschema[kw]
|
|
562
|
+
return ValidationError(
|
|
563
|
+
_message(kw, inst_sub, subschema, missing_prop),
|
|
564
|
+
path=ipath,
|
|
565
|
+
schema_path=spath,
|
|
566
|
+
validator=None if kw == "false" else kw,
|
|
567
|
+
validator_value=validator_value,
|
|
568
|
+
instance=inst_sub,
|
|
569
|
+
schema=subschema,
|
|
570
|
+
)
|
|
571
|
+
|
|
572
|
+
def validate(self, instance) -> None:
|
|
573
|
+
# Mirrors the reference's Validator.validate: raise the first error
|
|
574
|
+
# (in this backend's documented canonical order — see module docs).
|
|
575
|
+
for error in self.iter_errors(instance):
|
|
576
|
+
raise error
|
|
577
|
+
|
|
578
|
+
def is_valid(self, instance) -> bool:
|
|
579
|
+
return not self._records(instance)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def validate(instance, schema) -> None:
|
|
583
|
+
"""Validate ``instance`` under ``schema``, raising the best-matching
|
|
584
|
+
:class:`ValidationError` if invalid. Mirrors ``jsonschema.validate``
|
|
585
|
+
(which additionally metaschema-checks the schema; here the subset gate
|
|
586
|
+
plays that role and raises :class:`UnsupportedSchemaError`)."""
|
|
587
|
+
validator = Validator(schema)
|
|
588
|
+
errors = list(validator.iter_errors(instance))
|
|
589
|
+
if errors:
|
|
590
|
+
raise _best_match(errors)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def iter_errors(instance, schema):
|
|
594
|
+
"""Lazily iterate all validation errors. Mirrors
|
|
595
|
+
``Draft202012Validator(schema).iter_errors(instance)``."""
|
|
596
|
+
return Validator(schema).iter_errors(instance)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
# Drop-in convenience alias: same subset, same call shape as the reference's
|
|
600
|
+
# draft 2020-12 validator class.
|
|
601
|
+
Draft202012Validator = Validator
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: jsonschema-mojo
|
|
3
|
+
Version: 0.2.5
|
|
4
|
+
Summary: Drop-in faster replacement for the jsonschema package (draft 2020-12 subset), powered by a Mojo kernel (pure-Python fallback included).
|
|
5
|
+
Project-URL: Repository, https://github.com/thyn-ai/mojo-kernels
|
|
6
|
+
Project-URL: Company, https://thyn.ai
|
|
7
|
+
Author: Thyn
|
|
8
|
+
Maintainer: Thyn
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
Keywords: draft-2020-12,json,jsonschema,mojo,validation
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# jsonschema-mojo
|
|
19
|
+
|
|
20
|
+
Drop-in faster replacement for the [`jsonschema`](https://pypi.org/project/jsonschema/)
|
|
21
|
+
package (draft 2020-12 subset), powered by a Mojo kernel.
|
|
22
|
+
|
|
23
|
+
Same call shapes, same pass/fail outcomes, same failing instance paths —
|
|
24
|
+
validated by a differential test suite against the published `jsonschema`
|
|
25
|
+
package on both backends. The native Mojo kernel runs on macOS arm64 and
|
|
26
|
+
Linux x86_64; everywhere else (Windows, missing/unloadable kernel, or values
|
|
27
|
+
the native path cannot represent exactly) the package transparently uses a
|
|
28
|
+
vendored pure-Python fallback with identical semantics — tested on Windows
|
|
29
|
+
in CI ([`windows-fallback`](https://github.com/thyn-ai/mojo-kernels/actions/workflows/windows-fallback.yml)). Zero dependencies.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import jsonschema_mojo
|
|
33
|
+
|
|
34
|
+
schema = {
|
|
35
|
+
"type": "object",
|
|
36
|
+
"properties": {
|
|
37
|
+
"name": {"type": "string", "minLength": 1},
|
|
38
|
+
"age": {"type": "integer", "minimum": 0},
|
|
39
|
+
},
|
|
40
|
+
"required": ["name"],
|
|
41
|
+
"additionalProperties": False,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
jsonschema_mojo.validate({"name": "Ada", "age": 36}, schema) # None (valid)
|
|
45
|
+
jsonschema_mojo.validate({"age": -1}, schema) # raises ValidationError
|
|
46
|
+
|
|
47
|
+
validator = jsonschema_mojo.Validator(schema) # compiles the schema once
|
|
48
|
+
validator.is_valid({"name": "Ada"}) # True
|
|
49
|
+
for error in validator.iter_errors({"age": -1}):
|
|
50
|
+
print(error.json_path, error.message)
|
|
51
|
+
# $.age -1 is less than the minimum of 0
|
|
52
|
+
# $ 'name' is a required property
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`ValidationError` mirrors the reference's attributes: `message`,
|
|
56
|
+
`absolute_path`, `json_path`, `absolute_schema_path`, `validator`,
|
|
57
|
+
`validator_value`, `instance`, `schema`, `context`.
|
|
58
|
+
`jsonschema_mojo.Draft202012Validator` is an alias of `Validator`.
|
|
59
|
+
|
|
60
|
+
## Supported schema subset (draft 2020-12)
|
|
61
|
+
|
|
62
|
+
`type`, `properties`, `required`, `items`, `additionalProperties`, `enum`,
|
|
63
|
+
`const`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`,
|
|
64
|
+
`minLength`, `maxLength`, `pattern`, `minItems`, `maxItems`, `uniqueItems`,
|
|
65
|
+
`minProperties`, `maxProperties`, `multipleOf` — plus boolean subschemas
|
|
66
|
+
(`true`/`false`, including `additionalProperties: false` and `items: false`).
|
|
67
|
+
|
|
68
|
+
Annotation/inert keywords are ignored exactly like the reference does by
|
|
69
|
+
default: `$schema`, `$id`, `$defs`/`definitions`, `$anchor`, `$dynamicAnchor`,
|
|
70
|
+
`$comment`, `$vocabulary`, `title`, `description`, `default`, `deprecated`,
|
|
71
|
+
`readOnly`/`writeOnly`, `examples`, `format` (annotation-only without a
|
|
72
|
+
format checker), `contentEncoding`/`contentMediaType`/`contentSchema`.
|
|
73
|
+
|
|
74
|
+
Schemas using any *other* validation-affecting keyword — `$ref`,
|
|
75
|
+
`$dynamicRef`, `allOf`/`anyOf`/`oneOf`/`not`, `if`/`then`/`else`,
|
|
76
|
+
`patternProperties`, `prefixItems`, `contains`, `minContains`/`maxContains`,
|
|
77
|
+
`propertyNames`, `dependentRequired`/`dependentSchemas`/`dependencies`,
|
|
78
|
+
`unevaluatedItems`/`unevaluatedProperties` — raise
|
|
79
|
+
`jsonschema_mojo.UnsupportedSchemaError` at `Validator` construction (and in
|
|
80
|
+
`validate()`), instead of silently validating differently from the
|
|
81
|
+
reference. Invalid keyword value shapes (e.g. `{"type": "frob"}`,
|
|
82
|
+
`{"multipleOf": 0}`) also raise `UnsupportedSchemaError`; the reference's
|
|
83
|
+
`validate()` raises `SchemaError` for these via metaschema checking.
|
|
84
|
+
|
|
85
|
+
## Parity contract with `jsonschema` (measured, not aspirational)
|
|
86
|
+
|
|
87
|
+
Asserted on both backends by `tests/test_jsonschema_differential.py`
|
|
88
|
+
(229 tests per backend: curated per-keyword cases, edge semantics, and a
|
|
89
|
+
seeded randomized schema/instance sweep) against `jsonschema` 4.26.0:
|
|
90
|
+
|
|
91
|
+
- **pass/fail outcome — exact** (100% agreement);
|
|
92
|
+
- **failing instance JSON paths + keywords — exact** (multiset comparison,
|
|
93
|
+
100% agreement);
|
|
94
|
+
- **error message text — exact** for every supported keyword (the
|
|
95
|
+
reference's templates are replicated verbatim; `str(error)` differs: the
|
|
96
|
+
reference appends schema/instance excerpts, this package's `str()` is the
|
|
97
|
+
message itself);
|
|
98
|
+
- **error ordering — not part of the contract** (documented divergence):
|
|
99
|
+
the reference orders errors by schema-dict insertion order, the native
|
|
100
|
+
backend uses a fixed canonical keyword order. `Validator.validate()`
|
|
101
|
+
raises its own first error (identity best-effort; the module-level
|
|
102
|
+
`jsonschema_mojo.validate()` mirrors the reference's `best_match`
|
|
103
|
+
deepest-path heuristic).
|
|
104
|
+
|
|
105
|
+
Edge semantics replicated from the reference: `1.0` counts as `"integer"`;
|
|
106
|
+
booleans are never numbers and `True`/`False` never equal `1`/`0` for
|
|
107
|
+
`const`/`enum`/`uniqueItems` (but `1 == 1.0`); `"array"` is `list`,
|
|
108
|
+
`"object"` is `dict`; `multipleOf` uses floored-modulo semantics for integer
|
|
109
|
+
divisors and the `int(quotient) != quotient` test for float divisors with an
|
|
110
|
+
exact `Fraction` fallback; `pattern` is evaluated with Python's `re` on the
|
|
111
|
+
original string (the kernel defers it), so regex behavior is identical
|
|
112
|
+
—including `re.error` on invalid patterns.
|
|
113
|
+
|
|
114
|
+
## Native path boundaries (auto-degrade to the exact fallback)
|
|
115
|
+
|
|
116
|
+
The native kernel validates the JSON-document projection of the instance
|
|
117
|
+
(what `json.dumps` produces). It detects and silently routes to the
|
|
118
|
+
vendored fallback (which mirrors the reference on arbitrary Python objects)
|
|
119
|
+
when a value is not exactly representable:
|
|
120
|
+
|
|
121
|
+
- integers beyond ±2**53 (kernel big-number flag, in schema or instance);
|
|
122
|
+
- non-finite floats (`NaN`, `±Infinity`) and non-JSON-serializable values
|
|
123
|
+
(`Decimal`, bytes, sets, arbitrary objects) — `json.dumps` failure.
|
|
124
|
+
|
|
125
|
+
Instances containing **tuples** or **non-string dict keys** are not JSON
|
|
126
|
+
documents; the reference does not treat tuples as arrays and does not
|
|
127
|
+
stringify keys. The native path validates their JSON projection (tuple →
|
|
128
|
+
array, `1` → `"1"`), which can differ from the reference for such inputs;
|
|
129
|
+
use `JSONSCHEMA_MOJO_DISABLE_NATIVE=1` (or the oracle) if you rely on
|
|
130
|
+
Python-object semantics there. JSON documents loaded via `json.load` are
|
|
131
|
+
unaffected and always parity-exact.
|
|
132
|
+
|
|
133
|
+
## How it works
|
|
134
|
+
|
|
135
|
+
`Validator(schema)` checks the schema against the subset gate, serializes it
|
|
136
|
+
once (`json.dumps`), and hands it to the Mojo kernel, which parses it into a
|
|
137
|
+
flat node arena and compiles a keyword tree. Per `validate`/`iter_errors`
|
|
138
|
+
call the wrapper serializes the instance (C-speed `json.dumps`) and the
|
|
139
|
+
kernel parses it and walks the compiled schema tree in one pass, streaming
|
|
140
|
+
`(keyword, instance path, schema path)` records back. Error objects and
|
|
141
|
+
messages are then materialized in Python from the original objects; regex
|
|
142
|
+
`pattern` checks and `multipleOf` edge cases are deferred by the kernel to
|
|
143
|
+
the wrapper's exact Python path. Schema and instance never round-trip
|
|
144
|
+
through Python object reconstruction — the walk is fully native.
|
|
145
|
+
|
|
146
|
+
## Benchmarks
|
|
147
|
+
|
|
148
|
+
Measured on this machine (Apple M4 Max, macOS 26.6.2, Python 3.12.14, Mojo
|
|
149
|
+
1.1.0, oracle jsonschema 4.26.0), seed 20260919, median of 5 runs,
|
|
150
|
+
correctness-gated before timing. Reproduce with
|
|
151
|
+
`PYTHONPATH=python/jsonschema_mojo python benchmarks/bench_jsonschema.py`
|
|
152
|
+
from the repository root. Scenarios: **A** = 10,000 order records against a
|
|
153
|
+
shared schema (incl. two `pattern` checks per record, resolved via Python
|
|
154
|
+
`re`); **B** = one ~3 MB nested document (22,500 leaf objects) per call;
|
|
155
|
+
**C** = 2,000 invalid records producing ~4 errors each. Cold = fresh
|
|
156
|
+
`Validator` + first call (gate + native compile + first walk); warm =
|
|
157
|
+
steady-state per document.
|
|
158
|
+
|
|
159
|
+
| scenario | cold jsonschema (ms) | cold jsonschema_mojo (ms) | warm jsonschema (ms/doc) | warm jsonschema_mojo (ms/doc) | warm speedup |
|
|
160
|
+
|---|---:|---:|---:|---:|---:|
|
|
161
|
+
| A: 10k order records | 0.050 | 0.047 | 0.0589 | 0.0189 | 3.1x |
|
|
162
|
+
| B: big nested document | 222.803 | 9.470 | 213.1359 | 9.0478 | 23.6x |
|
|
163
|
+
| C: 2k invalid records | 0.080 | 0.063 | 0.0627 | 0.0292 | 2.1x |
|
|
164
|
+
|
|
165
|
+
Warm throughput: A — 16,976 vs 52,984 docs/s; B — 5 vs 111 docs/s; C —
|
|
166
|
+
15,947 vs 34,244 docs/s. The vendored pure-Python fallback (what Windows
|
|
167
|
+
gets) measured 0.0186 / 66.7 / 0.0396 ms/doc warm on A/B/C — itself ~3x
|
|
168
|
+
faster than the oracle on small documents, and on tiny documents roughly
|
|
169
|
+
equal to the native path (fixed serialization/FFI cost dominates); the
|
|
170
|
+
kernel's advantage grows with document size. Numbers on a shared machine
|
|
171
|
+
varied ±20% run to run; speedup ratios were stable (2.1–3.2x small docs,
|
|
172
|
+
21–28x large).
|
|
173
|
+
|
|
174
|
+
## Backend selection & diagnostics
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
import jsonschema_mojo
|
|
178
|
+
jsonschema_mojo.backend_info() # native source, ABI version, errors
|
|
179
|
+
jsonschema_mojo.native_available() # bool
|
|
180
|
+
jsonschema_mojo.Validator(schema).backend # "native" or "fallback"
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
- `JSONSCHEMA_MOJO_DISABLE_NATIVE=1` forces the fallback (used by the
|
|
184
|
+
differential suite).
|
|
185
|
+
- `JSONSCHEMA_MOJO_NATIVE_LIB=/path/to/libjsonschemamojo.{dylib,so}`
|
|
186
|
+
overrides kernel resolution (development).
|
|
187
|
+
|
|
188
|
+
The wrapper verifies an ABI-version handshake with the kernel before use;
|
|
189
|
+
any mismatch, load failure, or missing library falls back silently.
|
|
190
|
+
|
|
191
|
+
## Tests
|
|
192
|
+
|
|
193
|
+
From the repository root, inside the pixi environment (the jsonschema
|
|
194
|
+
oracle, `jsonschema==4.26.0`, comes from `pixi.toml [pypi-dependencies]`):
|
|
195
|
+
|
|
196
|
+
```bash
|
|
197
|
+
pixi run bash kernels/jsonschema/build.sh
|
|
198
|
+
pixi run bash scripts/test_all_jsonschema.sh # native backend, then forced fallback
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
229 differential tests + 7 loader tests per backend run (native and forced
|
|
202
|
+
fallback).
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
Apache-2.0. Copyright Algenta.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
jsonschema_mojo/__init__.py,sha256=fVO_16Rg0pXPWoO5yUkAe5XxFXXm6VM9o_Fj4qAetaw,1539
|
|
2
|
+
jsonschema_mojo/_native.py,sha256=uLO0FDGSJjN4Iuy_-gEu3zT7B9pyUh7KbC3H9UwPPX4,9867
|
|
3
|
+
jsonschema_mojo/_reference.py,sha256=rdSJUVLXdBPC4OtEUxbea53e-P8EM-6s2YJOYbBOLao,9169
|
|
4
|
+
jsonschema_mojo/core.py,sha256=mqXASHHw5lnKqxWC5humNmwUIrpXKMPBmiyLUEDer0M,22624
|
|
5
|
+
jsonschema_mojo-0.2.5.dist-info/METADATA,sha256=01fx8lsQKH_-Q3u4MmObpM4yXCB-058a1RSRovM0uLY,9910
|
|
6
|
+
jsonschema_mojo-0.2.5.dist-info/WHEEL,sha256=THafob7ofN-NsuMN7Mg4qZyHaQI7KkD-QlcQatYhXPo,87
|
|
7
|
+
jsonschema_mojo-0.2.5.dist-info/RECORD,,
|