trlog 0.1.0__py3-none-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.
- trlog/__init__.py +60 -0
- trlog/__main__.py +7 -0
- trlog/__version__.py +17 -0
- trlog/_aux.py +50 -0
- trlog/_bytesplit.py +243 -0
- trlog/_codec.py +179 -0
- trlog/_codec_bridge.py +319 -0
- trlog/_deps.py +169 -0
- trlog/_derived.py +315 -0
- trlog/_exceptions.py +33 -0
- trlog/_ext.py +102 -0
- trlog/_hierarchy.py +372 -0
- trlog/_index.py +237 -0
- trlog/_libpath.py +80 -0
- trlog/_metadata.py +178 -0
- trlog/_native.py +372 -0
- trlog/_reader.py +840 -0
- trlog/_string_table.py +115 -0
- trlog/_txn_data.py +893 -0
- trlog/_type_registry.py +457 -0
- trlog/_types.py +491 -0
- trlog/_vc_data.py +831 -0
- trlog/_writer.py +1146 -0
- trlog/cli.py +1841 -0
- trlog/codec.py +629 -0
- trlog/ext/__init__.py +5 -0
- trlog/ext/callreturn.py +458 -0
- trlog/query/__init__.py +33 -0
- trlog/query/_analysis.py +657 -0
- trlog/query/_cengine.py +702 -0
- trlog/query/_engine.py +1798 -0
- trlog/query/_export.py +300 -0
- trlog/query/_expr.py +1111 -0
- trlog/query/_format.py +323 -0
- trlog/query/_rows.py +162 -0
- trlog/query/_values.py +276 -0
- trlog/share/include/trl/trl.h +211 -0
- trlog/share/include/trl/trl_api.h +35 -0
- trlog/share/include/trl/trl_codec.h +188 -0
- trlog/share/include/trl/trl_qscan.h +174 -0
- trlog/share/include/trl/trl_query.h +114 -0
- trlog/share/include/trl/trl_rec.h +110 -0
- trlog/share/include/trlog_vpi.h +34 -0
- trlog/share/sv/trl_cursor.svh +144 -0
- trlog/share/sv/trl_db.svh +111 -0
- trlog/share/sv/trl_final.sv +13 -0
- trlog/share/sv/trl_macros.svh +31 -0
- trlog/share/sv/trl_pkg.sv +87 -0
- trlog/share/sv/trl_reader.svh +93 -0
- trlog/share/sv/trl_rstream.svh +22 -0
- trlog/share/sv/trl_schema.svh +40 -0
- trlog/share/sv/trl_stream.svh +175 -0
- trlog/share/sv/trl_sv_dpi.svh +96 -0
- trlog/share/sv/trl_txn.svh +98 -0
- trlog/share/sv/trl_type.svh +107 -0
- trlog/share/sv/trl_uvm_pkg.sv +332 -0
- trlog/trl.dll +0 -0
- trlog/trl.lib +0 -0
- trlog/trl_sv.dll +0 -0
- trlog/trl_sv.lib +0 -0
- trlog/trlog_vpi.dll +0 -0
- trlog/trlog_vpi.lib +0 -0
- trlog/weave/__init__.py +8 -0
- trlog/weave/_record.py +340 -0
- trlog-0.1.0.dist-info/METADATA +217 -0
- trlog-0.1.0.dist-info/RECORD +70 -0
- trlog-0.1.0.dist-info/WHEEL +5 -0
- trlog-0.1.0.dist-info/entry_points.txt +5 -0
- trlog-0.1.0.dist-info/licenses/LICENSE +201 -0
- trlog-0.1.0.dist-info/top_level.txt +1 -0
trlog/_codec_bridge.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""ctypes bridge: drive a Python value-change codec from the C writer.
|
|
2
|
+
|
|
3
|
+
The C codec ABI (``c/include/trl/trl_codec.h``) uses only plain C functions
|
|
4
|
+
and function-pointer vtables, so ctypes can implement a vtable in Python.
|
|
5
|
+
:func:`register_native` builds a ``trl_vc_codec_t`` whose slots are ctypes
|
|
6
|
+
``CFUNCTYPE`` callbacks into a :class:`~trlog.codec.VcCodec` instance and
|
|
7
|
+
registers it with ``trl_register_vc_codec``. After
|
|
8
|
+
``trl_writer_set_vc_codec(w, codec_id)``, the C writer calls the Python
|
|
9
|
+
codec's ``encode_block``, ``finalize`` and ``close`` through those callbacks.
|
|
10
|
+
Inside a callback, the codec reaches the C container through a
|
|
11
|
+
:class:`Store` whose methods call the SPI functions ``trl_store_intern``,
|
|
12
|
+
``trl_store_vc_change_count`` / ``trl_store_vc_change_at`` and
|
|
13
|
+
``trl_blkout_append``.
|
|
14
|
+
|
|
15
|
+
Limitations of the current bridge:
|
|
16
|
+
|
|
17
|
+
* Write side only. The bridged ``decode_block``, ``open_reader`` and
|
|
18
|
+
``input_streams`` slots do nothing and return 0.
|
|
19
|
+
* One stream: per-stream state lives on the :class:`NativeBridge`, not in the
|
|
20
|
+
C ``self`` pointer.
|
|
21
|
+
* Only ``U64``-kind changes are passed through; other value kinds read as 0.
|
|
22
|
+
* The codec's ``encode_block`` result is appended to the C block buffer as
|
|
23
|
+
returned, and the C writer writes it as the block. As in the Python writer,
|
|
24
|
+
the codec returns the complete block: header and payload (see
|
|
25
|
+
:doc:`/guide/writing-a-codec`).
|
|
26
|
+
|
|
27
|
+
The module imports without ``libtrl.so``. :data:`AVAILABLE` is then False and
|
|
28
|
+
:func:`register_native` raises ``RuntimeError``.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import ctypes
|
|
34
|
+
from typing import Any, List, Optional
|
|
35
|
+
|
|
36
|
+
from ._native import _LIB
|
|
37
|
+
from .codec import Store, VcCodec
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
AVAILABLE = _LIB is not None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ---------------------------------------------------------------------------
|
|
44
|
+
# ctypes mirror of the codec ABI (c/include/trl/trl_codec.h)
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
# Vtable slot signatures. `trl_store`/`trl_blkout`/`self` are opaque pointers.
|
|
48
|
+
_OPEN_FN = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p,
|
|
49
|
+
ctypes.c_uint32, ctypes.c_void_p, ctypes.c_size_t)
|
|
50
|
+
_CLOSE_FN = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
|
|
51
|
+
_FINALIZE_FN = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p)
|
|
52
|
+
_ENCODE_FN = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p,
|
|
53
|
+
ctypes.c_void_p)
|
|
54
|
+
_DECODE_FN = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p,
|
|
55
|
+
ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint8,
|
|
56
|
+
ctypes.c_void_p, ctypes.c_void_p)
|
|
57
|
+
_INPUTS_FN = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p,
|
|
58
|
+
ctypes.c_void_p, ctypes.c_void_p)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _VcCodecVTable(ctypes.Structure):
|
|
62
|
+
"""Layout of ``trl_vc_codec_t``. Field order + types must match the header
|
|
63
|
+
exactly; ctypes uses native alignment, matching the C struct ABI."""
|
|
64
|
+
|
|
65
|
+
_fields_ = [
|
|
66
|
+
("codec_id", ctypes.c_char_p),
|
|
67
|
+
("version", ctypes.c_uint16),
|
|
68
|
+
("caps", ctypes.c_uint32),
|
|
69
|
+
("open_writer", _OPEN_FN),
|
|
70
|
+
("open_reader", _OPEN_FN),
|
|
71
|
+
("close", _CLOSE_FN),
|
|
72
|
+
("finalize", _FINALIZE_FN),
|
|
73
|
+
("encode_block", _ENCODE_FN),
|
|
74
|
+
("decode_block", _DECODE_FN),
|
|
75
|
+
("input_streams", _INPUTS_FN),
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _bind_spi() -> None:
|
|
80
|
+
"""Declare arg/return types for the SPI symbols the bridge uses."""
|
|
81
|
+
_LIB.trl_register_vc_codec.argtypes = [ctypes.POINTER(_VcCodecVTable)]
|
|
82
|
+
_LIB.trl_register_vc_codec.restype = ctypes.c_int
|
|
83
|
+
_LIB.trl_writer_set_vc_codec.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
|
84
|
+
_LIB.trl_writer_set_vc_codec.restype = ctypes.c_int
|
|
85
|
+
_LIB.trl_store_intern.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
|
86
|
+
_LIB.trl_store_intern.restype = ctypes.c_uint32
|
|
87
|
+
_LIB.trl_blkout_append.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
|
|
88
|
+
ctypes.c_size_t]
|
|
89
|
+
_LIB.trl_blkout_append.restype = ctypes.c_int
|
|
90
|
+
_LIB.trl_store_vc_change_count.argtypes = [ctypes.c_void_p]
|
|
91
|
+
_LIB.trl_store_vc_change_count.restype = ctypes.c_size_t
|
|
92
|
+
_LIB.trl_store_vc_start_time.argtypes = [ctypes.c_void_p]
|
|
93
|
+
_LIB.trl_store_vc_start_time.restype = ctypes.c_uint64
|
|
94
|
+
_LIB.trl_store_vc_end_time.argtypes = [ctypes.c_void_p]
|
|
95
|
+
_LIB.trl_store_vc_end_time.restype = ctypes.c_uint64
|
|
96
|
+
_LIB.trl_store_vc_change_at.argtypes = [
|
|
97
|
+
ctypes.c_void_p, ctypes.c_size_t,
|
|
98
|
+
ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(ctypes.c_uint64),
|
|
99
|
+
ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(ctypes.c_uint64)]
|
|
100
|
+
_LIB.trl_store_vc_change_at.restype = ctypes.c_int
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if AVAILABLE:
|
|
104
|
+
_bind_spi()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ---------------------------------------------------------------------------
|
|
108
|
+
# Store facade over a live C trl_store pointer (valid only inside a callback)
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
class _BridgeStore(Store):
|
|
112
|
+
"""A :class:`Store` backed by a C ``trl_store`` pointer.
|
|
113
|
+
|
|
114
|
+
Created for each callback around the pointer the C writer passes in. The
|
|
115
|
+
pointer is valid only during that callback, so do not keep the object.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def __init__(self, cstore: int) -> None:
|
|
119
|
+
super().__init__(writer=None, reader=None)
|
|
120
|
+
self._cstore = cstore
|
|
121
|
+
|
|
122
|
+
def intern(self, s: str) -> int:
|
|
123
|
+
"""Intern ``s`` in the C writer's string table (``trl_store_intern``)."""
|
|
124
|
+
return int(_LIB.trl_store_intern(self._cstore, s.encode("utf-8")))
|
|
125
|
+
|
|
126
|
+
# -- change-accessor: the block's accumulated changes, var-major ----------
|
|
127
|
+
|
|
128
|
+
def vc_start_time(self) -> int:
|
|
129
|
+
"""Start time of the block being encoded."""
|
|
130
|
+
return int(_LIB.trl_store_vc_start_time(self._cstore))
|
|
131
|
+
|
|
132
|
+
def vc_end_time(self) -> int:
|
|
133
|
+
"""End time of the block being encoded."""
|
|
134
|
+
return int(_LIB.trl_store_vc_end_time(self._cstore))
|
|
135
|
+
|
|
136
|
+
def vc_changes(self) -> List[tuple]:
|
|
137
|
+
"""Return the block's changes as ``[(var_id, time, value), ...]``.
|
|
138
|
+
|
|
139
|
+
Changes are grouped by variable. ``value`` is the U64 value; changes
|
|
140
|
+
of other kinds read as 0.
|
|
141
|
+
"""
|
|
142
|
+
n = int(_LIB.trl_store_vc_change_count(self._cstore))
|
|
143
|
+
out: List[tuple] = []
|
|
144
|
+
var_id = ctypes.c_uint32()
|
|
145
|
+
t = ctypes.c_uint64()
|
|
146
|
+
kind = ctypes.c_uint32()
|
|
147
|
+
u64 = ctypes.c_uint64()
|
|
148
|
+
for i in range(n):
|
|
149
|
+
rc = _LIB.trl_store_vc_change_at(
|
|
150
|
+
self._cstore, i, ctypes.byref(var_id), ctypes.byref(t),
|
|
151
|
+
ctypes.byref(kind), ctypes.byref(u64))
|
|
152
|
+
if rc != 0:
|
|
153
|
+
break
|
|
154
|
+
out.append((var_id.value, t.value, u64.value))
|
|
155
|
+
return out
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# ---------------------------------------------------------------------------
|
|
159
|
+
# The bridge: wrap a VcCodec instance as a C vtable and register it
|
|
160
|
+
# ---------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
# Module-level keep-alive: ctypes does NOT keep CFUNCTYPE thunks or the vtable
|
|
163
|
+
# Structure alive once register_native returns, but the C registry stores the
|
|
164
|
+
# pointer for the trace's lifetime. Dropping them would crash the writer.
|
|
165
|
+
_KEEPALIVE: List[Any] = []
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class NativeBridge:
|
|
169
|
+
"""The C vtable and callbacks for one bridged :class:`VcCodec`.
|
|
170
|
+
|
|
171
|
+
Holds the codec's per-stream writer state and the first exception raised
|
|
172
|
+
inside a callback. A callback that raises returns an error code to C; call
|
|
173
|
+
:meth:`raise_pending` afterwards to re-raise the exception in Python.
|
|
174
|
+
|
|
175
|
+
Attributes:
|
|
176
|
+
codec: The bridged codec instance.
|
|
177
|
+
pending_exc: First exception raised in a callback, or ``None``.
|
|
178
|
+
last_payload: Bytes returned by the last ``encode_block`` call.
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
def __init__(self, codec: VcCodec) -> None:
|
|
182
|
+
self.codec = codec
|
|
183
|
+
self._state: Any = None
|
|
184
|
+
self.pending_exc: Optional[BaseException] = None
|
|
185
|
+
self.last_payload: Optional[bytes] = None
|
|
186
|
+
self._vtable = self._build_vtable(codec)
|
|
187
|
+
|
|
188
|
+
# -- exception trampoline -------------------------------------------------
|
|
189
|
+
|
|
190
|
+
def _record(self, exc: BaseException) -> None:
|
|
191
|
+
# Keep the first exception; later callbacks won't run meaningful work.
|
|
192
|
+
if self.pending_exc is None:
|
|
193
|
+
self.pending_exc = exc
|
|
194
|
+
|
|
195
|
+
def raise_pending(self) -> None:
|
|
196
|
+
"""Re-raise and clear the exception captured in a callback, if any.
|
|
197
|
+
|
|
198
|
+
Call this after a C function such as ``trl_vc_flush`` returns an error.
|
|
199
|
+
"""
|
|
200
|
+
exc = self.pending_exc
|
|
201
|
+
if exc is not None:
|
|
202
|
+
self.pending_exc = None
|
|
203
|
+
raise exc
|
|
204
|
+
|
|
205
|
+
# -- vtable construction --------------------------------------------------
|
|
206
|
+
|
|
207
|
+
def _build_vtable(self, codec: VcCodec) -> _VcCodecVTable:
|
|
208
|
+
codec_id_bytes = codec.codec_id.encode("utf-8")
|
|
209
|
+
|
|
210
|
+
def open_writer(cstore, stream_id, params, param_len):
|
|
211
|
+
try:
|
|
212
|
+
self._state = codec.open_writer(_BridgeStore(cstore),
|
|
213
|
+
int(stream_id), b"")
|
|
214
|
+
except BaseException as e: # noqa: BLE001 - trampoline to C
|
|
215
|
+
self._record(e)
|
|
216
|
+
return 0 # per-stream state lives on the Python side (single stream)
|
|
217
|
+
|
|
218
|
+
def open_reader(cstore, stream_id, params, param_len):
|
|
219
|
+
return 0
|
|
220
|
+
|
|
221
|
+
def close(self_ptr):
|
|
222
|
+
try:
|
|
223
|
+
codec.close(self._state)
|
|
224
|
+
except BaseException as e: # noqa: BLE001
|
|
225
|
+
self._record(e)
|
|
226
|
+
|
|
227
|
+
def finalize(self_ptr, cstore):
|
|
228
|
+
try:
|
|
229
|
+
return int(codec.finalize(self._state, _BridgeStore(cstore)))
|
|
230
|
+
except BaseException as e: # noqa: BLE001
|
|
231
|
+
self._record(e)
|
|
232
|
+
return -1
|
|
233
|
+
|
|
234
|
+
def encode_block(self_ptr, cstore, out):
|
|
235
|
+
try:
|
|
236
|
+
store = _BridgeStore(cstore)
|
|
237
|
+
# Rebuild the codec's per-block state from the C-accumulated
|
|
238
|
+
# changes, then run the *same* encode_block as the pure-Python
|
|
239
|
+
# container — that shared path is what guarantees payload parity.
|
|
240
|
+
blk = codec.new_block(store, self._state, store.vc_start_time())
|
|
241
|
+
for var_id, time, value in store.vc_changes():
|
|
242
|
+
blk.add_change(var_id, time, value)
|
|
243
|
+
payload, _start, _end = codec.encode_block(self._state, store)
|
|
244
|
+
payload = bytes(payload)
|
|
245
|
+
self.last_payload = payload
|
|
246
|
+
if payload:
|
|
247
|
+
rc = _LIB.trl_blkout_append(out, payload, len(payload))
|
|
248
|
+
if rc != 0:
|
|
249
|
+
return -1
|
|
250
|
+
return 0
|
|
251
|
+
except BaseException as e: # noqa: BLE001
|
|
252
|
+
self._record(e)
|
|
253
|
+
return -1
|
|
254
|
+
|
|
255
|
+
def decode_block(self_ptr, cstore, payload, length, flags, emit, user):
|
|
256
|
+
return 0 # decode-side bridge is future work (this slice is write)
|
|
257
|
+
|
|
258
|
+
def input_streams(self_ptr, cstore, out_ids, n):
|
|
259
|
+
return 0
|
|
260
|
+
|
|
261
|
+
vt = _VcCodecVTable()
|
|
262
|
+
vt.codec_id = codec_id_bytes
|
|
263
|
+
vt.version = int(getattr(codec, "version", 1))
|
|
264
|
+
vt.caps = int(getattr(codec, "caps", 0))
|
|
265
|
+
vt.open_writer = _OPEN_FN(open_writer)
|
|
266
|
+
vt.open_reader = _OPEN_FN(open_reader)
|
|
267
|
+
vt.close = _CLOSE_FN(close)
|
|
268
|
+
vt.finalize = _FINALIZE_FN(finalize)
|
|
269
|
+
vt.encode_block = _ENCODE_FN(encode_block)
|
|
270
|
+
vt.decode_block = _DECODE_FN(decode_block)
|
|
271
|
+
vt.input_streams = _INPUTS_FN(input_streams)
|
|
272
|
+
|
|
273
|
+
# Keep the thunks, the codec-id bytes, and the struct itself alive.
|
|
274
|
+
_KEEPALIVE.extend([
|
|
275
|
+
vt, codec_id_bytes,
|
|
276
|
+
vt.open_writer, vt.open_reader, vt.close, vt.finalize,
|
|
277
|
+
vt.encode_block, vt.decode_block, vt.input_streams,
|
|
278
|
+
])
|
|
279
|
+
return vt
|
|
280
|
+
|
|
281
|
+
def register(self) -> None:
|
|
282
|
+
"""Register the vtable with ``trl_register_vc_codec``.
|
|
283
|
+
|
|
284
|
+
Raises:
|
|
285
|
+
RuntimeError: If registration fails.
|
|
286
|
+
"""
|
|
287
|
+
rc = _LIB.trl_register_vc_codec(ctypes.byref(self._vtable))
|
|
288
|
+
if rc != 0:
|
|
289
|
+
raise RuntimeError(
|
|
290
|
+
f"trl_register_vc_codec failed for {self.codec.codec_id!r} (rc={rc})")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def register_native(codec: VcCodec) -> NativeBridge:
|
|
294
|
+
"""Register a Python value-change codec with the C codec registry.
|
|
295
|
+
|
|
296
|
+
The codec's ``new_block`` must return an accumulator with
|
|
297
|
+
``add_change(var_id, time, value)``; the bridge fills it from the C block
|
|
298
|
+
before calling ``encode_block``.
|
|
299
|
+
|
|
300
|
+
Args:
|
|
301
|
+
codec: The codec instance, for example from
|
|
302
|
+
:func:`trlog.codec.lookup_vc_codec`.
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
The :class:`NativeBridge`. Keep it while the C writer can call the
|
|
306
|
+
codec, and use :meth:`NativeBridge.raise_pending` to surface errors.
|
|
307
|
+
|
|
308
|
+
Raises:
|
|
309
|
+
RuntimeError: If ``libtrl.so`` is not loaded or registration fails.
|
|
310
|
+
"""
|
|
311
|
+
if not AVAILABLE:
|
|
312
|
+
raise RuntimeError(
|
|
313
|
+
"the ctypes codec bridge requires libtrl.so, which is not loaded")
|
|
314
|
+
bridge = NativeBridge(codec)
|
|
315
|
+
bridge.register()
|
|
316
|
+
return bridge
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
__all__ = ["AVAILABLE", "NativeBridge", "register_native"]
|
trlog/_deps.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Stream dependency resolution (design §4.4, impl-plan §2.5/§2.c).
|
|
2
|
+
|
|
3
|
+
A small DAG over stream-type ids: ``stream S depends on input streams I`` means
|
|
4
|
+
S's codec must have I materialized before it can decode (derived/consumer
|
|
5
|
+
codecs). The same graph drives three things:
|
|
6
|
+
|
|
7
|
+
* **cycle detection** — mandatory at write time (reject), defensive at read;
|
|
8
|
+
* **read order** — :meth:`topo_order` yields dependencies *before* dependents,
|
|
9
|
+
so a derived stream materializes after its inputs;
|
|
10
|
+
* **finalize order** — :meth:`finalize_order` is the *reverse*: a depended-on
|
|
11
|
+
(shared) stream is finalized only after every stream that feeds it has closed
|
|
12
|
+
(design §4.7), so a shared metadata stream is provably complete at close.
|
|
13
|
+
|
|
14
|
+
The reader pairs the graph with a lazy, memoized :class:`Materializer` so a
|
|
15
|
+
derived stream is computed only when iterated and reused for the query's life.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from typing import Callable, Dict, List, Optional
|
|
21
|
+
|
|
22
|
+
from ._exceptions import ZstError
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DependencyError(ZstError):
|
|
26
|
+
"""A dependency cycle or a reference to an undeclared stream."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DependencyGraph:
|
|
30
|
+
"""A directed graph of "X depends on Y" edges between integer IDs.
|
|
31
|
+
|
|
32
|
+
Used for stream-type dependencies and derived-signal inputs. Nodes are
|
|
33
|
+
created implicitly by :meth:`add`.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self) -> None:
|
|
37
|
+
self._deps: Dict[int, List[int]] = {}
|
|
38
|
+
|
|
39
|
+
def add(self, stream_id: int, inputs) -> None:
|
|
40
|
+
"""Set the inputs of ``stream_id``, replacing any earlier ones."""
|
|
41
|
+
self._deps[stream_id] = list(inputs)
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_catalog(cls, catalog: Dict[int, List[int]]) -> "DependencyGraph":
|
|
45
|
+
"""Build a graph from a ``{id: [input_ids]}`` dictionary."""
|
|
46
|
+
g = cls()
|
|
47
|
+
for sid, inputs in catalog.items():
|
|
48
|
+
g.add(sid, inputs)
|
|
49
|
+
return g
|
|
50
|
+
|
|
51
|
+
def inputs(self, stream_id: int) -> List[int]:
|
|
52
|
+
"""Return the direct inputs of ``stream_id`` (empty if none)."""
|
|
53
|
+
return list(self._deps.get(stream_id, []))
|
|
54
|
+
|
|
55
|
+
def nodes(self) -> List[int]:
|
|
56
|
+
"""Return all IDs that appear in the graph, sorted."""
|
|
57
|
+
nodes = set(self._deps)
|
|
58
|
+
for ins in self._deps.values():
|
|
59
|
+
nodes.update(ins)
|
|
60
|
+
return sorted(nodes)
|
|
61
|
+
|
|
62
|
+
def find_cycle(self) -> Optional[List[int]]:
|
|
63
|
+
"""Return a node sequence forming a cycle, or ``None`` if acyclic."""
|
|
64
|
+
WHITE, GRAY, BLACK = 0, 1, 2
|
|
65
|
+
color: Dict[int, int] = {}
|
|
66
|
+
path: List[int] = []
|
|
67
|
+
|
|
68
|
+
def visit(n: int) -> Optional[List[int]]:
|
|
69
|
+
color[n] = GRAY
|
|
70
|
+
path.append(n)
|
|
71
|
+
for m in self._deps.get(n, []):
|
|
72
|
+
if color.get(m, WHITE) == GRAY:
|
|
73
|
+
return path[path.index(m):] + [m]
|
|
74
|
+
if color.get(m, WHITE) == WHITE:
|
|
75
|
+
c = visit(m)
|
|
76
|
+
if c:
|
|
77
|
+
return c
|
|
78
|
+
path.pop()
|
|
79
|
+
color[n] = BLACK
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
for n in self.nodes():
|
|
83
|
+
if color.get(n, WHITE) == WHITE:
|
|
84
|
+
c = visit(n)
|
|
85
|
+
if c:
|
|
86
|
+
return c
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
def validate_acyclic(self) -> None:
|
|
90
|
+
"""Raise :class:`DependencyError` if the graph has a cycle."""
|
|
91
|
+
cycle = self.find_cycle()
|
|
92
|
+
if cycle:
|
|
93
|
+
arrow = " -> ".join(str(x) for x in cycle)
|
|
94
|
+
raise DependencyError(f"stream dependency cycle: {arrow}")
|
|
95
|
+
|
|
96
|
+
def topo_order(self) -> List[int]:
|
|
97
|
+
"""Return all nodes with each node's inputs before the node.
|
|
98
|
+
|
|
99
|
+
Raises:
|
|
100
|
+
DependencyError: The graph has a cycle.
|
|
101
|
+
"""
|
|
102
|
+
self.validate_acyclic()
|
|
103
|
+
order: List[int] = []
|
|
104
|
+
seen = set()
|
|
105
|
+
|
|
106
|
+
def visit(n: int) -> None:
|
|
107
|
+
if n in seen:
|
|
108
|
+
return
|
|
109
|
+
seen.add(n)
|
|
110
|
+
for m in self._deps.get(n, []):
|
|
111
|
+
visit(m)
|
|
112
|
+
order.append(n)
|
|
113
|
+
|
|
114
|
+
for n in self.nodes():
|
|
115
|
+
visit(n)
|
|
116
|
+
return order
|
|
117
|
+
|
|
118
|
+
def finalize_order(self) -> List[int]:
|
|
119
|
+
"""Return the reverse of :meth:`topo_order`: dependents first.
|
|
120
|
+
|
|
121
|
+
Raises:
|
|
122
|
+
DependencyError: The graph has a cycle.
|
|
123
|
+
"""
|
|
124
|
+
return list(reversed(self.topo_order()))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Materializer:
|
|
128
|
+
"""Computes nodes of a :class:`DependencyGraph` on demand, inputs first.
|
|
129
|
+
|
|
130
|
+
Usually obtained from :meth:`~trlog.TrlReader.materializer`.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
graph: The dependency graph.
|
|
134
|
+
compute: Called as ``compute(stream_id, inputs)``, where ``inputs``
|
|
135
|
+
maps each input ID to its computed result. Called at most once
|
|
136
|
+
per ID; results are cached for the materializer's lifetime.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(self, graph: DependencyGraph,
|
|
140
|
+
compute: Callable[[int, Dict[int, object]], object]) -> None:
|
|
141
|
+
self._graph = graph
|
|
142
|
+
self._compute = compute
|
|
143
|
+
self._cache: Dict[int, object] = {}
|
|
144
|
+
self._in_progress: set = set()
|
|
145
|
+
|
|
146
|
+
def materialize(self, stream_id: int) -> object:
|
|
147
|
+
"""Return the result for ``stream_id``, computing it and its inputs if
|
|
148
|
+
they are not cached yet.
|
|
149
|
+
|
|
150
|
+
Raises:
|
|
151
|
+
DependencyError: A cycle was reached.
|
|
152
|
+
"""
|
|
153
|
+
if stream_id in self._cache:
|
|
154
|
+
return self._cache[stream_id]
|
|
155
|
+
if stream_id in self._in_progress:
|
|
156
|
+
raise DependencyError(
|
|
157
|
+
f"dependency cycle hit at read time through stream {stream_id}")
|
|
158
|
+
self._in_progress.add(stream_id)
|
|
159
|
+
try:
|
|
160
|
+
inputs = {i: self.materialize(i) for i in self._graph.inputs(stream_id)}
|
|
161
|
+
result = self._compute(stream_id, inputs)
|
|
162
|
+
self._cache[stream_id] = result
|
|
163
|
+
return result
|
|
164
|
+
finally:
|
|
165
|
+
self._in_progress.discard(stream_id)
|
|
166
|
+
|
|
167
|
+
def is_materialized(self, stream_id: int) -> bool:
|
|
168
|
+
"""Return whether a result for ``stream_id`` is cached."""
|
|
169
|
+
return stream_id in self._cache
|