hypercache-io 0.9.0__tar.gz

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,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: hypercache-io
3
+ Version: 0.9.0
4
+ Summary: HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads
5
+ Author: Looe Labs
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/looelabs/hypercache
8
+ Project-URL: Repository, https://github.com/looelabs/hypercache
9
+ Project-URL: Issues, https://github.com/looelabs/hypercache/issues
10
+ Keywords: ai,pytorch,safetensors,vllm,nvme,gpudirect,cache,s3,fsspec
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Rust
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: System :: Filesystems
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ Requires-Dist: fsspec>=2023.1.0
28
+ Requires-Dist: numpy>=1.22.0
29
+ Provides-Extra: gpu
30
+ Requires-Dist: kvikio-cu12>=24.0.0; extra == "gpu"
31
+ Requires-Dist: cupy-cuda12x>=12.0.0; extra == "gpu"
32
+ Requires-Dist: torch>=2.0.0; extra == "gpu"
33
+ Requires-Dist: numpy>=1.22.0; extra == "gpu"
34
+ Provides-Extra: dev
35
+ Requires-Dist: torch>=2.0.0; extra == "dev"
36
+ Requires-Dist: safetensors>=0.4.0; extra == "dev"
37
+ Requires-Dist: boto3>=1.28.0; extra == "dev"
38
+ Requires-Dist: requests>=2.28.0; extra == "dev"
39
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
40
+ Requires-Dist: numpy>=1.22.0; extra == "dev"
41
+
42
+ # HyperCache Python Client & Data Plane (`client-py`)
43
+
44
+ The `hypercache` Python package integrates transparently into AI training and inference pipelines (PyTorch, Hugging Face, Safetensors) to provide **zero-copy Direct Block DMA / GPUDirect Storage (GDS)** checkpoint loading.
45
+
46
+ ---
47
+
48
+ ## Key Features
49
+
50
+ - **Transparent `hypercache://` Protocol**: Seamless `fsspec` filesystem implementation.
51
+ - **Dual Direct / Buffered Handles**: Uses `O_DIRECT` with sector/page-aligned DMA buffers for maximum hardware read throughput (up to **~7 GB/s** per PCIe Gen 4 NVMe and **~14 GB/s** per PCIe Gen 5 NVMe), with automatic transparent fallback for arbitrary unaligned byte slices.
52
+ - **Sub-Millisecond Metadata**: Resolves physical drive offsets from the local HyperCache control plane daemon in **< 1 ms** over Unix Domain Sockets.
53
+ - **Zero-Copy GPU Direct**: Direct DMA transfers bypassing host CPU and Linux page cache.
54
+
55
+ ---
56
+
57
+ ## Installation
58
+
59
+ ```bash
60
+ # Install from PyPI (imports as `import hypercache`)
61
+ pip install hypercache-io
62
+
63
+ # Or install in editable mode from the repository
64
+ cd client-py
65
+ pip install -e .
66
+
67
+ # Optional GPU Direct Storage acceleration dependencies
68
+ pip install "hypercache-io[gpu]" --extra-index-url https://pypi.nvidia.com
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Usage Examples
74
+
75
+ ### 1. PyTorch & Safetensors Loading
76
+ ```python
77
+ import torch
78
+ import safetensors.torch
79
+ from hypercache.fsspec_fs import register_hypercache_fsspec
80
+
81
+ # Automatically registers hypercache:// protocol
82
+ register_hypercache_fsspec()
83
+
84
+ # Load tensors directly from striped NVMe storage into VRAM/Host memory
85
+ with open("hypercache://models/llama-3/weights.safetensors", "rb") as f:
86
+ tensors = safetensors.torch.load(f.read())
87
+ ```
88
+
89
+ ### 2. Direct Python Client API
90
+ ```python
91
+ from hypercache.client import HyperCacheClient
92
+ from hypercache.datapath import get_data_reader
93
+
94
+ # Connect to local Control Plane Daemon (auto-resolves /run/hypercache/hypercache.sock)
95
+ client = HyperCacheClient()
96
+
97
+ # Check daemon health & discovered drives
98
+ devices = client.get_devices()
99
+ print(f"Discovered {len(devices)} active striped devices.")
100
+
101
+ # Locate checkpoint
102
+ layout = client.locate("hypercache://models/llama-3/weights.safetensors", auto_ingest=True)
103
+ if layout.is_hit:
104
+ reader = get_data_reader()
105
+ data = reader.read_chunks(layout.chunk_layout, layout.object_size)
106
+ print(f"Read {len(data)/(1024*1024):.2f} MiB at hardware line rate!")
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Running Unit Tests
112
+
113
+ ```bash
114
+ pytest tests/
115
+ ```
@@ -0,0 +1,74 @@
1
+ # HyperCache Python Client & Data Plane (`client-py`)
2
+
3
+ The `hypercache` Python package integrates transparently into AI training and inference pipelines (PyTorch, Hugging Face, Safetensors) to provide **zero-copy Direct Block DMA / GPUDirect Storage (GDS)** checkpoint loading.
4
+
5
+ ---
6
+
7
+ ## Key Features
8
+
9
+ - **Transparent `hypercache://` Protocol**: Seamless `fsspec` filesystem implementation.
10
+ - **Dual Direct / Buffered Handles**: Uses `O_DIRECT` with sector/page-aligned DMA buffers for maximum hardware read throughput (up to **~7 GB/s** per PCIe Gen 4 NVMe and **~14 GB/s** per PCIe Gen 5 NVMe), with automatic transparent fallback for arbitrary unaligned byte slices.
11
+ - **Sub-Millisecond Metadata**: Resolves physical drive offsets from the local HyperCache control plane daemon in **< 1 ms** over Unix Domain Sockets.
12
+ - **Zero-Copy GPU Direct**: Direct DMA transfers bypassing host CPU and Linux page cache.
13
+
14
+ ---
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ # Install from PyPI (imports as `import hypercache`)
20
+ pip install hypercache-io
21
+
22
+ # Or install in editable mode from the repository
23
+ cd client-py
24
+ pip install -e .
25
+
26
+ # Optional GPU Direct Storage acceleration dependencies
27
+ pip install "hypercache-io[gpu]" --extra-index-url https://pypi.nvidia.com
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Usage Examples
33
+
34
+ ### 1. PyTorch & Safetensors Loading
35
+ ```python
36
+ import torch
37
+ import safetensors.torch
38
+ from hypercache.fsspec_fs import register_hypercache_fsspec
39
+
40
+ # Automatically registers hypercache:// protocol
41
+ register_hypercache_fsspec()
42
+
43
+ # Load tensors directly from striped NVMe storage into VRAM/Host memory
44
+ with open("hypercache://models/llama-3/weights.safetensors", "rb") as f:
45
+ tensors = safetensors.torch.load(f.read())
46
+ ```
47
+
48
+ ### 2. Direct Python Client API
49
+ ```python
50
+ from hypercache.client import HyperCacheClient
51
+ from hypercache.datapath import get_data_reader
52
+
53
+ # Connect to local Control Plane Daemon (auto-resolves /run/hypercache/hypercache.sock)
54
+ client = HyperCacheClient()
55
+
56
+ # Check daemon health & discovered drives
57
+ devices = client.get_devices()
58
+ print(f"Discovered {len(devices)} active striped devices.")
59
+
60
+ # Locate checkpoint
61
+ layout = client.locate("hypercache://models/llama-3/weights.safetensors", auto_ingest=True)
62
+ if layout.is_hit:
63
+ reader = get_data_reader()
64
+ data = reader.read_chunks(layout.chunk_layout, layout.object_size)
65
+ print(f"Read {len(data)/(1024*1024):.2f} MiB at hardware line rate!")
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Running Unit Tests
71
+
72
+ ```bash
73
+ pytest tests/
74
+ ```
@@ -0,0 +1,61 @@
1
+ """
2
+ HyperCache: Host-Based Zero-Copy GPUDirect Storage Cache.
3
+ """
4
+
5
+ from typing import Optional
6
+
7
+ from hypercache.client import DiscoveredDeviceInfo, HyperCacheClient, LocateResult
8
+ from hypercache.datapath import (
9
+ ChunkLocation,
10
+ DataReader,
11
+ DirectBlockReader,
12
+ GDSReader,
13
+ get_data_reader,
14
+ )
15
+ from hypercache.fsspec_fs import HyperCacheFile, HyperCacheFileSystem
16
+ from hypercache.integrations import (
17
+ HyperCacheDCPStorageReader,
18
+ HyperCacheDCPStorageWriter,
19
+ HyperCachevLLMWeightLoader,
20
+ load_safetensors_state_dict,
21
+ save_safetensors_state_dict,
22
+ )
23
+ from hypercache.kv_store import HyperCacheKVStore
24
+ from hypercache.pipeline import HyperCachePipelinedLoader, pipeline_load
25
+
26
+
27
+ def preload(
28
+ uri: str,
29
+ socket_path: Optional[str] = None,
30
+ tier: Optional[str] = None,
31
+ pinned: bool = False,
32
+ ) -> LocateResult:
33
+ """
34
+ Convenience function to proactively pre-warm a checkpoint into the local NVMe cache.
35
+ """
36
+ client = HyperCacheClient(socket_path=socket_path)
37
+ return client.preload(uri, tier=tier, pinned=pinned)
38
+
39
+
40
+ __all__ = [
41
+ "HyperCacheClient",
42
+ "DiscoveredDeviceInfo",
43
+ "HyperCacheFileSystem",
44
+ "HyperCacheFile",
45
+ "ChunkLocation",
46
+ "DataReader",
47
+ "DirectBlockReader",
48
+ "GDSReader",
49
+ "get_data_reader",
50
+ "preload",
51
+ "HyperCachePipelinedLoader",
52
+ "pipeline_load",
53
+ "HyperCacheKVStore",
54
+ "load_safetensors_state_dict",
55
+ "save_safetensors_state_dict",
56
+ "HyperCachevLLMWeightLoader",
57
+ "HyperCacheDCPStorageWriter",
58
+ "HyperCacheDCPStorageReader",
59
+ ]
60
+
61
+ __version__ = "0.9.0"
@@ -0,0 +1,456 @@
1
+ """
2
+ HyperCache UDS IPC Client.
3
+
4
+ Facilitates sub-millisecond metadata handshakes with the Rust Control Plane.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import socket
12
+ from dataclasses import dataclass
13
+ from typing import List, Optional
14
+
15
+ from hypercache.datapath import ChunkLocation
16
+
17
+ import os
18
+
19
+ PRIMARY_SOCKET_PATH = "/run/hypercache/hypercache.sock"
20
+ FALLBACK_SOCKET_PATH = "/tmp/hypercache/hypercache.sock"
21
+ LEGACY_SOCKET_PATH = "/tmp/hypercache.sock"
22
+
23
+
24
+ def get_default_socket_path() -> str:
25
+ """Discovers and returns the active HyperCache Unix Domain Socket path."""
26
+ if os.path.exists(PRIMARY_SOCKET_PATH):
27
+ return PRIMARY_SOCKET_PATH
28
+ if os.path.exists(FALLBACK_SOCKET_PATH):
29
+ return FALLBACK_SOCKET_PATH
30
+ if os.path.exists(LEGACY_SOCKET_PATH):
31
+ return LEGACY_SOCKET_PATH
32
+ if os.path.exists("/run"):
33
+ return PRIMARY_SOCKET_PATH
34
+ return FALLBACK_SOCKET_PATH
35
+
36
+
37
+ DEFAULT_SOCKET_PATH = PRIMARY_SOCKET_PATH
38
+
39
+
40
+ @dataclass
41
+ class LocateResult:
42
+ status: str
43
+ object_size: int
44
+ chunk_size: int
45
+ chunk_layout: List[ChunkLocation]
46
+ error_message: Optional[str] = None
47
+
48
+ @property
49
+ def is_hit(self) -> bool:
50
+ return self.status == "HIT"
51
+
52
+
53
+ @dataclass
54
+ class StageWriteResult:
55
+ status: str
56
+ object_size: int
57
+ chunk_size: int
58
+ chunk_layout: List[ChunkLocation]
59
+ sync_status: str
60
+ error_message: Optional[str] = None
61
+
62
+ @property
63
+ def is_staged(self) -> bool:
64
+ return self.status in ("WRITESTAGED", "WRITE_STAGED")
65
+
66
+
67
+ @dataclass
68
+ class DiscoveredDeviceInfo:
69
+ path: str
70
+ is_nvme: bool
71
+ is_virtual: bool
72
+ is_partition: bool
73
+ is_rotational: bool
74
+ size_bytes: int
75
+ model: Optional[str] = None
76
+ existing_fs: Optional[str] = None
77
+ numa_node: Optional[int] = None
78
+
79
+ @classmethod
80
+ def from_dict(cls, data: dict) -> DiscoveredDeviceInfo:
81
+ return cls(
82
+ path=str(data.get("path", "")),
83
+ is_nvme=bool(data.get("is_nvme", False)),
84
+ is_virtual=bool(data.get("is_virtual", False)),
85
+ is_partition=bool(data.get("is_partition", False)),
86
+ is_rotational=bool(data.get("is_rotational", False)),
87
+ size_bytes=int(data.get("size_bytes", 0)),
88
+ model=data.get("model"),
89
+ existing_fs=data.get("existing_fs"),
90
+ numa_node=data.get("numa_node"),
91
+ )
92
+
93
+
94
+ class HyperCacheClient:
95
+ """Client for querying the HyperCache Control Plane daemon via Unix Domain Socket."""
96
+
97
+ def __init__(self, socket_path: Optional[str] = None, timeout: float = 120.0):
98
+ self.socket_path = socket_path or get_default_socket_path()
99
+ self.timeout = timeout
100
+ self._sock: Optional[socket.socket] = None
101
+
102
+ def _connect(self) -> socket.socket:
103
+ if self._sock is not None:
104
+ return self._sock
105
+
106
+ try:
107
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
108
+ sock.settimeout(self.timeout)
109
+ sock.connect(self.socket_path)
110
+ self._sock = sock
111
+ return sock
112
+ except Exception as e:
113
+ logger.error(f"Failed to connect to HyperCache daemon at {self.socket_path}: {e}")
114
+ raise ConnectionError(
115
+ f"HyperCache daemon unreachable at {self.socket_path}. Is the daemon running?"
116
+ ) from e
117
+
118
+ def _send_request(self, payload: dict) -> dict:
119
+ sock = self._connect()
120
+ data = (json.dumps(payload) + "\n").encode("utf-8")
121
+ try:
122
+ sock.sendall(data)
123
+
124
+ # Read newline-terminated response
125
+ resp_buf = bytearray()
126
+ while True:
127
+ chunk = sock.recv(4096)
128
+ if not chunk:
129
+ break
130
+ resp_buf.extend(chunk)
131
+ if b"\n" in chunk:
132
+ break
133
+
134
+ if not resp_buf:
135
+ raise ConnectionResetError("Connection closed by server without response")
136
+
137
+ line = bytes(resp_buf).split(b"\n", 1)[0].decode("utf-8")
138
+ return json.loads(line)
139
+ except (socket.error, ConnectionError):
140
+ self.close()
141
+ raise
142
+
143
+ def ping(self) -> bool:
144
+ """Checks if the control plane is alive."""
145
+ try:
146
+ resp = self._send_request({"action": "ping"})
147
+ return resp.get("status") == "PONG"
148
+ except Exception:
149
+ return False
150
+
151
+ def get_devices(self) -> List[DiscoveredDeviceInfo]:
152
+ """Queries the control plane for dynamically auto-discovered SSDs/NVMe devices."""
153
+ resp = self._send_request({"action": "get_devices"})
154
+ raw_devices = resp.get("devices", [])
155
+ return [DiscoveredDeviceInfo.from_dict(d) for d in raw_devices]
156
+
157
+ def locate(
158
+ self,
159
+ uri: str,
160
+ auto_ingest: bool = True,
161
+ tier: Optional[str] = None,
162
+ pinned: bool = False,
163
+ ) -> LocateResult:
164
+ """
165
+ Sends a locate request to the control plane for a given URI.
166
+ Returns exact physical chunk routing layout.
167
+ """
168
+ req = {
169
+ "action": "locate",
170
+ "uri": uri,
171
+ "auto_ingest": auto_ingest,
172
+ "pinned": pinned,
173
+ }
174
+ if tier is not None:
175
+ req["tier"] = tier.lower()
176
+
177
+ resp = self._send_request(req)
178
+ status = resp.get("status", "ERROR")
179
+
180
+ if status == "HIT":
181
+ chunk_layout = [
182
+ ChunkLocation.from_dict(c) for c in resp.get("chunk_layout", [])
183
+ ]
184
+ return LocateResult(
185
+ status=status,
186
+ object_size=resp.get("object_size", 0),
187
+ chunk_size=resp.get("chunk_size", 4194304),
188
+ chunk_layout=chunk_layout,
189
+ )
190
+ elif status == "MISS":
191
+ return LocateResult(
192
+ status=status,
193
+ object_size=0,
194
+ chunk_size=0,
195
+ chunk_layout=[],
196
+ )
197
+ else:
198
+ err = resp.get("error_message", "Unknown error from control plane")
199
+ return LocateResult(
200
+ status=status,
201
+ object_size=0,
202
+ chunk_size=0,
203
+ chunk_layout=[],
204
+ error_message=err,
205
+ )
206
+
207
+ def ingest(
208
+ self,
209
+ uri: str,
210
+ tier: Optional[str] = None,
211
+ pinned: bool = False,
212
+ ) -> LocateResult:
213
+ """Forces immediate ingestion and striping of an object into the SSD or RAM pool."""
214
+ req = {
215
+ "action": "ingest",
216
+ "uri": uri,
217
+ "pinned": pinned,
218
+ }
219
+ if tier is not None:
220
+ req["tier"] = tier.lower()
221
+ resp = self._send_request(req)
222
+ status = resp.get("status", "ERROR")
223
+ if status in ("HIT", "INGESTED"):
224
+ chunk_layout = [
225
+ ChunkLocation.from_dict(c) for c in resp.get("chunk_layout", [])
226
+ ]
227
+ return LocateResult(
228
+ status="HIT",
229
+ object_size=resp.get("object_size", 0),
230
+ chunk_size=resp.get("chunk_size", 4194304),
231
+ chunk_layout=chunk_layout,
232
+ )
233
+ else:
234
+ err = resp.get("error_message", "Ingestion failed")
235
+ return LocateResult(
236
+ status="ERROR",
237
+ object_size=0,
238
+ chunk_size=0,
239
+ chunk_layout=[],
240
+ error_message=err,
241
+ )
242
+
243
+ def preload(self, uri: str, tier: Optional[str] = None, pinned: bool = False) -> LocateResult:
244
+ """
245
+ Proactively pre-loads / pre-warms a checkpoint from S3 or NFS into the local NVMe cache.
246
+ """
247
+ return self.ingest(uri, tier=tier, pinned=pinned)
248
+
249
+ def pin(self, uri: str, pinned: bool = True) -> bool:
250
+ """Pins or unpins an existing cached object so W-TinyLFU never evicts it."""
251
+ resp = self._send_request({
252
+ "action": "pin",
253
+ "uri": uri,
254
+ "pinned": pinned,
255
+ })
256
+ return resp.get("status") == "PONG"
257
+
258
+ def evict(self, uri: str) -> bool:
259
+ """Evicts a specific URI from the cache and reclaims its 4 MiB blocks."""
260
+ resp = self._send_request({
261
+ "action": "evict",
262
+ "uri": uri,
263
+ })
264
+ return resp.get("status") in ("EVICTED", "PONG", "OK")
265
+
266
+ def purge(self) -> bool:
267
+ """Purges all cached objects from the daemon and resets block allocators."""
268
+ resp = self._send_request({"action": "purge"})
269
+ return resp.get("status") in ("PURGED", "PONG", "OK")
270
+
271
+ def get_status(self) -> dict:
272
+ """Queries live daemon metrics and pool utilization."""
273
+ return self._send_request({"action": "get_status"})
274
+
275
+ def stage_write(
276
+ self,
277
+ uri: str,
278
+ size_bytes: int,
279
+ tier: Optional[str] = None,
280
+ is_leader: bool = False,
281
+ auto_flush_s3: bool = True,
282
+ write_through: bool = False,
283
+ pinned: bool = False,
284
+ ) -> StageWriteResult:
285
+ """
286
+ Stages an asynchronous write-back or synchronous write-through allocation in the control plane.
287
+ Allocates physical chunk layouts across NVMe drives / RAM without blocking.
288
+ """
289
+ req = {
290
+ "action": "stage_write",
291
+ "uri": uri,
292
+ "size_bytes": size_bytes,
293
+ "is_leader": is_leader,
294
+ "auto_flush_s3": auto_flush_s3,
295
+ "write_through": write_through,
296
+ "pinned": pinned,
297
+ }
298
+ if tier is not None:
299
+ req["tier"] = tier.lower()
300
+
301
+ resp = self._send_request(req)
302
+ status = resp.get("status", "ERROR")
303
+
304
+ if status in ("WRITESTAGED", "WRITE_STAGED"):
305
+ chunk_layout = [
306
+ ChunkLocation.from_dict(c) for c in resp.get("chunk_layout", [])
307
+ ]
308
+ return StageWriteResult(
309
+ status=status,
310
+ object_size=resp.get("object_size", size_bytes),
311
+ chunk_size=resp.get("chunk_size", 4194304),
312
+ chunk_layout=chunk_layout,
313
+ sync_status=resp.get("sync_status", "STAGED"),
314
+ )
315
+ else:
316
+ err = resp.get("error_message", "Failed to stage write")
317
+ return StageWriteResult(
318
+ status="ERROR",
319
+ object_size=0,
320
+ chunk_size=0,
321
+ chunk_layout=[],
322
+ sync_status="ERROR",
323
+ error_message=err,
324
+ )
325
+
326
+ def append_write(
327
+ self,
328
+ uri: str,
329
+ size_bytes: int,
330
+ tier: Optional[str] = None,
331
+ ) -> StageWriteResult:
332
+ """
333
+ Incrementally allocates and appends chunk descriptors for a streaming write.
334
+ """
335
+ req = {
336
+ "action": "append_write",
337
+ "uri": uri,
338
+ "size_bytes": size_bytes,
339
+ }
340
+ if tier is not None:
341
+ req["tier"] = tier.lower()
342
+
343
+ resp = self._send_request(req)
344
+ status = resp.get("status", "ERROR")
345
+ if status in ("WRITESTAGED", "WRITE_STAGED"):
346
+ chunk_layout = [
347
+ ChunkLocation.from_dict(c) for c in resp.get("chunk_layout", [])
348
+ ]
349
+ return StageWriteResult(
350
+ status=status,
351
+ object_size=resp.get("object_size", size_bytes),
352
+ chunk_size=resp.get("chunk_size", 4194304),
353
+ chunk_layout=chunk_layout,
354
+ sync_status=resp.get("sync_status", "STAGED"),
355
+ )
356
+ else:
357
+ err = resp.get("error_message", "Failed to append write")
358
+ return StageWriteResult(
359
+ status="ERROR",
360
+ object_size=0,
361
+ chunk_size=0,
362
+ chunk_layout=[],
363
+ sync_status="ERROR",
364
+ error_message=err,
365
+ )
366
+
367
+ def commit_write(
368
+ self,
369
+ uri: str,
370
+ sha256: Optional[str] = None,
371
+ write_through: bool = False,
372
+ ) -> bool:
373
+ """
374
+ Commits a staged write in the control plane, triggering background sync to S3 (write-back)
375
+ or synchronously waiting for authoritative backend flush (write-through).
376
+ """
377
+ req = {
378
+ "action": "commit_write",
379
+ "uri": uri,
380
+ "write_through": write_through,
381
+ }
382
+ if sha256 is not None:
383
+ req["sha256"] = sha256
384
+
385
+ resp = self._send_request(req)
386
+ status = resp.get("status", "ERROR")
387
+ return status in ("WRITECOMMITTED", "WRITE_COMMITTED")
388
+
389
+ def get_write_status(self, uri: str) -> dict:
390
+ """
391
+ Queries current sync status (STAGED, COMMITTED, SYNCING_BACKEND, SYNCED_BACKEND).
392
+ """
393
+ req = {
394
+ "action": "get_write_status",
395
+ "uri": uri,
396
+ }
397
+ resp = self._send_request(req)
398
+ return {
399
+ "status": resp.get("sync_status", "UNKNOWN"),
400
+ "progress_percent": resp.get("sync_progress_percent", 0.0),
401
+ }
402
+
403
+ def record_telemetry(
404
+ self,
405
+ event_type: str,
406
+ uri: str,
407
+ object_size_bytes: int,
408
+ duration_us: int,
409
+ bandwidth_mbps: float,
410
+ client_id: str = "python_benchmark",
411
+ chunk_count: int = 1,
412
+ local_meta_us: int = 0,
413
+ remote_meta_us: int = 0,
414
+ local_ttfb_us: int = 0,
415
+ remote_ttfb_us: int = 0,
416
+ time_saved_ms: int = 0,
417
+ cpu_pct: float = 0.0,
418
+ status: str = "OK",
419
+ ) -> bool:
420
+ """Emits telemetry metrics to the control plane daemon for Prometheus & Grafana."""
421
+ req = {
422
+ "action": "record_telemetry",
423
+ "event_type": event_type,
424
+ "uri": uri,
425
+ "object_size_bytes": object_size_bytes,
426
+ "duration_us": duration_us,
427
+ "bandwidth_mbps": bandwidth_mbps,
428
+ "client_id": client_id,
429
+ "chunk_count": chunk_count,
430
+ "local_meta_us": local_meta_us,
431
+ "remote_meta_us": remote_meta_us,
432
+ "local_ttfb_us": local_ttfb_us,
433
+ "remote_ttfb_us": remote_ttfb_us,
434
+ "time_saved_ms": time_saved_ms,
435
+ "cpu_pct": cpu_pct,
436
+ "status": status,
437
+ }
438
+ try:
439
+ resp = self._send_request(req)
440
+ return resp.get("status") == "PONG"
441
+ except Exception:
442
+ return False
443
+
444
+ def close(self) -> None:
445
+ if self._sock is not None:
446
+ try:
447
+ self._sock.close()
448
+ except Exception:
449
+ pass
450
+ self._sock = None
451
+
452
+ def __enter__(self) -> HyperCacheClient:
453
+ return self
454
+
455
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
456
+ self.close()