hypercache-io 0.9.0__tar.gz → 0.9.1__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.
Files changed (24) hide show
  1. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/PKG-INFO +1 -1
  2. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/__init__.py +1 -1
  3. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/client.py +88 -31
  4. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/datapath.py +144 -20
  5. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache_io.egg-info/PKG-INFO +1 -1
  6. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache_io.egg-info/SOURCES.txt +2 -1
  7. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/pyproject.toml +1 -1
  8. hypercache_io-0.9.1/tests/test_robustness.py +352 -0
  9. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/README.md +0 -0
  10. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/fsspec_fs.py +0 -0
  11. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/integrations/__init__.py +0 -0
  12. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/integrations/dcp.py +0 -0
  13. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/integrations/safetensors_loader.py +0 -0
  14. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/kv_store.py +0 -0
  15. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache/pipeline.py +0 -0
  16. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache_io.egg-info/dependency_links.txt +0 -0
  17. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache_io.egg-info/entry_points.txt +0 -0
  18. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache_io.egg-info/requires.txt +0 -0
  19. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/hypercache_io.egg-info/top_level.txt +0 -0
  20. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/setup.cfg +0 -0
  21. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/tests/test_client.py +0 -0
  22. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/tests/test_fsspec.py +0 -0
  23. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/tests/test_integrations_and_kv.py +0 -0
  24. {hypercache_io-0.9.0 → hypercache_io-0.9.1}/tests/test_pipelined_and_numa.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercache-io
3
- Version: 0.9.0
3
+ Version: 0.9.1
4
4
  Summary: HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads
5
5
  Author: Looe Labs
6
6
  License: Apache-2.0
@@ -58,4 +58,4 @@ __all__ = [
58
58
  "HyperCacheDCPStorageReader",
59
59
  ]
60
60
 
61
- __version__ = "0.9.0"
61
+ __version__ = "0.9.1"
@@ -8,13 +8,18 @@ from __future__ import annotations
8
8
 
9
9
  import json
10
10
  import logging
11
+ import os
11
12
  import socket
13
+ import threading
12
14
  from dataclasses import dataclass
13
15
  from typing import List, Optional
14
16
 
15
17
  from hypercache.datapath import ChunkLocation
16
18
 
17
- import os
19
+ logger = logging.getLogger("hypercache.client")
20
+
21
+ # Sentinel meaning "use the client's default request timeout"
22
+ _DEFAULT = object()
18
23
 
19
24
  PRIMARY_SOCKET_PATH = "/run/hypercache/hypercache.sock"
20
25
  FALLBACK_SOCKET_PATH = "/tmp/hypercache/hypercache.sock"
@@ -23,6 +28,9 @@ LEGACY_SOCKET_PATH = "/tmp/hypercache.sock"
23
28
 
24
29
  def get_default_socket_path() -> str:
25
30
  """Discovers and returns the active HyperCache Unix Domain Socket path."""
31
+ override = os.environ.get("HYPERCACHE_SOCKET_PATH", "").strip()
32
+ if override:
33
+ return override
26
34
  if os.path.exists(PRIMARY_SOCKET_PATH):
27
35
  return PRIMARY_SOCKET_PATH
28
36
  if os.path.exists(FALLBACK_SOCKET_PATH):
@@ -44,6 +52,8 @@ class LocateResult:
44
52
  chunk_size: int
45
53
  chunk_layout: List[ChunkLocation]
46
54
  error_message: Optional[str] = None
55
+ # Layout generation reported by the daemon (changes whenever the URI is re-ingested or rewritten)
56
+ generation: Optional[int] = None
47
57
 
48
58
  @property
49
59
  def is_hit(self) -> bool:
@@ -92,12 +102,46 @@ class DiscoveredDeviceInfo:
92
102
 
93
103
 
94
104
  class HyperCacheClient:
