structured-data-models-client 2.0.0__cp310-abi3-win_amd64.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.
- sdm_client/__init__.py +128 -0
- sdm_client/_native.pyd +0 -0
- sdm_client/_native.pyi +152 -0
- sdm_client/_relbench.py +175 -0
- sdm_client/_rust/__init__.py +15 -0
- sdm_client/_rust/capabilities.py +42 -0
- sdm_client/_rust/codec.py +532 -0
- sdm_client/_rust/direct.py +883 -0
- sdm_client/_rust/direct_admission.py +205 -0
- sdm_client/_rust/direct_cells.py +223 -0
- sdm_client/_rust/direct_dtypes.py +130 -0
- sdm_client/_rust/direct_io.py +135 -0
- sdm_client/_rust/direct_options.py +106 -0
- sdm_client/_rust/direct_prediction.py +238 -0
- sdm_client/_rust/direct_response.py +632 -0
- sdm_client/_rust/direct_schema.py +532 -0
- sdm_client/_rust/edits.py +352 -0
- sdm_client/_rust/errors.py +821 -0
- sdm_client/_rust/examples.py +120 -0
- sdm_client/_rust/facts.py +161 -0
- sdm_client/_rust/frame_materialize.py +162 -0
- sdm_client/_rust/frame_schema.py +235 -0
- sdm_client/_rust/frame_sessions.py +225 -0
- sdm_client/_rust/host_providers.py +1130 -0
- sdm_client/_rust/labels.py +88 -0
- sdm_client/_rust/materialize.py +472 -0
- sdm_client/_rust/predict.py +686 -0
- sdm_client/_rust/providers/__init__.py +57 -0
- sdm_client/_rust/providers/databricks.py +258 -0
- sdm_client/_rust/providers/duckdb.py +64 -0
- sdm_client/_rust/providers/postgres.py +168 -0
- sdm_client/_rust/providers/postgres_arrow.py +346 -0
- sdm_client/_rust/providers/snowflake.py +152 -0
- sdm_client/_rust/providers/sqlite.py +81 -0
- sdm_client/_rust/rebind.py +57 -0
- sdm_client/_rust/refine.py +97 -0
- sdm_client/_rust/result_items.py +115 -0
- sdm_client/_rust/result_merge.py +265 -0
- sdm_client/_rust/results.py +950 -0
- sdm_client/_rust/run.py +608 -0
- sdm_client/_rust/s0.py +78 -0
- sdm_client/_rust/schema.py +256 -0
- sdm_client/_rust/sessions.py +440 -0
- sdm_client/_rust/spec.py +90 -0
- sdm_client/_rust/splits.py +58 -0
- sdm_client/_rust/sql_column.py +46 -0
- sdm_client/_rust/sql_kit.py +83 -0
- sdm_client/_rust/tabular_index.py +689 -0
- sdm_client/_rust/tabular_materialize.py +546 -0
- sdm_client/_rust/tabular_temporal.py +170 -0
- sdm_client/_version.py +5 -0
- sdm_client/_visualization.py +178 -0
- sdm_client/adapters/__init__.py +9 -0
- sdm_client/adapters/relational.py +311 -0
- sdm_client/adapters/tabular.py +127 -0
- sdm_client/assets/MERMAID_COMPONENTS.json +764 -0
- sdm_client/assets/MERMAID_LICENSE +21 -0
- sdm_client/assets/THIRD-PARTY-NOTICES-MERMAID.txt +891 -0
- sdm_client/assets/VENDORED.md +8 -0
- sdm_client/assets/mermaid.min.js +3405 -0
- sdm_client/assets/relbench/README.md +12 -0
- sdm_client/assets/relbench/overrides.json +74 -0
- sdm_client/assets/relbench/registry.json +1665 -0
- sdm_client/assets/schema.html +8 -0
- sdm_client/base.py +125 -0
- sdm_client/client.py +934 -0
- sdm_client/context_report.py +77 -0
- sdm_client/core/__init__.py +5 -0
- sdm_client/core/databricks_serving.py +695 -0
- sdm_client/core/databricks_user_agent.py +76 -0
- sdm_client/core/dates.py +278 -0
- sdm_client/core/transport.py +1002 -0
- sdm_client/core/warnings.py +51 -0
- sdm_client/decompose.py +203 -0
- sdm_client/errors.py +196 -0
- sdm_client/explanations.py +264 -0
- sdm_client/in_process/__init__.py +14 -0
- sdm_client/in_process/answers.py +137 -0
- sdm_client/in_process/backend.py +607 -0
- sdm_client/in_process/columns.py +298 -0
- sdm_client/in_process/gradients.py +135 -0
- sdm_client/in_process/relational.py +486 -0
- sdm_client/in_process/tables.py +106 -0
- sdm_client/in_process/tabular.py +141 -0
- sdm_client/inference.py +43 -0
- sdm_client/materializers/__init__.py +9 -0
- sdm_client/materializers/relational.py +100 -0
- sdm_client/materializers/sources.py +27 -0
- sdm_client/materializers/tabular.py +76 -0
- sdm_client/models.py +219 -0
- sdm_client/provider.py +1021 -0
- sdm_client/py.typed +0 -0
- sdm_client/query.py +835 -0
- sdm_client/relational_task.py +34 -0
- sdm_client/reports.py +358 -0
- sdm_client/request.py +1175 -0
- sdm_client/result.py +315 -0
- sdm_client/sanitization.py +56 -0
- sdm_client/schema.py +2696 -0
- sdm_client/sources.py +527 -0
- sdm_client/summaries.py +153 -0
- sdm_client/timeseries.py +176 -0
- sdm_client/wire/__init__.py +46 -0
- sdm_client/wire/answers.py +80 -0
- sdm_client/wire/dtypes.py +701 -0
- sdm_client/wire/keys.py +363 -0
- sdm_client/wire/tables.py +50 -0
- structured_data_models_client-2.0.0.dist-info/METADATA +108 -0
- structured_data_models_client-2.0.0.dist-info/RECORD +114 -0
- structured_data_models_client-2.0.0.dist-info/WHEEL +4 -0
- structured_data_models_client-2.0.0.dist-info/licenses/LICENSE +207 -0
- structured_data_models_client-2.0.0.dist-info/licenses/NOTICE +21 -0
- structured_data_models_client-2.0.0.dist-info/licenses/THIRD-PARTY-NOTICES-RUST.txt +5142 -0
- structured_data_models_client-2.0.0.dist-info/sboms/sdm-py.cyclonedx.json +6256 -0
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES.
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
r"""The control-message codec of the Python host.
|
|
6
|
+
|
|
7
|
+
A control message is the contract's JSON, as bytes, with the attachments it
|
|
8
|
+
names in a ``dict`` by id. Two rules come from the contract:
|
|
9
|
+
|
|
10
|
+
- A message the core writes whose encoding would pass the 64 KB control cap
|
|
11
|
+
travels whole as a bytes attachment of its JSON, named by
|
|
12
|
+
``{"message": "attached", "attachment": n}``;:func:`read` gives the
|
|
13
|
+
message that attachment carries.
|
|
14
|
+
- Every scalar is a tagged object whose value is a JSON string, so nothing
|
|
15
|
+
passes through a double.:func:`decode_scalar` reads every
|
|
16
|
+
tag exactly; the encoders, for the scalars this host writes, write only
|
|
17
|
+
what the core's decoder takes, and refuse anything else rather than
|
|
18
|
+
write it.
|
|
19
|
+
|
|
20
|
+
Input-sized fields of a ``start`` travel as bytes attachments of their JSON
|
|
21
|
+
;:func:`attachment` writes one.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import base64
|
|
27
|
+
import decimal
|
|
28
|
+
import fractions
|
|
29
|
+
import json
|
|
30
|
+
import math
|
|
31
|
+
import numbers
|
|
32
|
+
import re
|
|
33
|
+
import struct
|
|
34
|
+
import sys
|
|
35
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
36
|
+
from collections.abc import Set as AbstractSet
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
from decimal import Decimal
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
#: The largest control message, in bytes, in either direction.
|
|
42
|
+
CONTROL_CAP = 64 * 1024
|
|
43
|
+
|
|
44
|
+
_INTEGERS = {
|
|
45
|
+
'i8': (-(2**7), 2**7 - 1),
|
|
46
|
+
'i16': (-(2**15), 2**15 - 1),
|
|
47
|
+
'i32': (-(2**31), 2**31 - 1),
|
|
48
|
+
'i64': (-(2**63), 2**63 - 1),
|
|
49
|
+
'u8': (0, 2**8 - 1),
|
|
50
|
+
'u16': (0, 2**16 - 1),
|
|
51
|
+
'u32': (0, 2**32 - 1),
|
|
52
|
+
'u64': (0, 2**64 - 1),
|
|
53
|
+
}
|
|
54
|
+
_DECIMALS = {'d128': 38, 'd256': 76}
|
|
55
|
+
_TEMPORAL = ('ts', 'duration', 'time64')
|
|
56
|
+
_UNITS = ('ns', 'us')
|
|
57
|
+
_DIGITS = re.compile(r'(0|-?[1-9][0-9]*)\Z')
|
|
58
|
+
_FLOAT = re.compile(r'(NaN|inf|-inf|-?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?)\Z')
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CodecError(ValueError):
|
|
62
|
+
r"""A control message or scalar the contract does not hold.
|
|
63
|
+
|
|
64
|
+
It names the position or the tag, never the text it read, which may be
|
|
65
|
+
an input value.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class Temporal:
|
|
71
|
+
r"""A temporal scalar as the contract counts it: ``value`` in ``unit``.
|
|
72
|
+
|
|
73
|
+
``tag`` is ``date32`` (days since the epoch, no unit), ``ts`` (since the
|
|
74
|
+
epoch, shown in ``zone``), ``duration`` or ``time64`` (since midnight).
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
tag: str
|
|
78
|
+
value: int
|
|
79
|
+
unit: str | None = None
|
|
80
|
+
zone: str | None = None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _digits(tag: str, text: object) -> int:
|
|
84
|
+
if not isinstance(text, str) or not _DIGITS.match(text):
|
|
85
|
+
raise CodecError(f'{tag}: not an integer in canonical decimal form')
|
|
86
|
+
return int(text)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def decode_scalar(scalar: Any) -> Any:
|
|
90
|
+
r"""A contract scalar as a Python value, read exactly.
|
|
91
|
+
|
|
92
|
+
Integers are ``int``, floats ``float``, decimals:class:`~decimal.Decimal`
|
|
93
|
+
built from their digits, text ``str``, binary ``bytes``, and temporal
|
|
94
|
+
values:class:`Temporal`; ``null`` is ``None``.
|
|
95
|
+
"""
|
|
96
|
+
if not isinstance(scalar, dict) or not isinstance(scalar.get('t'), str):
|
|
97
|
+
raise CodecError('a scalar is a tagged object')
|
|
98
|
+
tag = scalar['t']
|
|
99
|
+
value = scalar.get('v')
|
|
100
|
+
if tag == 'null':
|
|
101
|
+
return None
|
|
102
|
+
if tag == 'bool':
|
|
103
|
+
if not isinstance(value, bool):
|
|
104
|
+
raise CodecError('bool: not a boolean')
|
|
105
|
+
return value
|
|
106
|
+
if tag in _INTEGERS:
|
|
107
|
+
number = _digits(tag, value)
|
|
108
|
+
low, high = _INTEGERS[tag]
|
|
109
|
+
if not low <= number <= high:
|
|
110
|
+
raise CodecError(f'{tag}: out of range')
|
|
111
|
+
return number
|
|
112
|
+
if tag in ('f32', 'f64'):
|
|
113
|
+
if not isinstance(value, str) or not _FLOAT.match(value):
|
|
114
|
+
raise CodecError(f'{tag}: not a float')
|
|
115
|
+
return _float32(value) if tag == 'f32' else _float64(value)
|
|
116
|
+
if tag in _DECIMALS:
|
|
117
|
+
precision, scale = scalar.get('p'), scalar.get('s')
|
|
118
|
+
number = _digits(tag, value)
|
|
119
|
+
if (
|
|
120
|
+
not isinstance(precision, int)
|
|
121
|
+
or not isinstance(scale, int)
|
|
122
|
+
or not 1 <= precision <= _DECIMALS[tag]
|
|
123
|
+
or scale > precision
|
|
124
|
+
or len(str(abs(number))) > precision
|
|
125
|
+
):
|
|
126
|
+
raise CodecError(f'{tag}: outside its precision and scale')
|
|
127
|
+
# From its digits, never by scaleb, which rounds to the context.
|
|
128
|
+
with decimal.localcontext(_exact()):
|
|
129
|
+
unscaled = Decimal(number).as_tuple()
|
|
130
|
+
return Decimal((unscaled.sign, unscaled.digits, -scale))
|
|
131
|
+
if tag == 'utf8':
|
|
132
|
+
if not isinstance(value, str):
|
|
133
|
+
raise CodecError('utf8: not text')
|
|
134
|
+
return value
|
|
135
|
+
if tag == 'binary':
|
|
136
|
+
if not isinstance(value, str):
|
|
137
|
+
raise CodecError('binary: not base64 text')
|
|
138
|
+
try:
|
|
139
|
+
return base64.b64decode(value, validate=True)
|
|
140
|
+
except ValueError:
|
|
141
|
+
raise CodecError('binary: not standard base64') from None
|
|
142
|
+
if tag == 'date32':
|
|
143
|
+
number = _digits(tag, value)
|
|
144
|
+
low, high = _INTEGERS['i32']
|
|
145
|
+
if not low <= number <= high:
|
|
146
|
+
raise CodecError('date32: out of range')
|
|
147
|
+
return Temporal('date32', number)
|
|
148
|
+
if tag in _TEMPORAL:
|
|
149
|
+
unit, zone = scalar.get('unit'), scalar.get('zone')
|
|
150
|
+
number = _digits(tag, value)
|
|
151
|
+
low, high = _INTEGERS['i64']
|
|
152
|
+
if unit not in _UNITS or not low <= number <= high:
|
|
153
|
+
raise CodecError(f'{tag}: unit or value out of range')
|
|
154
|
+
if tag == 'ts':
|
|
155
|
+
if zone is not None and (not isinstance(zone, str) or not zone):
|
|
156
|
+
raise CodecError('ts: the zone is empty')
|
|
157
|
+
return Temporal(tag, number, unit, zone)
|
|
158
|
+
return Temporal(tag, number, unit)
|
|
159
|
+
raise CodecError('a scalar of an unknown tag')
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _float64(text: str) -> float:
|
|
163
|
+
r"""``text`` read as a double; finite text that overflows is refused."""
|
|
164
|
+
value = float(text)
|
|
165
|
+
if math.isinf(value) and text not in ('inf', '-inf'):
|
|
166
|
+
raise CodecError('f64: finite text past the largest double')
|
|
167
|
+
return value
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _bits32(value: float) -> int:
|
|
171
|
+
return int.from_bytes(struct.pack('>f', value), 'big')
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _of_bits32(bits: int) -> float:
|
|
175
|
+
return float(struct.unpack('>f', bits.to_bytes(4, 'big'))[0])
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
#: The largest float32.
|
|
179
|
+
_FLOAT32_MAX = (2 - 2**-23) * 2.0**127
|
|
180
|
+
#: Halfway from the largest float32 to 2**128: text whose magnitude reaches
|
|
181
|
+
#: it rounds to infinity (a tie goes to the even neighbour, 2**128).
|
|
182
|
+
_FLOAT32_OVERFLOW = Decimal(2**128 - 2**103)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _exact() -> decimal.Context:
|
|
186
|
+
r"""A context of this module's own for exact comparisons, whatever the
|
|
187
|
+
caller's context traps (``FloatOperation`` included)."""
|
|
188
|
+
return decimal.Context()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _float32(text: str) -> float:
|
|
192
|
+
r"""``text`` rounded to the nearest float32, as a Python float.
|
|
193
|
+
|
|
194
|
+
Rounding the text to a double first and the double to a float32 can
|
|
195
|
+
round twice: when the double lands exactly halfway between two
|
|
196
|
+
float32s, or exactly on the overflow threshold, while the text does
|
|
197
|
+
not, the text itself decides, read exactly as a
|
|
198
|
+
:class:`~decimal.Decimal`. Finite text that rounds past the largest
|
|
199
|
+
float32 is refused, as the core refuses it.
|
|
200
|
+
"""
|
|
201
|
+
wide = float(text)
|
|
202
|
+
if math.isnan(wide):
|
|
203
|
+
return wide
|
|
204
|
+
if math.isinf(wide) and text in ('inf', '-inf'):
|
|
205
|
+
return wide
|
|
206
|
+
try:
|
|
207
|
+
narrow = _of_bits32(_bits32(wide))
|
|
208
|
+
except OverflowError:
|
|
209
|
+
narrow = math.inf
|
|
210
|
+
if math.isinf(narrow):
|
|
211
|
+
with decimal.localcontext(_exact()):
|
|
212
|
+
below = Decimal(text).copy_abs() < _FLOAT32_OVERFLOW
|
|
213
|
+
if not below:
|
|
214
|
+
raise CodecError('f32: finite text past the largest float32')
|
|
215
|
+
return math.copysign(_FLOAT32_MAX, wide)
|
|
216
|
+
if narrow == wide:
|
|
217
|
+
return narrow
|
|
218
|
+
# The float32 on the double's side of ``narrow`` (bits count magnitude
|
|
219
|
+
# within a sign), and the point halfway to it, exact as a double.
|
|
220
|
+
step = 1 if abs(wide) > abs(narrow) else -1
|
|
221
|
+
other = _of_bits32(_bits32(narrow) + step)
|
|
222
|
+
halfway = (narrow + other) / 2
|
|
223
|
+
if wide != halfway:
|
|
224
|
+
return narrow
|
|
225
|
+
with decimal.localcontext(_exact()):
|
|
226
|
+
exact, middle = Decimal(text), Decimal.from_float(halfway)
|
|
227
|
+
if exact == middle:
|
|
228
|
+
return narrow # A true tie: struct rounded it to even.
|
|
229
|
+
nearer_other = (exact > middle) == (other > narrow)
|
|
230
|
+
return other if nearer_other else narrow
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def integer(tag: str, value: int) -> dict[str, Any]:
|
|
234
|
+
r"""An integer scalar of width ``tag`` (``i8`` to ``u64``)."""
|
|
235
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
236
|
+
raise CodecError(f'{tag}: not an integer')
|
|
237
|
+
low, high = _INTEGERS[tag]
|
|
238
|
+
if not low <= value <= high:
|
|
239
|
+
raise CodecError(f'{tag}: out of range')
|
|
240
|
+
return {'t': tag, 'v': str(value)}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def timestamp(value: int, unit: str, zone: str | None) -> dict[str, Any]:
|
|
244
|
+
r"""A ``ts`` scalar: ``value`` in ``unit`` since the epoch, in ``zone``,
|
|
245
|
+
which is none or non-empty text."""
|
|
246
|
+
if unit not in _UNITS or (
|
|
247
|
+
zone is not None and (not isinstance(zone, str) or not zone)
|
|
248
|
+
):
|
|
249
|
+
raise CodecError('ts: unit or zone out of range')
|
|
250
|
+
return {**integer('i64', value), 't': 'ts', 'unit': unit, 'zone': zone}
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def seed(value: Any) -> str | None:
|
|
254
|
+
r"""A seed as the contract writes one: an integer of any size (a NumPy
|
|
255
|
+
integer too) as signed hexadecimal text with no leading zeros, so no
|
|
256
|
+
integer reader's digit limit is met. None for none, or for
|
|
257
|
+
a value of another type, which the call's values carry to the core as
|
|
258
|
+
given, and the core refuses."""
|
|
259
|
+
if isinstance(value, bool) or not isinstance(value, numbers.Integral):
|
|
260
|
+
return None
|
|
261
|
+
value = int(value)
|
|
262
|
+
sign = '-' if value < 0 else ''
|
|
263
|
+
return f'{sign}0x{abs(value):x}'
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _integral(value: Any) -> int:
|
|
267
|
+
r"""A host integer the JSON encoder does not know, such as a NumPy
|
|
268
|
+
integer, which the client's checks take as a whole number, written as
|
|
269
|
+
the integer it is; any other value refused, as the encoder refuses it.
|
|
270
|
+
A bool is not one (NumPy's is not ``numbers.Integral``)."""
|
|
271
|
+
if isinstance(value, numbers.Integral) and not isinstance(value, bool):
|
|
272
|
+
return int(value)
|
|
273
|
+
raise TypeError(
|
|
274
|
+
f'Object of type {type(value).__name__} is not JSON serializable'
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _scalar(value: Any) -> Any:
|
|
279
|
+
r"""A host scalar the JSON encoder does not know, written as the Python
|
|
280
|
+
value it holds, losslessly: an integer (func:`_integral`), and a NumPy boolean or float, its type kept (a float32 is exactly the
|
|
281
|
+
double it widens to), so the core reads the call's option values as the
|
|
282
|
+
caller gave them; a sequence the encoder does not know (a ``range``, and
|
|
283
|
+
a NumPy array) as its items, as the client reads a sequence
|
|
284
|
+
of hop counts and the engine's config classes a sequence of transforms;
|
|
285
|
+
any other value refused, as the encoder refuses it. a NumPy
|
|
286
|
+
float wider than a double (``np.longdouble``) is written as the double
|
|
287
|
+
it holds where that double is exactly its value, or as NaN where it
|
|
288
|
+
holds NaN, as the engine's config classes read it, else refused."""
|
|
289
|
+
import numpy as np
|
|
290
|
+
|
|
291
|
+
if isinstance(value, np.floating):
|
|
292
|
+
item = value.item()
|
|
293
|
+
if isinstance(item, float):
|
|
294
|
+
return item
|
|
295
|
+
if float(value) == value or np.isnan(value):
|
|
296
|
+
return float(value)
|
|
297
|
+
raise TypeError(
|
|
298
|
+
f'Object of type {type(value).__name__} is not JSON serializable'
|
|
299
|
+
)
|
|
300
|
+
if isinstance(value, np.bool_):
|
|
301
|
+
return value.item()
|
|
302
|
+
if isinstance(value, np.ndarray):
|
|
303
|
+
return value.tolist()
|
|
304
|
+
if isinstance(value, Sequence) and not isinstance(
|
|
305
|
+
value, (str, bytes, bytearray)
|
|
306
|
+
):
|
|
307
|
+
return list(value)
|
|
308
|
+
if isinstance(value, (decimal.Decimal, fractions.Fraction)):
|
|
309
|
+
# a finite decimal or fraction as its nearest double,
|
|
310
|
+
# its sign and whether it is zero kept, which is all an option the
|
|
311
|
+
# core reads as a number asks of it: one a double cannot reach is
|
|
312
|
+
# held at the double nearest it of the same sign (the least
|
|
313
|
+
# positive one, or the largest finite), so lag_timesteps=Decimal(2),
|
|
314
|
+
# Decimal('1e-400') or Decimal('1e400') on a static query is taken
|
|
315
|
+
# and ignored, and on a temporal one refused as not whole, as the
|
|
316
|
+
# reference meets each; a NaN or an infinity refused, as the
|
|
317
|
+
# encoder refuses it.
|
|
318
|
+
if not isinstance(value, decimal.Decimal) or value.is_finite():
|
|
319
|
+
sign = 1.0 if value > 0 else -1.0
|
|
320
|
+
try:
|
|
321
|
+
double = float(value)
|
|
322
|
+
except OverflowError:
|
|
323
|
+
double = math.inf
|
|
324
|
+
if math.isinf(double):
|
|
325
|
+
return math.copysign(sys.float_info.max, sign)
|
|
326
|
+
if double == 0 and value != 0:
|
|
327
|
+
return math.copysign(5e-324, sign)
|
|
328
|
+
return double
|
|
329
|
+
raise TypeError(
|
|
330
|
+
f'Object of type {type(value).__name__} is not JSON serializable'
|
|
331
|
+
)
|
|
332
|
+
return _integral(value)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def encode(message: dict[str, Any]) -> bytes:
|
|
336
|
+
r"""A control message the host sends, within the control cap.
|
|
337
|
+
|
|
338
|
+
A message past the cap is refused: whatever grows with the input travels
|
|
339
|
+
as an attachment (func:`attachment`), so a message past it is a defect
|
|
340
|
+
of this host.
|
|
341
|
+
"""
|
|
342
|
+
data = json.dumps(
|
|
343
|
+
message, ensure_ascii=False, allow_nan=False, default=_integral
|
|
344
|
+
).encode()
|
|
345
|
+
if len(data) > CONTROL_CAP:
|
|
346
|
+
raise CodecError(
|
|
347
|
+
f'a control message of {len(data)} bytes is past the control cap'
|
|
348
|
+
)
|
|
349
|
+
return data
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def attachment(
|
|
353
|
+
value: Any, *, named: bool = False, option_values: bool = False
|
|
354
|
+
) -> bytes:
|
|
355
|
+
r"""An input-sized field as a bytes attachment of its JSON. A value JSON
|
|
356
|
+
cannot hold (one of a type the encoder does not know, a number that is
|
|
357
|
+
not finite, one nested past what the encoder writes) is refused as the
|
|
358
|
+
client's transport refuses it, ``INVALID_REQUEST``: the
|
|
359
|
+
call's option values travel here as the caller gave them, and (``named``, for them alone) the refusal names the first option
|
|
360
|
+
whose value JSON cannot hold, in ``details['field']``.
|
|
361
|
+
With ``option_values``, nonfinite numeric tokens cross losslessly for
|
|
362
|
+
Rust's option admission; ordinary attachments remain strict JSON."""
|
|
363
|
+
|
|
364
|
+
def written(item: Any) -> bytes:
|
|
365
|
+
return json.dumps(
|
|
366
|
+
item, ensure_ascii=False, allow_nan=option_values, default=_scalar
|
|
367
|
+
).encode()
|
|
368
|
+
|
|
369
|
+
def writes(item: Any) -> bool:
|
|
370
|
+
try:
|
|
371
|
+
written(item)
|
|
372
|
+
except (TypeError, ValueError, RecursionError):
|
|
373
|
+
return False
|
|
374
|
+
return True
|
|
375
|
+
|
|
376
|
+
try:
|
|
377
|
+
return written(value)
|
|
378
|
+
except (TypeError, ValueError, RecursionError):
|
|
379
|
+
pass
|
|
380
|
+
from sdm_client.errors import StructuredDataError
|
|
381
|
+
|
|
382
|
+
# A mapping's first member JSON cannot hold is named (the call's
|
|
383
|
+
# option values, a NaN or an infinity among them, say which option).
|
|
384
|
+
option = next(
|
|
385
|
+
(
|
|
386
|
+
str(name)
|
|
387
|
+
for name, item in (
|
|
388
|
+
value.items() if named and isinstance(value, dict) else ()
|
|
389
|
+
)
|
|
390
|
+
if not writes(item)
|
|
391
|
+
),
|
|
392
|
+
None,
|
|
393
|
+
)
|
|
394
|
+
raise StructuredDataError(
|
|
395
|
+
'this request carries a value that cannot be sent as JSON'
|
|
396
|
+
if option is None
|
|
397
|
+
else f'{option} carries a value that cannot be sent as JSON (a NaN, '
|
|
398
|
+
f'an infinity, or a type JSON has no form for)',
|
|
399
|
+
code='INVALID_REQUEST',
|
|
400
|
+
details=None if option is None else {'field': option},
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
# --- a caller's value as the contract's Given ----------------------------------
|
|
405
|
+
#
|
|
406
|
+
# The conformance rule of the contract's ``Given`` (``sdm-contract``'s ops.rs):
|
|
407
|
+
# a value the host can write faithfully as the contract's type is written
|
|
408
|
+
# ``{"value":...}``; any other is written ``"unreadable"``, and the core
|
|
409
|
+
# refuses it. The host asks nothing else of the value: what a null, an empty
|
|
410
|
+
# key or a name the table lacks means is the core's. In Python, text is a
|
|
411
|
+
# ``str`` (a subclass written as the plain ``str``); a collection is any
|
|
412
|
+
# other iterable but ``bytes``, a mapping and a set (no order), read once
|
|
413
|
+
# with ``tuple``. Nothing is caught: an exception raised while reading the
|
|
414
|
+
# caller's iterable, ``KeyboardInterrupt`` included, is the caller's, as the
|
|
415
|
+
# reference's ``list(key)`` lets it out.
|
|
416
|
+
|
|
417
|
+
#: A value no contract type holds, as the contract writes it.
|
|
418
|
+
UNREADABLE = 'unreadable'
|
|
419
|
+
#: The longest text:func:`spelled` gives the core; a value whose ``repr``
|
|
420
|
+
#: is longer is given as:data:`UNREADABLE`, so a control message stays
|
|
421
|
+
#: within its cap.
|
|
422
|
+
SPELLED_MOST = 2_000
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def spelled(value: Any, *, include_type: bool = False) -> Any:
|
|
426
|
+
r"""A value no contract type holds, as ``Given`` writes it with the
|
|
427
|
+
text Python shows it as (``repr``), which the core names in its refusal
|
|
428
|
+
as the reference names the value;:data:`UNREADABLE` where its
|
|
429
|
+
``repr`` fails or is past:data:`SPELLED_MOST` characters.
|
|
430
|
+
``include_type`` also names the native type in that bounded diagnostic."""
|
|
431
|
+
try:
|
|
432
|
+
text = repr(value)
|
|
433
|
+
except Exception: # noqa: BLE001 - a caller's value's own repr
|
|
434
|
+
return UNREADABLE
|
|
435
|
+
if include_type and isinstance(text, str):
|
|
436
|
+
text = f'{type(value).__name__}: {text}'
|
|
437
|
+
if not isinstance(text, str) or len(text) > SPELLED_MOST:
|
|
438
|
+
return UNREADABLE
|
|
439
|
+
return {'spelled': str.__str__(text)}
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def given(value: Any) -> Any:
|
|
443
|
+
r"""``value``, of the contract's type, as ``Given`` writes it."""
|
|
444
|
+
return {'value': value}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def given_text(value: Any) -> Any:
|
|
448
|
+
r"""Text as the contract writes it, or any other value
|
|
449
|
+
:func:`spelled`."""
|
|
450
|
+
if isinstance(value, str):
|
|
451
|
+
return given(str.__str__(value))
|
|
452
|
+
return spelled(value)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def given_name_or_none(value: Any) -> Any:
|
|
456
|
+
r"""A name or ``None`` (a time column), as the contract writes it, or
|
|
457
|
+
any other value:func:`spelled`."""
|
|
458
|
+
if value is None:
|
|
459
|
+
return given(None)
|
|
460
|
+
return given_text(value)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def given_key(value: Any) -> tuple[Any, Any]:
|
|
464
|
+
r"""A key as the contract writes it, and the form the reference keeps
|
|
465
|
+
it in (``_as_key_tuple``: a name, or a tuple of the names, read once)."""
|
|
466
|
+
if value is None:
|
|
467
|
+
return given(None), None
|
|
468
|
+
if isinstance(value, str):
|
|
469
|
+
return given([str.__str__(value)]), value
|
|
470
|
+
if isinstance(value, (bytes, Mapping, AbstractSet)) or not isinstance(
|
|
471
|
+
value, Iterable
|
|
472
|
+
):
|
|
473
|
+
return spelled(value), None
|
|
474
|
+
names = tuple(value)
|
|
475
|
+
if not all(isinstance(name, str) for name in names):
|
|
476
|
+
return spelled(value), None
|
|
477
|
+
return given([str.__str__(name) for name in names]), names
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def relation(name: Any) -> dict[str, Any]:
|
|
481
|
+
r"""``name``, a table's name in the source, as the contract's relation
|
|
482
|
+
of one part (contract v26, design choice 12): never split on a dot, so
|
|
483
|
+
``'a.b'`` reads the one table of that name."""
|
|
484
|
+
return {'source': [name]}
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def relation_name(value: Any) -> str:
|
|
488
|
+
r"""The name of a relation of one part the core described: this host
|
|
489
|
+
gives one part, so the core answers one; any other is refused."""
|
|
490
|
+
parts = value.get('source') if isinstance(value, Mapping) else None
|
|
491
|
+
if (
|
|
492
|
+
not isinstance(parts, list)
|
|
493
|
+
or len(parts) != 1
|
|
494
|
+
or not isinstance(parts[0], str)
|
|
495
|
+
):
|
|
496
|
+
raise CodecError('relation: not a relation of one part')
|
|
497
|
+
return parts[0]
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _json(data: bytes) -> dict[str, Any]:
|
|
501
|
+
try:
|
|
502
|
+
message = json.loads(data)
|
|
503
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
504
|
+
position = getattr(error, 'pos', getattr(error, 'start', 0))
|
|
505
|
+
raise CodecError(
|
|
506
|
+
f'not a control message (at byte {position})'
|
|
507
|
+
) from None
|
|
508
|
+
if not isinstance(message, dict) or not isinstance(
|
|
509
|
+
message.get('message'), str
|
|
510
|
+
):
|
|
511
|
+
raise CodecError('not a control message')
|
|
512
|
+
return message
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def read(control: bytes, attachments: dict[int, Any]) -> dict[str, Any]:
|
|
516
|
+
r"""A control message the core wrote, whole.
|
|
517
|
+
|
|
518
|
+
An ``attached`` message is replaced by the message its bytes attachment
|
|
519
|
+
carries, which is never itself ``attached``.
|
|
520
|
+
"""
|
|
521
|
+
message = _json(control)
|
|
522
|
+
if message['message'] != 'attached':
|
|
523
|
+
return message
|
|
524
|
+
carried = attachments.get(message.get('attachment')) # type: ignore[arg-type]
|
|
525
|
+
if not isinstance(carried, bytes):
|
|
526
|
+
raise CodecError(
|
|
527
|
+
'an attached message names a bytes attachment that is not with it'
|
|
528
|
+
)
|
|
529
|
+
whole = _json(carried)
|
|
530
|
+
if whole['message'] == 'attached':
|
|
531
|
+
raise CodecError('an attached message carries another')
|
|
532
|
+
return whole
|