forked from kvcache-ai/Mooncake
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstructured_object_store.py
More file actions
1524 lines (1348 loc) · 55.1 KB
/
Copy pathstructured_object_store.py
File metadata and controls
1524 lines (1348 loc) · 55.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import ctypes
import json
import uuid
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Iterator, Literal, Mapping, Optional, Protocol, Sequence
import numpy as np
DEFAULT_BUNDLE_CHUNK_BYTES = 512 * 1024**2
AUTO_PARALLEL_MIN_BYTES = 4 * 1024**3
AUTO_PARALLEL_MIN_CHUNKS = 8
MISSING_OBJECT_ERROR = (
-704
) # Mooncake remove returns -704 for an already-missing object.
STRUCTURED_FIELD_SPECS_KEY = "__mooncake_structured_fields__"
class BundleStore(Protocol):
def put(self, key: str, value: Any) -> int: ...
def get(self, key: str) -> bytes: ...
def remove(self, key: str, force: bool = False) -> int: ...
@dataclass(frozen=True)
class BundleTransferPolicy:
"""Controls generic bundle transfer parallelism."""
max_inflight_put: int = 1
put_mode: Literal["auto", "batch", "parallel"] = "auto"
@dataclass
class RemoteBundleRef:
"""Reference to a generic named-buffer bundle stored in Mooncake."""
manifest_key: str
manifest: dict[str, Any]
@dataclass(frozen=True, init=False)
class StructuredObjectPayload:
"""Structured object encoded as metadata plus named buffers."""
metadata: Mapping[str, Any]
buffers: Mapping[str, Any]
def __init__(
self,
metadata: Optional[Mapping[str, Any]] = None,
buffers: Optional[Mapping[str, Any]] = None,
) -> None:
if buffers is None:
raise TypeError("StructuredObjectPayload requires buffers")
object.__setattr__(self, "metadata", {} if metadata is None else metadata)
object.__setattr__(self, "buffers", buffers)
@dataclass
class StructuredObjectResult:
"""Materialized structured object data fetched from Mooncake."""
metadata: dict[str, Any]
objects: dict[str, Any]
@dataclass(frozen=True)
class StructuredMemberSlice:
"""Slice description for one structured member."""
axis: int
start: int
end: int
step: int = 1
@dataclass(frozen=True)
class StructuredObjectReadSpec:
"""Lazy read plan for structured object materialization."""
ref: RemoteBundleRef | Mapping[str, Any]
member_names: tuple[str, ...] | None = None
member_slices: tuple[tuple[str, StructuredMemberSlice], ...] = ()
def select_members(
self, names: Optional[Sequence[str]]
) -> "StructuredObjectReadSpec":
"""Return a new spec that materializes only the selected members."""
return StructuredObjectReadSpec(
ref=self.ref,
member_names=None if names is None else tuple(names),
member_slices=self.member_slices,
)
def slice_member(
self,
name: str,
axis: int,
start: int,
end: int,
step: int = 1,
) -> "StructuredObjectReadSpec":
"""Return a new spec with a slice applied to one member."""
slice_spec = StructuredMemberSlice(axis=axis, start=start, end=end, step=step)
member_slices = dict(self.member_slices)
member_slices[name] = slice_spec
return StructuredObjectReadSpec(
ref=self.ref,
member_names=self.member_names,
member_slices=tuple(member_slices.items()),
)
def member_slice(self, name: str) -> StructuredMemberSlice | None:
"""Return the configured slice for a member, if any."""
return dict(self.member_slices).get(name)
@dataclass(frozen=True)
class _NdarrayReadPlan:
dtype: np.dtype[Any]
full_shape: tuple[int, ...]
output_shape: tuple[int, ...]
byte_offset: int
byte_length: int
step: int
cover_row_count: int
class MooncakeBundleTransfer:
"""Transfer structured objects through Mooncake, with a low-level bundle fallback."""
def __init__(
self,
store: BundleStore,
key_prefix: str = "bundle",
default_chunk_bytes: int = DEFAULT_BUNDLE_CHUNK_BYTES,
) -> None:
"""Initialize a bundle transfer helper with a configurable default chunk size."""
self.store = store
self.key_prefix = _normalize_key_prefix(key_prefix)
self.default_chunk_bytes = _validate_chunk_bytes(default_chunk_bytes)
self._transport = _MooncakePayloadTransport(store)
self._bundle_store = _BundleManifestStore(
store=store,
transport=self._transport,
key_prefix=self.key_prefix,
default_chunk_bytes=self.default_chunk_bytes,
)
self._structured_store = _StructuredObjectLayer(self._bundle_store)
def put_bundle(
self,
meta: bytes | bytearray | memoryview,
buffers: Mapping[str, Any],
partition: str = "default",
chunk_bytes: Optional[int] = None,
policy: Optional[BundleTransferPolicy] = None,
max_inflight_put: Optional[int] = None,
pre_registered_buffers: Optional[Mapping[str, bool]] = None,
) -> RemoteBundleRef:
"""Store raw metadata bytes plus named buffers as a low-level bundle."""
return self._bundle_store.put_bundle(
meta=meta,
buffers=buffers,
partition=partition,
chunk_bytes=chunk_bytes,
policy=policy,
max_inflight_put=max_inflight_put,
pre_registered_buffers=pre_registered_buffers,
)
def remove_bundle(self, ref: RemoteBundleRef | Mapping[str, Any]) -> None:
"""Remove all Mooncake objects that belong to a stored bundle."""
self._bundle_store.remove_bundle(ref)
def put_structured_object(
self,
payload: StructuredObjectPayload,
partition: str = "default",
chunk_bytes: Optional[int] = None,
policy: Optional[BundleTransferPolicy] = None,
max_inflight_put: Optional[int] = None,
) -> RemoteBundleRef:
"""Store a structured object described by JSON metadata plus named members."""
return self._structured_store.put_structured_object(
payload=payload,
partition=partition,
chunk_bytes=chunk_bytes,
policy=policy,
max_inflight_put=max_inflight_put,
)
def read_spec(
self, ref: RemoteBundleRef | Mapping[str, Any]
) -> StructuredObjectReadSpec:
"""Create a lazy read spec for a structured object reference."""
return self._structured_store.read_spec(ref)
def materialize(self, spec: StructuredObjectReadSpec) -> StructuredObjectResult:
"""Materialize a structured object read spec."""
return self._structured_store.materialize(spec)
def materialize_into(
self,
spec: StructuredObjectReadSpec,
destinations: Optional[Mapping[str, Any]],
) -> StructuredObjectResult:
"""Materialize a structured object read spec into caller-provided destinations when possible."""
return self._structured_store.materialize_into(spec, destinations)
class _StructuredObjectLayer:
def __init__(self, bundle_store: "_BundleManifestStore") -> None:
self._bundle_store = bundle_store
def put_structured_object(
self,
payload: StructuredObjectPayload,
partition: str,
chunk_bytes: Optional[int],
policy: Optional[BundleTransferPolicy],
max_inflight_put: Optional[int],
) -> RemoteBundleRef:
metadata, buffers = _encode_structured_fields(payload.metadata, payload.buffers)
return self._bundle_store.put_bundle(
meta=_encode_structured_metadata(metadata),
buffers=buffers,
partition=partition,
chunk_bytes=chunk_bytes,
policy=policy,
max_inflight_put=max_inflight_put,
)
def read_spec(
self, ref: RemoteBundleRef | Mapping[str, Any]
) -> StructuredObjectReadSpec:
return StructuredObjectReadSpec(ref=ref)
def materialize(self, spec: StructuredObjectReadSpec) -> StructuredObjectResult:
return self.materialize_into(spec, destinations=None)
def materialize_into(
self,
spec: StructuredObjectReadSpec,
destinations: Optional[Mapping[str, Any]],
) -> StructuredObjectResult:
metadata, buffers, selected = self._resolve_structured_read(spec)
field_specs = _structured_field_specs(metadata)
destination_map = destinations or {}
member_slices = dict(spec.member_slices)
objects = {
name: self._read_structured_member(
name=name,
payload_spec=buffers[name],
field_spec=field_specs.get(name, {"encoding": "bytes"}),
member_slice=member_slices.get(name),
destination=destination_map.get(name),
)
for name in selected
}
return StructuredObjectResult(metadata=dict(metadata), objects=objects)
def _resolve_structured_read(
self,
spec: StructuredObjectReadSpec,
) -> tuple[dict[str, Any], Mapping[str, Any], list[str]]:
if spec.member_names is not None and not spec.member_names:
raise ValueError("structured read spec selected no members")
manifest = self._bundle_store.resolve_manifest(spec.ref)
metadata = _decode_structured_metadata(
self._bundle_store.read_payload(manifest["meta"])
)
buffers = manifest["buffers"]
selected = (
list(buffers) if spec.member_names is None else list(spec.member_names)
)
missing = [name for name in selected if name not in buffers]
if missing:
raise KeyError(f"unknown bundle buffers: {missing}")
return metadata, buffers, selected
def _read_structured_member(
self,
name: str,
payload_spec: Mapping[str, Any],
field_spec: Mapping[str, Any],
member_slice: StructuredMemberSlice | None,
destination: Any,
) -> Any:
encoding = field_spec.get("encoding", "bytes")
if encoding == "bytes":
return self._read_bytes_member(
name, payload_spec, member_slice, destination
)
if encoding != "ndarray":
raise ValueError(f"unsupported structured field encoding: {encoding}")
return self._read_ndarray_member(
name, payload_spec, field_spec, member_slice, destination
)
def _read_bytes_member(
self,
name: str,
payload_spec: Mapping[str, Any],
member_slice: StructuredMemberSlice | None,
destination: Any,
) -> bytes:
if member_slice is not None:
raise ValueError(f"structured bytes member {name} does not support slicing")
if destination is not None:
raise ValueError(
f"structured bytes member {name} does not support materialize_into"
)
return self._bundle_store.read_payload(payload_spec)
def _read_ndarray_member(
self,
name: str,
payload_spec: Mapping[str, Any],
field_spec: Mapping[str, Any],
member_slice: StructuredMemberSlice | None,
destination: Any,
) -> np.ndarray:
dtype = field_spec.get("dtype")
shape = field_spec.get("shape")
if not isinstance(dtype, str) or not isinstance(shape, list):
raise ValueError(
f"structured ndarray field {name} is missing dtype or shape"
)
read_plan = _resolve_ndarray_read_plan(
tuple(int(dim) for dim in shape), np.dtype(dtype), member_slice
)
target = _resolve_ndarray_destination(
name, destination, read_plan.dtype, read_plan.output_shape
)
destination_view = target.view(np.uint8).reshape(-1)
if read_plan.byte_length == 0:
return target
if read_plan.step == 1:
self._bundle_store.read_payload_range_into_destination(
payload_spec,
destination_view,
read_plan.byte_offset,
)
return target
temp_shape = (read_plan.cover_row_count, *read_plan.full_shape[1:])
temp = np.empty(temp_shape, dtype=read_plan.dtype)
temp_view = temp.view(np.uint8).reshape(-1)
self._bundle_store.read_payload_range_into_destination(
payload_spec, temp_view, read_plan.byte_offset
)
target[...] = temp[:: read_plan.step]
return target
class _BundleManifestStore:
def __init__(
self,
store: BundleStore,
transport: "_MooncakePayloadTransport",
key_prefix: str,
default_chunk_bytes: int,
) -> None:
self._store = store
self._transport = transport
self._key_prefix = key_prefix
self._default_chunk_bytes = default_chunk_bytes
def put_bundle(
self,
meta: bytes | bytearray | memoryview,
buffers: Mapping[str, Any],
partition: str,
chunk_bytes: Optional[int],
policy: Optional[BundleTransferPolicy],
max_inflight_put: Optional[int],
pre_registered_buffers: Optional[Mapping[str, bool]] = None,
) -> RemoteBundleRef:
_validate_key_segment(partition, "partition")
meta_view = _bytes_view(meta, "meta")
target_chunk_bytes = _validate_chunk_bytes(
self._default_chunk_bytes if chunk_bytes is None else chunk_bytes
)
transfer_policy = self._policy(policy, max_inflight_put=max_inflight_put)
object_id = f"{partition}/{uuid.uuid4().hex}"
base_key = f"{self._key_prefix}/{object_id}"
manifest_key = f"{base_key}/manifest"
written_keys: list[str] = []
buffer_specs: dict[str, Any] = {}
pre_registered_map = dict(pre_registered_buffers or {})
try:
meta_spec, meta_keys = self._put_payload(
f"{base_key}/meta",
meta_view,
target_chunk_bytes,
transfer_policy,
pre_registered=False,
)
written_keys.extend(meta_keys)
for name, value in buffers.items():
_validate_key_segment(name, "buffer name")
payload_view = _bytes_view(value, name)
payload_spec, payload_keys = self._put_payload(
f"{base_key}/buffer/{name}",
payload_view,
target_chunk_bytes,
transfer_policy,
pre_registered=bool(pre_registered_map.get(name, False)),
)
buffer_specs[name] = payload_spec
written_keys.extend(payload_keys)
manifest = {
"version": 1,
"layout": "bundle",
"object_id": object_id,
"meta": meta_spec,
"buffers": buffer_specs,
}
manifest_blob = _encode_manifest(manifest)
_check_status(
self._store.put(manifest_key, manifest_blob), "put", manifest_key
)
written_keys.append(manifest_key)
except Exception:
_cleanup_keys(self._store, written_keys, strict=False)
raise
return RemoteBundleRef(manifest_key=manifest_key, manifest=manifest)
def remove_bundle(self, ref: RemoteBundleRef | Mapping[str, Any]) -> None:
manifest = self.resolve_manifest(ref)
keys = self._payload_keys(manifest)
keys.append(self._manifest_key(ref, manifest))
_cleanup_keys(self._store, keys, strict=True)
def resolve_manifest(
self, ref: RemoteBundleRef | Mapping[str, Any]
) -> dict[str, Any]:
if isinstance(ref, RemoteBundleRef):
manifest = ref.manifest
else:
manifest = ref.get("manifest")
if manifest is None:
manifest_key = ref.get("manifest_key")
if not isinstance(manifest_key, str):
raise ValueError("bundle ref must include manifest_key")
manifest = _decode_manifest(self._store.get(manifest_key))
self._validate_manifest(manifest)
return manifest
def read_payload(self, payload_spec: Mapping[str, Any]) -> bytes:
return self._transport.read_payload(payload_spec)
def read_payload_range_into_destination(
self,
payload_spec: Mapping[str, Any],
destination: np.ndarray,
byte_offset: int,
destination_pre_registered: bool = False,
) -> None:
self._transport.read_payload_range_into_destination(
payload_spec,
destination,
byte_offset,
destination_pre_registered=destination_pre_registered,
)
def _put_payload(
self,
key: str,
value: memoryview,
chunk_bytes: int,
transfer_policy: BundleTransferPolicy,
pre_registered: bool,
) -> tuple[dict[str, Any], list[str]]:
chunks = _split_view(value, chunk_bytes)
chunk_keys = [
key if len(chunks) == 1 else f"{key}/chunk/{index}"
for index in range(len(chunks))
]
written_keys = self._transport.put_payload_chunks(
chunk_keys,
chunks,
transfer_policy,
pre_registered=pre_registered,
)
payload_spec = {
"key": key,
"bytes": len(value),
"chunks": [
{"key": chunk_key, "bytes": len(chunk)}
for chunk_key, chunk in zip(chunk_keys, chunks)
],
}
return payload_spec, written_keys
def _policy(
self,
policy: Optional[BundleTransferPolicy],
max_inflight_put: Optional[int] = None,
) -> BundleTransferPolicy:
result = policy or BundleTransferPolicy()
if max_inflight_put is not None:
result = BundleTransferPolicy(
max_inflight_put=max_inflight_put, put_mode=result.put_mode
)
if result.max_inflight_put < 1:
raise ValueError("max_inflight_put must be positive")
if result.put_mode not in {"auto", "batch", "parallel"}:
raise ValueError(f"unsupported put_mode: {result.put_mode}")
return result
def _validate_manifest(self, manifest: Mapping[str, Any]) -> None:
if manifest.get("version") != 1 or manifest.get("layout") != "bundle":
raise ValueError("invalid bundle manifest")
object_id = manifest.get("object_id")
if not isinstance(object_id, str):
raise ValueError("bundle manifest object_id must be a string")
base_key = f"{self._key_prefix}/{object_id}"
self._validate_payload_spec(manifest.get("meta"), base_key)
buffers = manifest.get("buffers")
if not isinstance(buffers, dict):
raise ValueError("bundle manifest buffers must be a dict")
for name, payload_spec in buffers.items():
_validate_key_segment(name, "buffer name")
self._validate_payload_spec(payload_spec, base_key)
def _validate_payload_spec(self, payload_spec: Any, base_key: str) -> None:
if not isinstance(payload_spec, dict):
raise ValueError("bundle payload spec must be a dict")
payload_key = payload_spec.get("key")
if not isinstance(payload_key, str) or not payload_key.startswith(
f"{base_key}/"
):
raise ValueError("bundle payload key is outside the bundle namespace")
expected_bytes = int(payload_spec.get("bytes", -1))
if expected_bytes < 0:
raise ValueError("bundle payload bytes must be non-negative")
chunks = payload_spec.get("chunks")
if not isinstance(chunks, list) or (expected_bytes and not chunks):
raise ValueError("bundle payload chunks are invalid")
seen_keys = set()
total_bytes = 0
for chunk in chunks:
if not isinstance(chunk, dict):
raise ValueError("bundle chunk must be a dict")
key = chunk.get("key")
chunk_bytes = int(chunk.get("bytes", -1))
if not isinstance(key, str) or (
key != payload_key and not key.startswith(f"{payload_key}/")
):
raise ValueError("bundle chunk key is outside the payload namespace")
if key in seen_keys:
raise ValueError("bundle chunk keys must be unique")
if chunk_bytes < 0:
raise ValueError("bundle chunk bytes must be non-negative")
seen_keys.add(key)
total_bytes += chunk_bytes
if total_bytes != expected_bytes:
raise ValueError(
f"bundle payload chunks total {total_bytes} bytes, expected {expected_bytes}"
)
def _manifest_key(
self, ref: RemoteBundleRef | Mapping[str, Any], manifest: Mapping[str, Any]
) -> str:
expected = f"{self._key_prefix}/{manifest['object_id']}/manifest"
manifest_key = (
ref.manifest_key
if isinstance(ref, RemoteBundleRef)
else ref.get("manifest_key")
)
if manifest_key is None:
return expected
if manifest_key != expected:
raise ValueError("bundle manifest_key does not match manifest object_id")
return manifest_key
def _payload_keys(self, manifest: Mapping[str, Any]) -> list[str]:
return [
chunk["key"]
for payload_spec in [manifest["meta"], *manifest["buffers"].values()]
for chunk in payload_spec["chunks"]
]
class _MooncakePayloadTransport:
"""Move payload bytes through Mooncake, preferring fast-path APIs and falling back to generic store calls."""
def __init__(self, store: BundleStore) -> None:
self._store = store
self._batch_put_from = getattr(store, "batch_put_from", None)
self._batch_get_into = getattr(store, "batch_get_into", None)
self._get_into = getattr(store, "get_into", None)
self._get_into_ranges = getattr(store, "get_into_ranges", None)
self._register_buffer = getattr(store, "register_buffer", None)
self._unregister_buffer = getattr(store, "unregister_buffer", None)
def put_payload_chunks(
self,
chunk_keys: Sequence[str],
chunks: Sequence[memoryview],
transfer_policy: BundleTransferPolicy,
pre_registered: bool,
) -> list[str]:
if not self._has_batch_put_support():
return self._put_chunks_direct(chunk_keys, chunks)
put_mode = self._resolve_put_mode(chunks, transfer_policy)
if put_mode == "batch":
self.batch_put_chunks_from(
chunk_keys, chunks, pre_registered=pre_registered
)
return list(chunk_keys)
return self._put_chunks_parallel(
list(chunk_keys),
list(chunks),
transfer_policy.max_inflight_put,
pre_registered=pre_registered,
)
def read_payload(self, payload_spec: Mapping[str, Any]) -> bytes:
expected_bytes = int(payload_spec["bytes"])
if expected_bytes == 0:
return b""
data = bytearray(expected_bytes)
self.read_payload_into(payload_spec, data)
return bytes(data)
def read_payload_into(
self, payload_spec: Mapping[str, Any], destination: bytearray | np.ndarray
) -> None:
chunks = payload_spec["chunks"]
offsets = _chunk_offsets(chunks)
if self._read_chunks_with_batch_get_into(chunks, offsets, destination):
return
for offset, chunk in zip(offsets, chunks):
self._read_chunk_with_get(chunk, destination, offset)
def read_payload_range_into_destination(
self,
payload_spec: Mapping[str, Any],
destination: np.ndarray,
byte_offset: int,
destination_pre_registered: bool,
) -> None:
chunks = payload_spec["chunks"]
byte_length = _buffer_nbytes(destination)
if not self._read_payload_range_into_registered_destination(
chunks,
destination,
byte_offset,
byte_length,
destination_pre_registered=destination_pre_registered,
):
self._copy_payload_range_into_destination(
chunks, destination, byte_offset, byte_length
)
def batch_put_chunks_from(
self,
chunk_keys: Sequence[str],
chunks: Sequence[memoryview],
pre_registered: bool,
) -> None:
batch_put_from = self._batch_put_from
if not callable(batch_put_from):
raise RuntimeError("batch_put_from is unavailable")
if not chunk_keys:
return
prepared_chunks = [_prepare_chunk_source_buffer(chunk) for chunk in chunks]
buffer_ptrs = [ptr for _owner, ptr, _size in prepared_chunks]
sizes = [size for _owner, _ptr, size in prepared_chunks]
registered_ptrs = self._register_buffers(
buffer_ptrs, sizes, pre_registered, "bundle source payload"
)
try:
results = batch_put_from(list(chunk_keys), buffer_ptrs, sizes)
if len(results) != len(chunk_keys):
raise RuntimeError(
f"batch_put_from returned {len(results)} results for {len(chunk_keys)} chunks"
)
for chunk_key, status in zip(chunk_keys, results):
_check_status(status, "batch_put_from", chunk_key)
except Exception:
_cleanup_keys(self._store, chunk_keys, strict=False)
raise
finally:
self._unregister_buffers(registered_ptrs, "bundle source payload")
def _put_chunks_direct(
self,
chunk_keys: Sequence[str],
chunks: Sequence[memoryview],
) -> list[str]:
written_keys: list[str] = []
try:
for chunk_key, chunk in zip(chunk_keys, chunks):
_check_status(self._store.put(chunk_key, chunk), "put", chunk_key)
written_keys.append(chunk_key)
except Exception:
_cleanup_keys(self._store, written_keys, strict=False)
raise
return list(chunk_keys)
def _put_chunks_parallel(
self,
chunk_keys: list[str],
chunks: list[memoryview],
max_inflight_put: int,
pre_registered: bool,
) -> list[str]:
groups = self._group_chunk_ranges(chunk_keys, chunks, max_inflight_put)
futures: list[Future[None]] = []
try:
with ThreadPoolExecutor(
max_workers=min(max_inflight_put, len(groups))
) as executor:
futures = [
executor.submit(
self.batch_put_chunks_from,
group_keys,
group_chunks,
pre_registered,
)
for group_keys, group_chunks in groups
]
for future in as_completed(futures):
future.result()
except Exception:
for future in futures:
future.cancel()
for future in futures:
if future.done() and not future.cancelled():
try:
future.result()
except Exception:
pass
_cleanup_keys(self._store, chunk_keys, strict=False)
raise
return chunk_keys
def _group_chunk_ranges(
self,
chunk_keys: Sequence[str],
chunks: Sequence[memoryview],
max_inflight_put: int,
) -> list[tuple[list[str], list[memoryview]]]:
if not chunk_keys:
return []
group_count = max(1, min(max_inflight_put, len(chunks)))
group_size = (len(chunks) + group_count - 1) // group_count
return [
(
list(chunk_keys[start : start + group_size]),
list(chunks[start : start + group_size]),
)
for start in range(0, len(chunks), group_size)
]
def _read_chunks_with_batch_get_into(
self,
chunks: Sequence[Mapping[str, Any]],
offsets: Sequence[int],
destination: bytearray | np.ndarray,
) -> bool:
batch_get_into = self._batch_get_into
if not callable(batch_get_into) or not self._has_buffer_registration_support():
return False
with self._registered_buffer(destination, "bundle payload") as base_ptr:
keys = [chunk["key"] for chunk in chunks]
ptrs = [base_ptr + offset for offset in offsets]
sizes = [int(chunk["bytes"]) for chunk in chunks]
read_sizes = batch_get_into(keys, ptrs, sizes)
if len(read_sizes) != len(keys):
raise RuntimeError(
f"batch_get_into returned {len(read_sizes)} results for {len(keys)} chunks"
)
for key, expected_size, actual_size in zip(keys, sizes, read_sizes):
if actual_size != expected_size:
raise RuntimeError(
f"batch_get_into failed for {key}: expected {expected_size}, got {actual_size}"
)
return True
def _read_chunk_with_get(
self,
chunk: Mapping[str, Any],
destination: bytearray | np.ndarray,
offset: int,
) -> None:
chunk_bytes = int(chunk["bytes"])
if chunk_bytes == 0:
return
data = self._store.get(chunk["key"])
if len(data) != chunk_bytes:
raise RuntimeError(
f"get failed for {chunk['key']}: expected {chunk_bytes} bytes, got {len(data)}"
)
destination[offset : offset + chunk_bytes] = data
def _read_payload_range_into_registered_destination(
self,
chunks: Sequence[Mapping[str, Any]],
destination: np.ndarray,
byte_offset: int,
byte_length: int,
destination_pre_registered: bool,
) -> bool:
get_into = self._get_into
can_use_get_into = len(chunks) == 1 and byte_offset == 0 and callable(get_into)
get_into_ranges = self._get_into_ranges
can_use_get_into_ranges = callable(get_into_ranges)
if not self._has_buffer_registration_support():
return False
if not can_use_get_into and not can_use_get_into_ranges:
return False
with self._registered_buffer(
destination,
"structured ndarray payload",
pre_registered=destination_pre_registered,
) as base_ptr:
if can_use_get_into and int(chunks[0]["bytes"]) == byte_length:
expected_size = int(chunks[0]["bytes"])
read_size = get_into(chunks[0]["key"], base_ptr, expected_size)
if read_size != expected_size:
raise RuntimeError(
f"get_into failed for {chunks[0]['key']}: expected {expected_size}, got {read_size}"
)
return True
if not can_use_get_into_ranges:
return False
fragments = _payload_range_fragments(chunks, byte_offset, byte_length)
if not fragments:
return True
keys = [
key
for key, _chunk_size, _destination_offset, _source_offset, _size in fragments
]
dst_offsets = [
[destination_offset]
for _key, _chunk_size, destination_offset, _source_offset, _size in fragments
]
src_offsets = [
[source_offset]
for _key, _chunk_size, _destination_offset, source_offset, _size in fragments
]
sizes = [
[size]
for _key, _chunk_size, _destination_offset, _source_offset, size in fragments
]
results = get_into_ranges(
[base_ptr], [keys], [dst_offsets], [src_offsets], [sizes]
)
if len(results) != 1 or len(results[0]) != len(keys):
raise RuntimeError(
f"get_into_ranges returned invalid ranged result shape for {len(keys)} chunks"
)
for key, expected_sizes, actual_sizes in zip(keys, sizes, results[0]):
if len(actual_sizes) != len(expected_sizes):
raise RuntimeError(
f"get_into_ranges returned invalid ranged fragment count for {key}"
)
for expected_size, actual_size in zip(expected_sizes, actual_sizes):
if actual_size != expected_size:
raise RuntimeError(
f"get_into_ranges failed for {key}: expected {expected_size}, got {actual_size}"
)
return True
def _copy_payload_range_into_destination(
self,
chunks: Sequence[Mapping[str, Any]],
destination: np.ndarray,
byte_offset: int,
byte_length: int,
) -> None:
for (
key,
chunk_size,
destination_offset,
source_offset,
size,
) in _payload_range_fragments(
chunks,
byte_offset,
byte_length,
):
data = self._store.get(key)
if len(data) != chunk_size:
raise RuntimeError(
f"get failed for {key}: expected {chunk_size} bytes, got {len(data)}"
)
fragment = memoryview(data)[source_offset : source_offset + size]
target_end = destination_offset + size
destination[destination_offset:target_end] = np.frombuffer(
fragment, dtype=np.uint8
)
def _register_buffers(
self,
buffer_ptrs: Sequence[int],
sizes: Sequence[int],
pre_registered: bool,
label: str,
) -> list[int]:
register_buffer = self._register_buffer
unregister_buffer = self._unregister_buffer
if pre_registered:
return []
if not (callable(register_buffer) and callable(unregister_buffer)):
raise RuntimeError(f"register_buffer APIs are unavailable for {label}")
registered_ptrs: list[int] = []
try:
for ptr, size in zip(buffer_ptrs, sizes):
register_status = register_buffer(ptr, size)
if register_status == 0:
registered_ptrs.append(ptr)
continue
if not _is_duplicate_buffer_registration(register_status):
_check_status(register_status, "register_buffer", label)
except Exception:
self._unregister_buffers(registered_ptrs, label)
raise
return registered_ptrs
def _unregister_buffers(self, registered_ptrs: Sequence[int], label: str) -> None:
unregister_buffer = self._unregister_buffer
if not callable(unregister_buffer):
raise RuntimeError(f"unregister_buffer APIs are unavailable for {label}")
for ptr in reversed(registered_ptrs):
_check_status(unregister_buffer(ptr), "unregister_buffer", label)
@contextmanager
def _registered_buffer(
self,
destination: bytearray | np.ndarray,
label: str,
pre_registered: bool = False,
) -> Iterator[int]:
base_ptr = _buffer_ptr(destination)
if pre_registered:
yield base_ptr
return
registered_ptrs = self._register_buffers(
[base_ptr], [_buffer_nbytes(destination)], False, label
)
if not registered_ptrs:
yield base_ptr
return
succeeded = False
try:
yield base_ptr
succeeded = True
finally:
try:
self._unregister_buffers(registered_ptrs, label)
except Exception:
if succeeded:
raise
def _resolve_put_mode(
self,
chunks: Sequence[memoryview],
transfer_policy: BundleTransferPolicy,
) -> Literal["batch", "parallel"]:
if transfer_policy.put_mode == "parallel":
return "parallel"
if transfer_policy.put_mode == "batch":
return "batch"
if transfer_policy.max_inflight_put <= 1:
return "batch"
if len(chunks) < AUTO_PARALLEL_MIN_CHUNKS:
return "batch"
if sum(len(chunk) for chunk in chunks) < AUTO_PARALLEL_MIN_BYTES:
return "batch"
if min(transfer_policy.max_inflight_put, len(chunks)) < 2:
return "batch"
return "parallel"
def _has_batch_put_support(self) -> bool:
return (
callable(self._batch_put_from) and self._has_buffer_registration_support()
)
def _has_buffer_registration_support(self) -> bool:
return callable(self._register_buffer) and callable(self._unregister_buffer)
def _resolve_ndarray_destination(
name: str,
destination: Any,
dtype: np.dtype[Any],
shape: tuple[int, ...],
) -> np.ndarray:
if destination is None:
return np.empty(shape, dtype=dtype)