95
- """Client for querying the HyperCache Control Plane daemon via Unix Domain Socket."""
105
+ """Client for querying the HyperCache Control Plane daemon via Unix Domain Socket.
106
+
107
+ A client instance is safe to share between threads (requests are serialized on one
108
+ connection) and across fork() (the child transparently opens its own connection).
96
109
 
97
- def __init__(self, socket_path: Optional[str] = None, timeout: float = 120.0):
110
+ Args:
111
+ socket_path: daemon socket; auto-discovered when omitted.
112
+ timeout: per-request timeout in seconds for metadata calls.
113
+ ingest_timeout: timeout for calls that may download a whole object from S3/NFS
114
+ (locate with auto_ingest, ingest, preload). None waits indefinitely, since
115
+ multi-GB ingests legitimately take minutes.
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ socket_path: Optional[str] = None,
121
+ timeout: float = 120.0,
122
+ ingest_timeout: Optional[float] = None,
123
+ ):
98
124
  self.socket_path = socket_path or get_default_socket_path()
99
125
  self.timeout = timeout
126
+ self.ingest_timeout = ingest_timeout
100
127
  self._sock: Optional[socket.socket] = None
128
+ self._rbuf = bytearray()
129
+ self._lock = threading.RLock()
130
+ self._pid = os.getpid()
131
+
132
+ def _check_fork(self) -> None:
133
+ # A socket inherited from the parent process is shared with it, so a response could
134
+ # be read by the wrong process. Close this process's copy and reconnect lazily.
135
+ if self._pid != os.getpid():
136
+ if self._sock is not None:
137
+ try:
138
+ self._sock.close()
139
+ except Exception:
140
+ pass
141
+ self._sock = None
142
+ self._rbuf = bytearray()
143
+ self._lock = threading.RLock()
144
+ self._pid = os.getpid()
101
145
 
102
146
  def _connect(self) -> socket.socket:
103
147
  if self._sock is not None:
@@ -108,37 +152,43 @@ class HyperCacheClient:
108
152
  sock.settimeout(self.timeout)
109
153
  sock.connect(self.socket_path)
110
154
  self._sock = sock
155
+ self._rbuf = bytearray()
111
156
  return sock
112
157
  except Exception as e:
113
- logger.error(f"Failed to connect to HyperCache daemon at {self.socket_path}: {e}")
158
+ logger.debug(f"Failed to connect to HyperCache daemon at {self.socket_path}: {e}")
114
159
  raise ConnectionError(
115
160
  f"HyperCache daemon unreachable at {self.socket_path}. Is the daemon running?"
116
161
  ) from e
117
162
 
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:
163
+ def _read_line(self, sock: socket.socket) -> bytes:
164
+ while True:
165
+ idx = self._rbuf.find(b"\n")
166
+ if idx >= 0:
167
+ line = bytes(self._rbuf[:idx])
168
+ del self._rbuf[: idx + 1]
169
+ return line
170
+ chunk = sock.recv(65536)
171
+ if not chunk:
135
172
  raise ConnectionResetError("Connection closed by server without response")
173
+ self._rbuf.extend(chunk)
136
174
 
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
175
+ def _send_request(self, payload: dict, timeout=_DEFAULT) -> dict:
176
+ self._check_fork()
177
+ with self._lock:
178
+ sock = self._connect()
179
+ data = (json.dumps(payload) + "\n").encode("utf-8")
180
+ try:
181
+ sock.settimeout(self.timeout if timeout is _DEFAULT else timeout)
182
+ sock.sendall(data)
183
+ while True:
184
+ line = self._read_line(sock)
185
+ if line.strip():
186
+ return json.loads(line.decode("utf-8"))
187
+ except (OSError, ConnectionError, ValueError):
188
+ # Timeouts, resets and garbled frames leave the stream in an unknown
189
+ # position; drop the connection so the next request starts clean.
190
+ self.close()
191
+ raise
142
192
 
143
193
  def ping(self) -> bool:
144
194
  """Checks if the control plane is alive."""
@@ -174,7 +224,7 @@ class HyperCacheClient:
174
224
  if tier is not None:
175
225
  req["tier"] = tier.lower()
176
226
 
177
- resp = self._send_request(req)
227
+ resp = self._send_request(req, timeout=self.ingest_timeout if auto_ingest else _DEFAULT)
178
228
  status = resp.get("status", "ERROR")
179
229
 
180
230
  if status == "HIT":
@@ -186,6 +236,7 @@ class HyperCacheClient:
186
236
  object_size=resp.get("object_size", 0),
187
237
  chunk_size=resp.get("chunk_size", 4194304),
188
238
  chunk_layout=chunk_layout,
239
+ generation=resp.get("generation"),
189
240
  )
190
241
  elif status == "MISS":
191
242
  return LocateResult(
@@ -218,7 +269,7 @@ class HyperCacheClient:
218
269
  }
219
270
  if tier is not None:
220
271
  req["tier"] = tier.lower()
221
- resp = self._send_request(req)
272
+ resp = self._send_request(req, timeout=self.ingest_timeout)
222
273
  status = resp.get("status", "ERROR")
223
274
  if status in ("HIT", "INGESTED"):
224
275
  chunk_layout = [
@@ -229,6 +280,7 @@ class HyperCacheClient:
229
280
  object_size=resp.get("object_size", 0),
230
281
  chunk_size=resp.get("chunk_size", 4194304),
231
282
  chunk_layout=chunk_layout,
283
+ generation=resp.get("generation"),
232
284
  )
233
285
  else:
234
286
  err = resp.get("error_message", "Ingestion failed")
@@ -382,13 +434,17 @@ class HyperCacheClient:
382
434
  if sha256 is not None:
383
435
  req["sha256"] = sha256
384
436
 
385
- resp = self._send_request(req)
437
+ # Commit hashes the staged data (when sha256 is given) and, for write-through, uploads it
438
+ resp = self._send_request(req, timeout=self.ingest_timeout)
386
439
  status = resp.get("status", "ERROR")
387
- return status in ("WRITECOMMITTED", "WRITE_COMMITTED")
440
+ if status not in ("WRITECOMMITTED", "WRITE_COMMITTED"):
441
+ logger.error(f"Commit of '{uri}' failed: {resp.get('error_message', 'unknown error')}")
442
+ return False
443
+ return True
388
444
 
389
445
  def get_write_status(self, uri: str) -> dict:
390
446
  """
