dag-ml-data-provider 0.2.16__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.
@@ -0,0 +1,30 @@
1
+ """Stdlib-only ctypes provider shim for the dag-ml-data C ABI.
2
+
3
+ This package is a thin, modality-neutral wrapper over the Rust C ABI provider
4
+ vtable (`dag-ml-data-capi`). It implements no NIRS, ML, or scheduling logic; it
5
+ only hands JSON payloads and host buffers to Rust and decodes the results.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ._library import (
11
+ NativeLibraryError,
12
+ NativeLibraryIntegrityError,
13
+ NativeLibraryNotFoundError,
14
+ find_capi_library,
15
+ load_library,
16
+ )
17
+ from ._provider import InMemoryProvider, PackageProvider
18
+
19
+ __all__ = [
20
+ "InMemoryProvider",
21
+ "NativeLibraryError",
22
+ "NativeLibraryIntegrityError",
23
+ "NativeLibraryNotFoundError",
24
+ "PackageProvider",
25
+ "__version__",
26
+ "find_capi_library",
27
+ "load_library",
28
+ ]
29
+
30
+ __version__ = "0.2.16"
@@ -0,0 +1,226 @@
1
+ """ctypes layout of the dag-ml-data C ABI provider surface.
2
+
3
+ This module mirrors `crates/dag-ml-data-capi/include/dag_ml_data.h`. It owns the
4
+ `ctypes.Structure` / `CFUNCTYPE` definitions and the `configure_library` routine
5
+ that pins argtypes/restypes on a loaded cdylib. It contains no behavior beyond
6
+ the ABI shape.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ctypes
12
+
13
+
14
+ class DagMlDataString(ctypes.Structure):
15
+ _fields_ = [("ptr", ctypes.c_void_p), ("len", ctypes.c_size_t)]
16
+
17
+
18
+ class DagMlDataBytesView(ctypes.Structure):
19
+ _fields_ = [("ptr", ctypes.POINTER(ctypes.c_uint8)), ("len", ctypes.c_size_t)]
20
+
21
+
22
+ class DagMlDataStringArray(ctypes.Structure):
23
+ _fields_ = [("ptr", ctypes.POINTER(DagMlDataString)), ("len", ctypes.c_size_t)]
24
+
25
+
26
+ class DagMlDataUSizeArray(ctypes.Structure):
27
+ _fields_ = [("ptr", ctypes.POINTER(ctypes.c_size_t)), ("len", ctypes.c_size_t)]
28
+
29
+
30
+ class DagMlDataF64Array(ctypes.Structure):
31
+ _fields_ = [("ptr", ctypes.POINTER(ctypes.c_double)), ("len", ctypes.c_size_t)]
32
+
33
+
34
+ class DagMlDataU8Array(ctypes.Structure):
35
+ _fields_ = [("ptr", ctypes.POINTER(ctypes.c_uint8)), ("len", ctypes.c_size_t)]
36
+
37
+
38
+ class DagMlDataTensorF64(ctypes.Structure):
39
+ _fields_ = [
40
+ ("abi_version", ctypes.c_uint32),
41
+ ("block_id", DagMlDataString),
42
+ ("representation_id", DagMlDataString),
43
+ ("batch_container", DagMlDataString),
44
+ ("observation_ids", DagMlDataStringArray),
45
+ ("sample_ids", DagMlDataStringArray),
46
+ ("shape", DagMlDataUSizeArray),
47
+ ("values", DagMlDataF64Array),
48
+ ("presence_mask", DagMlDataU8Array),
49
+ ("validity_mask", DagMlDataU8Array),
50
+ ("feature_names", DagMlDataStringArray),
51
+ ]
52
+
53
+
54
+ class ArrowArray(ctypes.Structure):
55
+ pass
56
+
57
+
58
+ class ArrowSchema(ctypes.Structure):
59
+ pass
60
+
61
+
62
+ ArrowArray._fields_ = [
63
+ ("length", ctypes.c_int64),
64
+ ("null_count", ctypes.c_int64),
65
+ ("offset", ctypes.c_int64),
66
+ ("n_buffers", ctypes.c_int64),
67
+ ("n_children", ctypes.c_int64),
68
+ ("buffers", ctypes.POINTER(ctypes.c_void_p)),
69
+ ("children", ctypes.POINTER(ctypes.POINTER(ArrowArray))),
70
+ ("dictionary", ctypes.POINTER(ArrowArray)),
71
+ ("release", ctypes.c_void_p),
72
+ ("private_data", ctypes.c_void_p),
73
+ ]
74
+
75
+ ArrowSchema._fields_ = [
76
+ ("format", ctypes.c_char_p),
77
+ ("name", ctypes.c_char_p),
78
+ ("metadata", ctypes.c_char_p),
79
+ ("flags", ctypes.c_int64),
80
+ ("n_children", ctypes.c_int64),
81
+ ("children", ctypes.POINTER(ctypes.POINTER(ArrowSchema))),
82
+ ("dictionary", ctypes.POINTER(ArrowSchema)),
83
+ ("release", ctypes.c_void_p),
84
+ ("private_data", ctypes.c_void_p),
85
+ ]
86
+
87
+
88
+ MaterializeFn = ctypes.CFUNCTYPE(
89
+ ctypes.c_int,
90
+ ctypes.c_void_p,
91
+ ctypes.c_uint64,
92
+ DagMlDataBytesView,
93
+ ctypes.POINTER(ctypes.c_uint64),
94
+ )
95
+ MakeViewFn = ctypes.CFUNCTYPE(
96
+ ctypes.c_int,
97
+ ctypes.c_void_p,
98
+ ctypes.c_uint64,
99
+ DagMlDataBytesView,
100
+ ctypes.POINTER(ctypes.c_uint64),
101
+ )
102
+ ViewIdentityFn = ctypes.CFUNCTYPE(
103
+ ctypes.c_int,
104
+ ctypes.c_void_p,
105
+ ctypes.c_uint64,
106
+ ctypes.POINTER(ctypes.POINTER(ArrowArray)),
107
+ ctypes.POINTER(ctypes.POINTER(ArrowSchema)),
108
+ )
109
+ TargetArrowFn = ctypes.CFUNCTYPE(
110
+ ctypes.c_int,
111
+ ctypes.c_void_p,
112
+ ctypes.c_uint64,
113
+ DagMlDataBytesView,
114
+ ctypes.POINTER(ctypes.POINTER(ArrowArray)),
115
+ ctypes.POINTER(ctypes.POINTER(ArrowSchema)),
116
+ )
117
+ FeatureArrowFn = ctypes.CFUNCTYPE(
118
+ ctypes.c_int,
119
+ ctypes.c_void_p,
120
+ ctypes.c_uint64,
121
+ DagMlDataBytesView,
122
+ ctypes.POINTER(ctypes.POINTER(ArrowArray)),
123
+ ctypes.POINTER(ctypes.POINTER(ArrowSchema)),
124
+ )
125
+ ReleaseFn = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint64)
126
+ DestroyFn = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
127
+
128
+
129
+ class DagMlDataVTable(ctypes.Structure):
130
+ _fields_ = [
131
+ ("abi_version", ctypes.c_uint32),
132
+ ("user_data", ctypes.c_void_p),
133
+ ("materialize", MaterializeFn),
134
+ ("make_view", MakeViewFn),
135
+ ("view_identity", ViewIdentityFn),
136
+ ("target_arrow", TargetArrowFn),
137
+ ("feature_arrow", FeatureArrowFn),
138
+ ("release", ReleaseFn),
139
+ ("destroy", DestroyFn),
140
+ ]
141
+
142
+
143
+ def configure_library(lib: ctypes.CDLL) -> ctypes.CDLL:
144
+ """Pins argtypes/restypes for the C ABI symbols this package calls."""
145
+ lib.dagmldata_inmemory_provider_new_json.argtypes = [
146
+ ctypes.POINTER(ctypes.c_uint8),
147
+ ctypes.c_size_t,
148
+ ctypes.POINTER(ctypes.c_uint8),
149
+ ctypes.c_size_t,
150
+ ctypes.POINTER(DagMlDataVTable),
151
+ ctypes.POINTER(DagMlDataString),
152
+ ]
153
+ lib.dagmldata_inmemory_provider_new_json.restype = ctypes.c_int
154
+ lib.dagmldata_inmemory_provider_new_with_features_json.argtypes = [
155
+ ctypes.POINTER(ctypes.c_uint8),
156
+ ctypes.c_size_t,
157
+ ctypes.POINTER(ctypes.c_uint8),
158
+ ctypes.c_size_t,
159
+ ctypes.POINTER(ctypes.c_uint8),
160
+ ctypes.c_size_t,
161
+ ctypes.POINTER(DagMlDataVTable),
162
+ ctypes.POINTER(DagMlDataString),
163
+ ]
164
+ lib.dagmldata_inmemory_provider_new_with_features_json.restype = ctypes.c_int
165
+ lib.dagmldata_inmemory_provider_new_with_f64_features_json.argtypes = [
166
+ ctypes.POINTER(ctypes.c_uint8),
167
+ ctypes.c_size_t,
168
+ ctypes.POINTER(ctypes.c_uint8),
169
+ ctypes.c_size_t,
170
+ ctypes.POINTER(ctypes.c_uint8),
171
+ ctypes.c_size_t,
172
+ ctypes.POINTER(DagMlDataVTable),
173
+ ctypes.POINTER(DagMlDataString),
174
+ ]
175
+ lib.dagmldata_inmemory_provider_new_with_f64_features_json.restype = ctypes.c_int
176
+ lib.dagmldata_inmemory_provider_new_from_file.argtypes = [
177
+ ctypes.POINTER(ctypes.c_uint8),
178
+ ctypes.c_size_t,
179
+ ctypes.POINTER(ctypes.c_uint8),
180
+ ctypes.c_size_t,
181
+ ctypes.POINTER(ctypes.c_uint8),
182
+ ctypes.c_size_t,
183
+ ctypes.POINTER(DagMlDataVTable),
184
+ ctypes.POINTER(DagMlDataString),
185
+ ]
186
+ lib.dagmldata_inmemory_provider_new_from_file.restype = ctypes.c_int
187
+ lib.dagmldata_inmemory_provider_feature_buffer_manifest_json.argtypes = [
188
+ ctypes.POINTER(DagMlDataVTable),
189
+ ctypes.POINTER(DagMlDataString),
190
+ ctypes.POINTER(DagMlDataString),
191
+ ]
192
+ lib.dagmldata_inmemory_provider_feature_buffer_manifest_json.restype = ctypes.c_int
193
+ lib.dagmldata_inmemory_provider_data_feature_buffer_manifest_json.argtypes = [
194
+ ctypes.POINTER(DagMlDataVTable),
195
+ ctypes.c_uint64,
196
+ ctypes.POINTER(DagMlDataString),
197
+ ctypes.POINTER(DagMlDataString),
198
+ ]
199
+ lib.dagmldata_inmemory_provider_data_feature_buffer_manifest_json.restype = ctypes.c_int
200
+ lib.dagmldata_inmemory_provider_feature_collation_json.argtypes = [
201
+ ctypes.POINTER(DagMlDataVTable),
202
+ ctypes.c_uint64,
203
+ DagMlDataBytesView,
204
+ ctypes.POINTER(DagMlDataString),
205
+ ctypes.POINTER(DagMlDataString),
206
+ ]
207
+ lib.dagmldata_inmemory_provider_feature_collation_json.restype = ctypes.c_int
208
+ lib.dagmldata_inmemory_provider_feature_collation_tensor_f64_json.argtypes = [
209
+ ctypes.POINTER(DagMlDataVTable),
210
+ ctypes.c_uint64,
211
+ DagMlDataBytesView,
212
+ ctypes.POINTER(DagMlDataTensorF64),
213
+ ctypes.POINTER(DagMlDataString),
214
+ ]
215
+ lib.dagmldata_inmemory_provider_feature_collation_tensor_f64_json.restype = ctypes.c_int
216
+ lib.dagmldata_inmemory_provider_destroy.argtypes = [ctypes.POINTER(DagMlDataVTable)]
217
+ lib.dagmldata_inmemory_provider_destroy.restype = None
218
+ lib.dagmldata_string_free.argtypes = [DagMlDataString]
219
+ lib.dagmldata_string_free.restype = None
220
+ lib.dagmldata_tensor_f64_free.argtypes = [DagMlDataTensorF64]
221
+ lib.dagmldata_tensor_f64_free.restype = None
222
+ lib.dagmldata_arrow_array_free.argtypes = [ctypes.POINTER(ArrowArray)]
223
+ lib.dagmldata_arrow_array_free.restype = None
224
+ lib.dagmldata_arrow_schema_free.argtypes = [ctypes.POINTER(ArrowSchema)]
225
+ lib.dagmldata_arrow_schema_free.restype = None
226
+ return lib
@@ -0,0 +1,222 @@
1
+ """Discovery and loading of the dag-ml-data C ABI cdylib.
2
+
3
+ The platform wheel bundles and integrity-checks `dag_ml_data_capi`. Explicit
4
+ paths and the existing source-checkout discovery order remain supported.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from ._abi import configure_library
18
+
19
+ _MANIFEST_NAME = "native-library.json"
20
+ _MANIFEST_SCHEMA_VERSION = 1
21
+
22
+
23
+ class NativeLibraryError(RuntimeError):
24
+ """Base error for failures that happen before the native ABI is used."""
25
+
26
+
27
+ class NativeLibraryNotFoundError(NativeLibraryError):
28
+ """Raised when the platform library is absent from the installed package."""
29
+
30
+
31
+ class NativeLibraryIntegrityError(NativeLibraryError):
32
+ """Raised when the bundled library or its provenance manifest is invalid."""
33
+
34
+
35
+ def _library_filename() -> str:
36
+ if sys.platform == "darwin":
37
+ return "libdag_ml_data_capi.dylib"
38
+ if sys.platform == "win32":
39
+ return "dag_ml_data_capi.dll"
40
+ return "libdag_ml_data_capi.so"
41
+
42
+
43
+ def _package_root() -> Path:
44
+ return Path(__file__).resolve().parent
45
+
46
+
47
+ def _read_manifest(path: Path) -> dict[str, Any]:
48
+ if not path.is_file():
49
+ raise NativeLibraryNotFoundError(
50
+ f"bundled native-library manifest is missing from the installed package: {path}"
51
+ )
52
+ try:
53
+ payload = json.loads(path.read_text(encoding="utf-8"))
54
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
55
+ raise NativeLibraryIntegrityError(
56
+ f"bundled native-library manifest is unreadable or invalid JSON: {path}"
57
+ ) from exc
58
+ if not isinstance(payload, dict):
59
+ raise NativeLibraryIntegrityError(
60
+ "bundled native-library manifest must be a JSON object"
61
+ )
62
+ required = {
63
+ "schema_version",
64
+ "package",
65
+ "package_version",
66
+ "cargo_package",
67
+ "library",
68
+ "sha256",
69
+ "size_bytes",
70
+ "rust_target",
71
+ "rustc",
72
+ "source_commit",
73
+ "source_dirty",
74
+ }
75
+ if set(payload) != required:
76
+ missing = sorted(required - set(payload))
77
+ unknown = sorted(set(payload) - required)
78
+ raise NativeLibraryIntegrityError(
79
+ "bundled native-library manifest fields are not the closed v1 contract "
80
+ f"(missing={missing}, unknown={unknown})"
81
+ )
82
+ if payload["schema_version"] != _MANIFEST_SCHEMA_VERSION:
83
+ raise NativeLibraryIntegrityError(
84
+ "unsupported bundled native-library manifest schema_version "
85
+ f"{payload['schema_version']!r}"
86
+ )
87
+ if (
88
+ payload["package"] != "dag-ml-data-provider"
89
+ or payload["cargo_package"] != "dag-ml-data-capi"
90
+ ):
91
+ raise NativeLibraryIntegrityError(
92
+ "bundled native-library manifest identifies the wrong package"
93
+ )
94
+ if payload["library"] != _library_filename():
95
+ raise NativeLibraryIntegrityError(
96
+ f"bundled native-library manifest names {payload['library']!r}, "
97
+ f"expected {_library_filename()!r} for {sys.platform}"
98
+ )
99
+ digest = payload["sha256"]
100
+ if (
101
+ not isinstance(digest, str)
102
+ or len(digest) != 64
103
+ or any(c not in "0123456789abcdef" for c in digest)
104
+ ):
105
+ raise NativeLibraryIntegrityError(
106
+ "bundled native-library manifest sha256 is not lowercase hexadecimal"
107
+ )
108
+ if not isinstance(payload["size_bytes"], int) or payload["size_bytes"] <= 0:
109
+ raise NativeLibraryIntegrityError(
110
+ "bundled native-library manifest size_bytes must be positive"
111
+ )
112
+ for field in ("package_version", "rust_target", "rustc", "source_commit"):
113
+ if not isinstance(payload[field], str) or not payload[field].strip():
114
+ raise NativeLibraryIntegrityError(
115
+ f"bundled native-library manifest {field} must be a non-empty string"
116
+ )
117
+ if not isinstance(payload["source_dirty"], bool):
118
+ raise NativeLibraryIntegrityError(
119
+ "bundled native-library manifest source_dirty must be a boolean"
120
+ )
121
+ return payload
122
+
123
+
124
+ def _candidate_paths() -> list[Path]:
125
+ filename = _library_filename()
126
+ candidates: list[Path] = []
127
+
128
+ env_path = os.environ.get("DAG_ML_DATA_CAPI_LIB")
129
+ if env_path:
130
+ candidates.append(Path(env_path))
131
+
132
+ # The platform wheel contains a native library and a provenance manifest.
133
+ candidates.append(_package_root() / ".libs" / filename)
134
+
135
+ # Source-checkout convenience: locate the cdylib under the Cargo target dir.
136
+ # parents[5] of .../crates/dag-ml-data-capi/bindings/python/dag_ml_data_provider/_library.py
137
+ # is the workspace root; when pip-installed this is not a checkout and the
138
+ # fallback is skipped (guarded by the workspace `Cargo.toml`).
139
+ resolved = Path(__file__).resolve()
140
+ workspace_root = resolved.parents[5] if len(resolved.parents) >= 6 else None
141
+
142
+ target_dirs: list[Path] = []
143
+ cargo_target = os.environ.get("CARGO_TARGET_DIR")
144
+ if cargo_target:
145
+ cargo_target_path = Path(cargo_target)
146
+ if not cargo_target_path.is_absolute() and workspace_root is not None:
147
+ # Cargo resolves a relative CARGO_TARGET_DIR against the workspace root,
148
+ # not the current working directory.
149
+ cargo_target_path = workspace_root / cargo_target_path
150
+ target_dirs.append(cargo_target_path)
151
+ if workspace_root is not None and (workspace_root / "Cargo.toml").is_file():
152
+ target_dirs.append(workspace_root / "target")
153
+
154
+ for target_dir in target_dirs:
155
+ candidates.append(target_dir / "debug" / filename)
156
+ candidates.append(target_dir / "release" / filename)
157
+
158
+ return candidates
159
+
160
+
161
+ def _verified_bundled_library(package_root: Path) -> Path:
162
+ """Validate the wheel's native library against its package-local manifest."""
163
+ manifest = _read_manifest(package_root / _MANIFEST_NAME)
164
+ library = package_root / ".libs" / _library_filename()
165
+ if not library.is_file():
166
+ raise NativeLibraryNotFoundError(
167
+ f"bundled native library is missing from the installed package: {library}"
168
+ )
169
+ try:
170
+ size = library.stat().st_size
171
+ digest = hashlib.sha256(library.read_bytes()).hexdigest()
172
+ except OSError as exc:
173
+ raise NativeLibraryIntegrityError(
174
+ f"bundled native library cannot be read for integrity verification: {library}"
175
+ ) from exc
176
+ if size != manifest["size_bytes"] or digest != manifest["sha256"]:
177
+ raise NativeLibraryIntegrityError(
178
+ "bundled native library failed integrity verification "
179
+ f"(expected size={manifest['size_bytes']} sha256={manifest['sha256']}, "
180
+ f"actual size={size} sha256={digest})"
181
+ )
182
+ return library
183
+
184
+
185
+ def find_capi_library() -> Path:
186
+ """Returns the first existing candidate path for the C ABI cdylib.
187
+
188
+ Raises ``FileNotFoundError`` with the searched locations if none is found.
189
+ """
190
+ candidates = _candidate_paths()
191
+ package_root = _package_root()
192
+ bundled = package_root / ".libs" / _library_filename()
193
+ for candidate in candidates:
194
+ if candidate == bundled and ((package_root / _MANIFEST_NAME).exists() or bundled.exists()):
195
+ return _verified_bundled_library(package_root)
196
+ if candidate.is_file():
197
+ return candidate
198
+ searched = "\n ".join(str(candidate) for candidate in candidates)
199
+ raise FileNotFoundError(
200
+ "could not locate the dag-ml-data C ABI cdylib "
201
+ f"({_library_filename()}). Set DAG_ML_DATA_CAPI_LIB, pass "
202
+ "library_path=..., or build it with "
203
+ "`cargo build -p dag-ml-data-capi --lib`. Searched:\n " + searched
204
+ )
205
+
206
+
207
+ def load_library(library_path: str | Path | None = None) -> ctypes.CDLL:
208
+ """Loads and configures the C ABI cdylib.
209
+
210
+ When ``library_path`` is ``None`` the library is discovered via
211
+ :func:`find_capi_library`.
212
+ """
213
+ path = Path(library_path) if library_path is not None else find_capi_library()
214
+ try:
215
+ return configure_library(ctypes.CDLL(str(path)))
216
+ except OSError as exc:
217
+ bundled = _package_root() / ".libs" / _library_filename()
218
+ if library_path is None and path == bundled:
219
+ raise NativeLibraryIntegrityError(
220
+ f"bundled native library passed hashing but could not be loaded: {path}: {exc}"
221
+ ) from exc
222
+ raise