391
- Queries current sync status (STAGED, COMMITTED, SYNCING_BACKEND, SYNCED_BACKEND).
447
+ Queries current sync status (STAGED, COMMITTED, SYNCING_BACKEND, SYNCED_BACKEND, SYNC_FAILED).
392
448
  """
393
449
  req = {
394
450
  "action": "get_write_status",
@@ -448,6 +504,7 @@ class HyperCacheClient:
448
504
  except Exception:
449
505
  pass
450
506
  self._sock = None
507
+ self._rbuf = bytearray()
451
508
 
452
509
  def __enter__(self) -> HyperCacheClient:
453
510
  return self
@@ -11,6 +11,7 @@ import logging
11
11
  import mmap
12
12
  import os
13
13
  import threading
14
+ import zlib
14
15
  from concurrent.futures import ThreadPoolExecutor
15
16
  from dataclasses import dataclass
16
17
  from typing import Any, Dict, List, Optional, Tuple, Union
@@ -35,6 +36,38 @@ try:
35
36
  except (ImportError, Exception):
36
37
  pass
37
38
 
39
+ # Opt-in end-to-end integrity check: when set, full-chunk reads are verified against the
40
+ # per-chunk CRC32 recorded by the daemon (adds one zlib.crc32 pass over the data).
41
+ VERIFY_CHECKSUMS_ENV = "HYPERCACHE_VERIFY_CHECKSUMS"
42
+ DEFAULT_BLOCK_SIZE = 4096
43
+
44
+
45
+ def _env_flag(name: str) -> bool:
46
+ return os.environ.get(name, "").strip().lower() in ("1", "true", "yes", "on")
47
+
48
+
49
+ class ChecksumMismatchError(IOError):
50
+ """Raised when chunk data does not match the CRC32 recorded at ingest time."""
51
+
52
+
53
+ def logical_block_size(device_path: str) -> int:
54
+ """Returns the O_DIRECT alignment for a device (sysfs logical_block_size), or 4096."""
55
+ try:
56
+ name = os.path.basename(os.path.realpath(device_path))
57
+ for candidate in (
58
+ f"/sys/class/block/{name}/queue/logical_block_size",
59
+ # Partitions inherit the queue limits of their parent disk
60
+ os.path.join(os.path.dirname(os.path.realpath(f"/sys/class/block/{name}")), "queue", "logical_block_size"),
61
+ ):
62
+ if os.path.exists(candidate):
63
+ with open(candidate) as f:
64
+ value = int(f.read().strip())
65
+ if value > 0 and value & (value - 1) == 0:
66
+ return max(value, 512)
67
+ except (OSError, ValueError):
68
+ pass
69
+ return DEFAULT_BLOCK_SIZE
70
+
38
71
 
39
72
  @dataclass(frozen=True)
40
73
  class ChunkLocation:
@@ -43,23 +76,34 @@ class ChunkLocation:
43
76
  offset: int
44
77
  length: int
45
78
  tier: str = "nvme"
79
+ # CRC32 (zlib.crc32) of the chunk bytes, when the daemon recorded one
80
+ checksum: Optional[int] = None
46
81
 
47
82
  @classmethod
48
83
  def from_dict(cls, data: dict) -> ChunkLocation:
84
+ checksum = data.get("checksum")
49
85
  return cls(
50
86
  device=str(data["device"]),
51
87
  offset=int(data["offset"]),
52
88
  length=int(data["length"]),
53
89
  tier=str(data.get("tier", "nvme")).lower(),
90
+ checksum=int(checksum) if checksum is not None else None,
54
91
  )
55
92
 
93
+ @property
94
+ def is_shm(self) -> bool:
95
+ return self.tier == "ram" or self.device.endswith(".shm")
96
+
56
97
  def to_dict(self) -> dict:
57
- return {
98
+ out = {
58
99
  "device": self.device,
59
100
  "offset": self.offset,
60
101
  "length": self.length,
61
102
  "tier": self.tier,
62
103
  }
104
+ if self.checksum is not None:
105
+ out["checksum"] = self.checksum
106
+ return out
63
107
 
64
108
 
65
109
  class DataReader:
@@ -96,15 +140,67 @@ class DirectBlockReader(DataReader):
96
140
  Uses multi-threaded I/O submission to saturate SSD controller queue depth.
97
141
  """
98
142
 
99
- def __init__(self, max_workers: Optional[int] = None):
143
+ def __init__(self, max_workers: Optional[int] = None, verify_checksums: Optional[bool] = None):
100
144
  self._fd_cache: Dict[str, Tuple[Optional[int], int]] = {}
145
+ self._block_sizes: Dict[str, int] = {}
101
146
  self._lock = threading.Lock()
102
147
  self._closed = False
148
+ self._pid = os.getpid()
149
+ self._local = threading.local()
150
+ self.verify_checksums = _env_flag(VERIFY_CHECKSUMS_ENV) if verify_checksums is None else verify_checksums
151
+ self._stats = {"direct_reads": 0, "direct_fallbacks": 0, "buffered_reads": 0, "shm_reads": 0}
152
+ self._stats_lock = threading.Lock()
103
153
  if max_workers is None:
104
154
  max_workers = min(64, max(16, (os.cpu_count() or 4) * 4))
105
155
  self._max_workers = max_workers
106
156
  self._executor = ThreadPoolExecutor(max_workers=max_workers)
107
157
 
158
+ def _count(self, key: str) -> None:
159
+ with self._stats_lock:
160
+ self._stats[key] += 1
161
+
162
+ def get_stats(self) -> Dict[str, int]:
163
+ """Read path counters. A growing `direct_fallbacks` means O_DIRECT is not engaging."""
164
+ with self._stats_lock:
165
+ return dict(self._stats)
166
+
167
+ def _bounce_buffer(self, size: int) -> mmap.mmap:
168
+ # Anonymous mmaps are page-aligned, which satisfies O_DIRECT buffer alignment.
169
+ # One buffer per worker thread, grown on demand.
170
+ buf = getattr(self._local, "buf", None)
171
+ if buf is None or len(buf) < size:
172
+ if buf is not None:
173
+ buf.close()
174
+ buf = mmap.mmap(-1, size)
175
+ self._local.buf = buf
176
+ return buf
177
+
178
+ def _block_size(self, device_path: str) -> int:
179
+ bs = self._block_sizes.get(device_path)
180
+ if bs is None:
181
+ bs = logical_block_size(device_path)
182
+ self._block_sizes[device_path] = bs
183
+ return bs
184
+
185
+ def _read_direct(self, fd_direct: int, dev_path: str, target_slice: memoryview, phys_offset: int) -> bool:
186
+ """O_DIRECT read via an aligned bounce buffer. Returns False if the caller must fall back."""
187
+ length = len(target_slice)
188
+ bs = self._block_size(dev_path)
189
+ aligned_start = phys_offset - (phys_offset % bs)
190
+ head = phys_offset - aligned_start
191
+ aligned_len = -(-(head + length) // bs) * bs
192
+ buf = self._bounce_buffer(aligned_len)
193
+ try:
194
+ n = os.preadv(fd_direct, [memoryview(buf)[:aligned_len]], aligned_start)
195
+ except OSError as e:
196
+ logger.debug(f"O_DIRECT read failed on {dev_path} at {aligned_start}: {e}")
197
+ return False
198
+ # A short read is fine as long as it covers the requested bytes (e.g. at end of a file)
199
+ if n < head + length:
200
+ return False
201
+ target_slice[:] = memoryview(buf)[head : head + length]
202
+ return True
203
+
108
204
  def _get_fds(self, device_path: str) -> Tuple[Optional[int], int]:
109
205
  if device_path in self._fd_cache:
110
206
  return self._fd_cache[device_path]
@@ -161,42 +257,51 @@ class DirectBlockReader(DataReader):
161
257
  physical_device_offset = chunk.offset + offset_in_chunk
162
258
 
163
259
  dest_pos = target_offset + (overlap_start - start_offset)
164
- tasks.append((chunk.device, overlap_len, physical_device_offset, dest_pos))
260
+ tasks.append((chunk, overlap_len, physical_device_offset, dest_pos))
165
261
 
166
262
  if not tasks:
167
263
  return 0
168
264
 
169
265
  def _read_task(t):
170
- dev_path, overlap_len, phys_offset, dest_pos = t
266
+ chunk, overlap_len, phys_offset, dest_pos = t
267
+ dev_path = chunk.device
171
268
  target_slice = view[dest_pos : dest_pos + overlap_len]
172
269
 
173
- if dev_path.endswith(".shm") or "/shm" in dev_path:
270
+ if chunk.is_shm:
271
+ # Tier 1 chunks are files in /dev/shm: a positioned read copies straight from
272
+ # the shared pages into the destination buffer.
174
273
  try:
175
- with open(dev_path, "rb") as f:
176
- with mmap.mmap(f.fileno(), 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ) as mm:
177
- target_slice[:] = mm[phys_offset : phys_offset + overlap_len]
178
- return overlap_len
274
+ fd = os.open(dev_path, os.O_RDONLY)
275
+ try:
276
+ n = os.preadv(fd, [target_slice], phys_offset) if hasattr(os, "preadv") else None
277
+ if n is None:
278
+ data = os.pread(fd, overlap_len, phys_offset)
279
+ n = len(data)
280
+ target_slice[:n] = data
281
+ finally:
282
+ os.close(fd)
179
283
  except OSError as e:
180
284
  logger.error(f"Failed reading SHM chunk {dev_path}: {e}")
181
285
  raise
286
+ if n != overlap_len:
287
+ raise IOError(f"Short read from SHM chunk {dev_path}: expected {overlap_len}, got {n}")
288
+ self._count("shm_reads")
289
+ return self._verify(chunk, overlap_len, target_slice)
182
290
 
183
291
  fd_direct, fd_buffered = self._get_fds(dev_path)
184
292
 
185
- # Try direct DMA first if O_DIRECT is active and offsets are sector aligned
186
- if fd_direct is not None and hasattr(os, "preadv") and overlap_len % 512 == 0 and phys_offset % 512 == 0:
187
- try:
188
- n = os.preadv(fd_direct, [target_slice], phys_offset)
189
- if n == overlap_len:
190
- return n
191
- except OSError:
192
- pass
293
+ if fd_direct is not None and hasattr(os, "preadv"):
294
+ if self._read_direct(fd_direct, dev_path, target_slice, phys_offset):
295
+ self._count("direct_reads")
296
+ return self._verify(chunk, overlap_len, target_slice)
297
+ self._count("direct_fallbacks")
193
298
 
194
- # Robust fallback to buffered handle
299
+ self._count("buffered_reads")
195
300
  if hasattr(os, "preadv"):
196
301
  try:
197
302
  n = os.preadv(fd_buffered, [target_slice], phys_offset)
198
303
  if n == overlap_len:
199
- return n
304
+ return self._verify(chunk, overlap_len, target_slice)
200
305
  except OSError:
201
306
  pass
202
307
 
@@ -207,7 +312,7 @@ class DirectBlockReader(DataReader):
207
312
  f"expected {overlap_len} bytes, got {len(chunk_data)}"
208
313
  )
209
314
  target_slice[:] = chunk_data
210
- return len(chunk_data)
315
+ return self._verify(chunk, overlap_len, target_slice)
211
316
 
212
317
  if len(tasks) == 1:
213
318
  return _read_task(tasks[0])
@@ -216,6 +321,18 @@ class DirectBlockReader(DataReader):
216
321
  results = list(self._executor.map(_read_task, tasks))
217
322
  return sum(results)
218
323
 
324
+ def _verify(self, chunk: ChunkLocation, read_len: int, data: memoryview) -> int:
325
+ # Only whole-chunk reads can be checked against the per-chunk CRC
326
+ if self.verify_checksums and chunk.checksum is not None and read_len == chunk.length:
327
+ actual = zlib.crc32(data) & 0xFFFFFFFF
328
+ if actual != chunk.checksum:
329
+ raise ChecksumMismatchError(
330
+ f"CRC32 mismatch for chunk at {chunk.device}+{chunk.offset}: "
331
+ f"expected {chunk.checksum:08x}, got {actual:08x}. The cached layout may be stale; "
332
+ f"locate the object again."
333
+ )
334
+ return read_len
335
+
219
336
  def read_range(
220
337
  self,
221
338
  chunk_layout: List[ChunkLocation],
@@ -363,6 +480,7 @@ class GDSReader(DataReader):
363
480
 
364
481
  _SHARED_READERS: Dict[bool, DataReader] = {}
365
482
  _SHARED_READER_LOCK = threading.Lock()
483
+ _SHARED_READER_PID = os.getpid()
366
484
 
367
485
 
368
486
  def get_data_reader(prefer_gds: bool = True) -> DataReader:
@@ -370,7 +488,13 @@ def get_data_reader(prefer_gds: bool = True) -> DataReader:
370
488
  Factory to return the optimal shared DataReader based on hardware environment.
371
489
  Reuses open block-device file descriptors and DMA thread pools across requests.
372
490
  """
491
+ global _SHARED_READER_PID
373
492
  with _SHARED_READER_LOCK:
493
+ if _SHARED_READER_PID != os.getpid():
494
+ # After fork() the parent's thread pools do not exist in the child and its file
495
+ # descriptors / CUDA handles must not be shared: start fresh in this process.
496
+ _SHARED_READERS.clear()
497
+ _SHARED_READER_PID = os.getpid()
374
498
  existing = _SHARED_READERS.get(prefer_gds)
375
499
  if existing is not None and not getattr(existing, "_closed", False):
376
500
  return existing
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercache-io
3
- Version: 0.9.0
3
+ Version: 0.9.1
4
4
  Summary: HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads
5
5
  Author: Looe Labs
6
6
  License: Apache-2.0
@@ -18,4 +18,5 @@ hypercache_io.egg-info/top_level.txt
18
18
  tests/test_client.py
19
19
  tests/test_fsspec.py
20
20
  tests/test_integrations_and_kv.py
21
- tests/test_pipelined_and_numa.py
21
+ tests/test_pipelined_and_numa.py
22
+ tests/test_robustness.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "hypercache-io"
7
- version = "0.9.0"
7
+ version = "0.9.1"
8
8
  description = "HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads"
9
9
  readme = "README.md"
10
10
  license = { text = "Apache-2.0" }
@@ -0,0 +1,352 @@
1
+ """
2
+ Regression tests for client robustness: thread/fork safety, response framing, O_DIRECT
3
+ bounce buffers, tier-based SHM detection, and opt-in CRC32 verification.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ import socket
9
+ import sys
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import unittest
14
+ import warnings
15
+ import zlib
16
+
17
+ from hypercache.client import HyperCacheClient
18
+ from hypercache.datapath import (
19
+ ChecksumMismatchError,
20
+ ChunkLocation,
21
+ DirectBlockReader,
22
+ get_data_reader,
23
+ )
24
+
25
+
26
+ def _fork():
27
+ # The test process is multi-threaded (daemon threads); the child only touches the
28
+ # objects under test, so the generic fork-safety warning does not apply here.
29
+ with warnings.catch_warnings():
30
+ warnings.simplefilter("ignore", DeprecationWarning)
31
+ return os.fork()
32
+
33
+
34
+ class _EchoDaemon:
35
+ """Minimal UDS daemon that answers each request with its own id, optionally
36
+ splitting responses across writes or batching several into one write."""
37
+
38
+ def __init__(self, path: str, mode: str = "normal", delay: float = 0.0):
39
+ self.path = path
40
+ self.mode = mode
41
+ self.delay = delay
42
+ if os.path.exists(path):
43
+ os.remove(path)
44
+ self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
45
+ self.sock.bind(path)
46
+ self.sock.listen(64)
47
+ self.running = True
48
+ threading.Thread(target=self._accept, daemon=True).start()
49
+
50
+ def _accept(self):
51
+ while self.running:
52
+ try:
53
+ conn, _ = self.sock.accept()
54
+ except OSError:
55
+ return
56
+ threading.Thread(target=self._serve, args=(conn,), daemon=True).start()
57
+
58
+ def _serve(self, conn):
59
+ buf = b""
60
+ with conn:
61
+ while True:
62
+ try:
63
+ data = conn.recv(65536)
64
+ except OSError:
65
+ return
66
+ if not data:
67
+ return
68
+ buf += data
69
+ while b"\n" in buf:
70
+ line, buf = buf.split(b"\n", 1)
71
+ if not line.strip():
72
+ continue
73
+ req = json.loads(line)
74
+ if self.delay:
75
+ time.sleep(self.delay)
76
+ resp = {
77
+ "status": "HIT",
78
+ "object_size": int(req.get("uri", "0").rsplit("/", 1)[-1] or 0),
79
+ "chunk_size": 4096,
80
+ "chunk_layout": [],
81
+ "generation": 7,
82
+ }
83
+ out = (json.dumps(resp) + "\n").encode()
84
+ try:
85
+ if self.mode == "split":
86
+ # Deliver the response one byte at a time
87
+ for i in range(len(out)):
88
+ conn.sendall(out[i : i + 1])
89
+ elif self.mode == "trailing_blank":
90
+ conn.sendall(b"\n" + out)
91
+ else:
92
+ conn.sendall(out)
93
+ except OSError:
94
+ # The client gave up (timeout test) and closed its end
95
+ return
96
+
97
+ def close(self):
98
+ self.running = False
99
+ try:
100
+ self.sock.close()
101
+ except OSError:
102
+ pass
103
+ if os.path.exists(self.path):
104
+ os.remove(self.path)
105
+
106
+
107
+ class TestClientConcurrencyAndFraming(unittest.TestCase):
108
+ def setUp(self):
109
+ self.dir = tempfile.mkdtemp(prefix="hc_rb_", dir="/tmp")
110
+ self.path = os.path.join(self.dir, "d.sock")
111
+
112
+ def tearDown(self):
113
+ for name in os.listdir(self.dir):
114
+ try:
115
+ os.remove(os.path.join(self.dir, name))
116
+ except OSError:
117
+ pass
118
+ os.rmdir(self.dir)
119
+
120
+ def test_threads_sharing_one_client_get_their_own_responses(self):
121
+ daemon = _EchoDaemon(self.path)
122
+ try:
123
+ client = HyperCacheClient(socket_path=self.path)
124
+ errors = []
125
+
126
+ def worker(n):
127
+ for i in range(50):
128
+ size = n * 1000 + i
129
+ res = client.locate(f"hypercache://x/{size}", auto_ingest=False)
130
+ if res.object_size != size:
131
+ errors.append((size, res.object_size))
132
+
133
+ threads = [threading.Thread(target=worker, args=(n,)) for n in range(1, 9)]
134
+ for t in threads:
135
+ t.start()
136
+ for t in threads:
137
+ t.join()
138
+ self.assertEqual(errors, [])
139
+ client.close()
140
+ finally:
141
+ daemon.close()
142
+
143
+ def test_response_split_across_reads_and_blank_lines(self):
144
+ for mode in ("split", "trailing_blank"):
145
+ daemon = _EchoDaemon(self.path, mode=mode)
146
+ try:
147
+ client = HyperCacheClient(socket_path=self.path)
148
+ for size in (1, 22, 333):
149
+ res = client.locate(f"hypercache://x/{size}", auto_ingest=False)
150
+ self.assertEqual(res.object_size, size)
151
+ self.assertEqual(res.generation, 7)
152
+ client.close()
153
+ finally:
154
+ daemon.close()
155
+
156
+ def test_timeout_drops_connection_and_next_request_is_clean(self):
157
+ daemon = _EchoDaemon(self.path, delay=0.5)
158
+ try:
159
+ client = HyperCacheClient(socket_path=self.path, timeout=0.1)
160
+ with self.assertRaises(OSError):
161
+ client.locate("hypercache://x/5", auto_ingest=False)
162
+ # The late answer to the first request must not be returned for the second one
163
+ daemon.delay = 0.0
164
+ res = client.locate("hypercache://x/9", auto_ingest=False)
165
+ self.assertEqual(res.object_size, 9)
166
+ client.close()
167
+ finally:
168
+ daemon.close()
169
+
170
+ def test_ingest_calls_use_ingest_timeout(self):
171
+ daemon = _EchoDaemon(self.path, delay=0.3)
172
+ try:
173
+ client = HyperCacheClient(socket_path=self.path, timeout=0.1, ingest_timeout=None)
174
+ # Metadata-only calls honor the short timeout...
175
+ with self.assertRaises(OSError):
176
+ client.locate("hypercache://x/1", auto_ingest=False)
177
+ # ...while ingesting calls wait for the daemon
178
+ self.assertEqual(client.locate("hypercache://x/2", auto_ingest=True).object_size, 2)
179
+ self.assertEqual(client.ingest("hypercache://x/3").object_size, 3)
180
+ client.close()
181
+ finally:
182
+ daemon.close()
183
+
184
+ def test_unreachable_daemon_raises_connection_error(self):
185
+ client = HyperCacheClient(socket_path=os.path.join(self.dir, "missing.sock"))
186
+ with self.assertRaises(ConnectionError):
187
+ client.locate("hypercache://x/1", auto_ingest=False)
188
+ self.assertFalse(client.ping())
189
+
190
+ @unittest.skipUnless(hasattr(os, "fork"), "requires fork()")
191
+ def test_client_reconnects_after_fork(self):
192
+ daemon = _EchoDaemon(self.path)
193
+ try:
194
+ client = HyperCacheClient(socket_path=self.path)
195
+ self.assertEqual(client.locate("hypercache://x/4", auto_ingest=False).object_size, 4)
196
+ parent_sock = client._sock
197
+ r, w = os.pipe()
198
+ pid = _fork()
199
+ if pid == 0: # child
200
+ code = 1
201
+ try:
202
+ os.close(r)
203
+ res = client.locate("hypercache://x/11", auto_ingest=False)
204
+ ok = res.object_size == 11 and client._sock is not parent_sock
205
+ os.write(w, b"1" if ok else b"0")
206
+ code = 0
207
+ finally:
208
+ os._exit(code)
209
+ os.close(w)
210
+ _, status = os.waitpid(pid, 0)
211
+ result = os.read(r, 1)
212
+ os.close(r)
213
+ self.assertEqual(status, 0)
214
+ self.assertEqual(result, b"1")
215
+ # The parent's connection is unaffected
216
+ self.assertEqual(client.locate("hypercache://x/12", auto_ingest=False).object_size, 12)
217
+ client.close()
218
+ finally:
219
+ daemon.close()
220
+
221
+
222
+ class TestDatapathReads(unittest.TestCase):
223
+ def setUp(self):
224
+ self.dir = tempfile.mkdtemp(prefix="hc_dp_")
225
+ self.dev = os.path.join(self.dir, "dev0.raw")
226
+ self.payload = bytes((i * 7) % 251 for i in range(3 * 65536 + 777))
227
+ with open(self.dev, "wb") as f:
228
+ f.write(b"\0" * 4096)
229
+ f.write(self.payload)
230
+ f.write(b"\0" * 8192)
231
+
232
+ def tearDown(self):
233
+ for name in os.listdir(self.dir):
234
+ os.remove(os.path.join(self.dir, name))
235
+ os.rmdir(self.dir)
236
+
237
+ def _layout(self, chunk=65536, crc=True):
238
+ out = []
239
+ pos = 0
240
+ while pos < len(self.payload):
241
+ n = min(chunk, len(self.payload) - pos)
242
+ out.append(
243
+ ChunkLocation(
244
+ device=self.dev,
245
+ offset=4096 + pos,
246
+ length=n,
247
+ checksum=(zlib.crc32(self.payload[pos : pos + n]) if crc else None),
248
+ )
249
+ )
250
+ pos += n
251
+ return out
252
+
253
+ def test_unaligned_ranges_read_correctly(self):
254
+ reader = DirectBlockReader()
255
+ try:
256
+ layout = self._layout()
257
+ for start, length in [(0, len(self.payload)), (1, 4095), (65530, 20), (100, 3 * 65536), (len(self.payload) - 5, 5)]:
258
+ got = bytes(reader.read_range(layout, start, length))
259
+ self.assertEqual(got, self.payload[start : start + length], (start, length))
260
+ stats = reader.get_stats()
261
+ if sys.platform.startswith("linux") and hasattr(os, "O_DIRECT"):
262
+ # With aligned bounce buffers O_DIRECT engages even for unaligned requests,
263
+ # unless the filesystem (e.g. tmpfs) does not support it at all
264
+ if stats["direct_reads"] == 0:
265
+ self.assertGreater(stats["direct_fallbacks"], 0)
266
+ else:
267
+ self.assertEqual(stats["direct_fallbacks"], 0)
268
+ else:
269
+ self.assertGreater(stats["buffered_reads"], 0)
270
+ finally:
271
+ reader.close()
272
+
273
+ def test_checksum_verification_is_opt_in(self):
274
+ layout = self._layout()
275
+ # Corrupt one byte inside chunk 1
276
+ with open(self.dev, "r+b") as f:
277
+ f.seek(4096 + 65536 + 10)
278
+ f.write(b"\xff" if self.payload[65536 + 10] != 0xFF else b"\x00")
279
+
280
+ off = DirectBlockReader(verify_checksums=False)
281
+ try:
282
+ off.read_range(layout, 0, len(self.payload))
283
+ finally:
284
+ off.close()
285
+
286
+ on = DirectBlockReader(verify_checksums=True)
287
+ try:
288
+ # Chunk 0 alone is intact
289
+ self.assertEqual(bytes(on.read_range(layout, 0, 65536)), self.payload[:65536])
290
+ with self.assertRaises(ChecksumMismatchError):
291
+ on.read_range(layout, 0, len(self.payload))
292
+ # Partial reads cannot be verified and are served as-is
293
+ on.read_range(layout, 65536 + 5, 100)
294
+ finally:
295
+ on.close()
296
+
297
+ os.environ["HYPERCACHE_VERIFY_CHECKSUMS"] = "1"
298
+ try:
299
+ env_reader = DirectBlockReader()
300
+ self.assertTrue(env_reader.verify_checksums)
301
+ env_reader.close()
302
+ finally:
303
+ del os.environ["HYPERCACHE_VERIFY_CHECKSUMS"]
304
+
305
+ def test_ram_tier_detected_by_tier_not_path(self):
306
+ shm_file = os.path.join(self.dir, "chunk_0_abc") # no "/shm" in the name
307
+ with open(shm_file, "wb") as f:
308
+ f.write(self.payload[:5000])
309
+ reader = DirectBlockReader()
310
+ try:
311
+ loc = ChunkLocation(device=shm_file, offset=0, length=5000, tier="ram", checksum=zlib.crc32(self.payload[:5000]))
312
+ self.assertTrue(loc.is_shm)
313
+ self.assertEqual(bytes(reader.read_range([loc], 10, 100)), self.payload[10:110])
314
+ self.assertEqual(reader.get_stats()["shm_reads"], 1)
315
+ finally:
316
+ reader.close()
317
+
318
+ def test_chunk_location_round_trip_and_legacy(self):
319
+ legacy = ChunkLocation.from_dict({"device": "/dev/x", "offset": 4096, "length": 10})
320
+ self.assertIsNone(legacy.checksum)
321
+ self.assertNotIn("checksum", legacy.to_dict())
322
+ new = ChunkLocation.from_dict({"device": "/dev/x", "offset": 4096, "length": 10, "tier": "RAM", "checksum": 123})
323
+ self.assertEqual(new.tier, "ram")
324
+ self.assertEqual(new.to_dict()["checksum"], 123)
325
+
326
+ @unittest.skipUnless(hasattr(os, "fork"), "requires fork()")
327
+ def test_shared_reader_is_recreated_after_fork(self):
328
+ parent_reader = get_data_reader(prefer_gds=False)
329
+ r, w = os.pipe()
330
+ pid = _fork()
331
+ if pid == 0:
332
+ code = 1
333
+ try:
334
+ os.close(r)
335
+ child_reader = get_data_reader(prefer_gds=False)
336
+ data = bytes(child_reader.read_range(self._layout(), 0, 100))
337
+ ok = child_reader is not parent_reader and data == self.payload[:100]
338
+ os.write(w, b"1" if ok else b"0")
339
+ code = 0
340
+ finally:
341
+ os._exit(code)
342
+ os.close(w)
343
+ _, status = os.waitpid(pid, 0)
344
+ result = os.read(r, 1)
345
+ os.close(r)
346
+ self.assertEqual(status, 0)
347
+ self.assertEqual(result, b"1")
348
+ self.assertIs(get_data_reader(prefer_gds=False), parent_reader)
349
+
350
+
351
+ if __name__ == "__main__":
352
+ unittest.main()
File without changes
File without changes