-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlib.rs
More file actions
476 lines (439 loc) · 18.1 KB
/
lib.rs
File metadata and controls
476 lines (439 loc) · 18.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
#![warn(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
use std::borrow::Cow;
use std::collections::HashMap;
use std::ptr::NonNull;
use std::sync::Arc;
use chunk_item::ChunkItem;
use itertools::Itertools;
use numpy::npyffi::PyArrayObject;
use numpy::{PyArrayDescrMethods, PyUntypedArray, PyUntypedArrayMethods};
use pyo3::exceptions::{PyRuntimeError, PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3_stub_gen::define_stub_info_gatherer;
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pymethods};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use rayon_iter_concurrent_limit::iter_concurrent_limit;
use unsafe_cell_slice::UnsafeCellSlice;
use utils::is_whole_chunk;
use zarrs::array::{
ArrayBytes, ArrayBytesDecodeIntoTarget, ArrayBytesFixedDisjointView, ArrayMetadata,
ArrayPartialDecoderTraits, ArrayToBytesCodecTraits, CodecChain, CodecOptions, DataType,
FillValue, StoragePartialDecoder, copy_fill_value_into, update_array_bytes,
};
use zarrs::config::global_config;
use zarrs::convert::array_metadata_v2_to_v3;
use zarrs::plugin::ZarrVersion;
use zarrs::storage::{ReadableWritableListableStorage, StorageHandle, StoreKey};
mod chunk_item;
mod concurrency;
mod runtime;
mod store;
#[cfg(test)]
mod tests;
mod utils;
use crate::concurrency::ChunkConcurrentLimitAndCodecOptions;
use crate::store::StoreConfig;
use crate::utils::{PyCodecErrExt, PyErrExt as _};
// TODO: Use a OnceLock for store with get_or_try_init when stabilised?
#[gen_stub_pyclass]
#[pyclass]
pub struct CodecPipelineImpl {
pub(crate) store: ReadableWritableListableStorage,
pub(crate) codec_chain: Arc<CodecChain>,
pub(crate) codec_options: CodecOptions,
pub(crate) chunk_concurrent_minimum: usize,
pub(crate) chunk_concurrent_maximum: usize,
pub(crate) num_threads: usize,
pub(crate) fill_value: FillValue,
pub(crate) data_type: DataType,
}
impl CodecPipelineImpl {
fn retrieve_chunk_bytes<'a>(
&self,
item: &ChunkItem,
codec_chain: &CodecChain,
codec_options: &CodecOptions,
) -> PyResult<ArrayBytes<'a>> {
let value_encoded = self.store.get(&item.key).map_py_err::<PyRuntimeError>()?;
let value_decoded = if let Some(value_encoded) = value_encoded {
let value_encoded: Vec<u8> = value_encoded.into(); // zero-copy in this case
codec_chain
.decode(
value_encoded.into(),
&item.shape,
&self.data_type,
&self.fill_value,
codec_options,
)
.map_codec_err()?
} else {
ArrayBytes::new_fill_value(&self.data_type, item.num_elements, &self.fill_value)
.map_py_err::<PyRuntimeError>()?
};
Ok(value_decoded)
}
fn store_chunk_bytes(
&self,
item: &ChunkItem,
codec_chain: &CodecChain,
value_decoded: ArrayBytes,
codec_options: &CodecOptions,
) -> PyResult<()> {
value_decoded
.validate(item.num_elements, &self.data_type)
.map_codec_err()?;
if value_decoded.is_fill_value(&self.fill_value) {
self.store.erase(&item.key).map_py_err::<PyRuntimeError>()
} else {
let value_encoded = codec_chain
.encode(
value_decoded,
&item.shape,
&self.data_type,
&self.fill_value,
codec_options,
)
.map(Cow::into_owned)
.map_codec_err()?;
// Store the encoded chunk
self.store
.set(&item.key, value_encoded.into())
.map_py_err::<PyRuntimeError>()
}
}
fn store_chunk_subset_bytes(
&self,
item: &ChunkItem,
codec_chain: &CodecChain,
chunk_subset_bytes: ArrayBytes,
codec_options: &CodecOptions,
) -> PyResult<()> {
let array_shape = &item.shape;
let chunk_subset = &item.chunk_subset;
if !chunk_subset.inbounds_shape(bytemuck::must_cast_slice(array_shape)) {
return Err(PyErr::new::<PyValueError, _>(format!(
"chunk subset ({chunk_subset}) is out of bounds for array shape ({array_shape:?})"
)));
}
let data_type_size = self.data_type.size();
if is_whole_chunk(item) {
// Fast path if the chunk subset spans the entire chunk, no read required
self.store_chunk_bytes(item, codec_chain, chunk_subset_bytes, codec_options)
} else {
// Validate the chunk subset bytes
chunk_subset_bytes
.validate(chunk_subset.num_elements(), &self.data_type)
.map_codec_err()?;
// Retrieve the chunk
let chunk_bytes_old = self.retrieve_chunk_bytes(item, codec_chain, codec_options)?;
// Update the chunk
let chunk_bytes_new = update_array_bytes(
chunk_bytes_old,
bytemuck::must_cast_slice(array_shape),
chunk_subset,
&chunk_subset_bytes,
data_type_size,
)
.map_codec_err()?;
// Store the updated chunk
self.store_chunk_bytes(item, codec_chain, chunk_bytes_new, codec_options)
}
}
fn py_untyped_array_to_array_object<'a>(
value: &'a Bound<'_, PyUntypedArray>,
) -> &'a PyArrayObject {
// TODO: Upstream a PyUntypedArray.as_array_ref()?
// https://github.com/zarrs/zarrs-python/pull/80/files/75be39184905d688ac04a5f8bca08c5241c458cd#r1918365296
let array_object_ptr: NonNull<PyArrayObject> = NonNull::new(value.as_array_ptr())
.expect("bug in numpy crate: Bound<'_, PyUntypedArray>::as_array_ptr unexpectedly returned a null pointer");
let array_object: &'a PyArrayObject = unsafe {
// SAFETY: the array object pointed to by array_object_ptr is valid for 'a
array_object_ptr.as_ref()
};
array_object
}
fn nparray_to_slice<'a>(value: &'a Bound<'_, PyUntypedArray>) -> Result<&'a [u8], PyErr> {
if !value.is_c_contiguous() {
return Err(PyErr::new::<PyValueError, _>(
"input array must be a C contiguous array".to_string(),
));
}
let array_object: &PyArrayObject = Self::py_untyped_array_to_array_object(value);
let array_data = array_object.data.cast::<u8>();
let array_len = value.len() * value.dtype().itemsize();
let slice = unsafe {
// SAFETY: array_data is a valid pointer to a u8 array of length array_len
debug_assert!(!array_data.is_null());
std::slice::from_raw_parts(array_data, array_len)
};
Ok(slice)
}
fn nparray_to_unsafe_cell_slice<'a>(
value: &'a Bound<'_, PyUntypedArray>,
) -> Result<UnsafeCellSlice<'a, u8>, PyErr> {
if !value.is_c_contiguous() {
return Err(PyErr::new::<PyValueError, _>(
"input array must be a C contiguous array".to_string(),
));
}
let array_object: &PyArrayObject = Self::py_untyped_array_to_array_object(value);
let array_data = array_object.data.cast::<u8>();
let array_len = value.len() * value.dtype().itemsize();
let output = unsafe {
// SAFETY: array_data is a valid pointer to a u8 array of length array_len
debug_assert!(!array_data.is_null());
std::slice::from_raw_parts_mut(array_data, array_len)
};
Ok(UnsafeCellSlice::new(output))
}
}
#[gen_stub_pymethods]
#[pymethods]
impl CodecPipelineImpl {
#[pyo3(signature = (
array_metadata,
store_config,
*,
validate_checksums=false,
chunk_concurrent_minimum=None,
chunk_concurrent_maximum=None,
num_threads=None,
direct_io=false,
))]
#[new]
fn new(
array_metadata: &str,
mut store_config: StoreConfig,
validate_checksums: bool,
chunk_concurrent_minimum: Option<usize>,
chunk_concurrent_maximum: Option<usize>,
num_threads: Option<usize>,
direct_io: bool,
) -> PyResult<Self> {
store_config.direct_io(direct_io);
let metadata = serde_json::from_str(array_metadata).map_py_err::<PyTypeError>()?;
let metadata_v3 = match &metadata {
ArrayMetadata::V2(v2) => {
Cow::Owned(array_metadata_v2_to_v3(v2).map_py_err::<PyTypeError>()?)
}
ArrayMetadata::V3(v3) => Cow::Borrowed(v3),
};
let codec_chain =
Arc::new(CodecChain::from_metadata(&metadata_v3.codecs).map_py_err::<PyTypeError>()?);
let codec_options = CodecOptions::default().with_validate_checksums(validate_checksums);
let chunk_concurrent_minimum =
chunk_concurrent_minimum.unwrap_or(global_config().chunk_concurrent_minimum());
let chunk_concurrent_maximum =
chunk_concurrent_maximum.unwrap_or(rayon::current_num_threads());
let num_threads = num_threads.unwrap_or(rayon::current_num_threads());
let store: ReadableWritableListableStorage =
(&store_config).try_into().map_py_err::<PyTypeError>()?;
let data_type =
DataType::from_metadata(&metadata_v3.data_type).map_py_err::<PyTypeError>()?;
let fill_value = data_type
.fill_value(&metadata_v3.fill_value, ZarrVersion::V3)
.or_else(|_| {
Err(match &metadata {
ArrayMetadata::V2(metadata) => format!(
"incompatible fill value metadata: dtype={}, fill_value={}",
metadata.dtype, metadata.fill_value
),
ArrayMetadata::V3(metadata) => format!(
"incompatible fill value metadata: data_type={}, fill_value={}",
metadata.data_type, metadata.fill_value
),
})
})
.map_py_err::<PyTypeError>()?;
Ok(Self {
store,
codec_chain,
codec_options,
chunk_concurrent_minimum,
chunk_concurrent_maximum,
num_threads,
fill_value,
data_type,
})
}
fn retrieve_chunks_and_apply_index(
&self,
py: Python,
chunk_descriptions: Vec<chunk_item::ChunkItem>, // FIXME: Ref / iterable?
value: &Bound<'_, PyUntypedArray>,
) -> PyResult<()> {
// Get input array
let output = Self::nparray_to_unsafe_cell_slice(value)?;
// Adjust the concurrency based on the codec chain and the first chunk description
let Some((chunk_concurrent_limit, codec_options)) =
chunk_descriptions.get_chunk_concurrent_limit_and_codec_options(self)?
else {
return Ok(());
};
// Assemble partial decoders ahead of time and in parallel
let partial_chunk_items = chunk_descriptions
.iter()
.filter(|item| !(is_whole_chunk(item)))
.unique_by(|item| item.key.clone())
.collect::<Vec<_>>();
let mut partial_decoder_cache: HashMap<StoreKey, Arc<dyn ArrayPartialDecoderTraits>> =
HashMap::new();
if !partial_chunk_items.is_empty() {
let key_decoder_pairs =
iter_concurrent_limit!(chunk_concurrent_limit, partial_chunk_items, map, |item| {
let storage_handle = Arc::new(StorageHandle::new(self.store.clone()));
let input_handle = StoragePartialDecoder::new(storage_handle, item.key.clone());
let partial_decoder = self
.codec_chain
.clone()
.partial_decoder(
Arc::new(input_handle),
&item.shape,
&self.data_type,
&self.fill_value,
&codec_options,
)
.map_codec_err()?;
Ok((item.key.clone(), partial_decoder))
})
.collect::<PyResult<Vec<_>>>()?;
partial_decoder_cache.extend(key_decoder_pairs);
}
py.detach(move || {
// FIXME: the `decode_into` methods only support fixed length data types.
// For variable length data types, need a codepath with non `_into` methods.
// Collect all the subsets and copy into value on the Python side?
let update_chunk_subset = |item: ChunkItem| {
let mut output_view = unsafe {
// TODO: Is the following correct?
// can we guarantee that when this function is called from Python with arbitrary arguments?
// SAFETY: chunks represent disjoint array subsets
ArrayBytesFixedDisjointView::new(
output,
// TODO: why is data_type in `item`, it should be derived from `output`, no?
self.data_type
.fixed_size()
.ok_or("variable length data type not supported")
.map_py_err::<PyTypeError>()?,
bytemuck::must_cast_slice(&item.array_shape),
item.subset.clone(),
)
.map_py_err::<PyRuntimeError>()?
};
let target = ArrayBytesDecodeIntoTarget::Fixed(&mut output_view);
// See zarrs::array::Array::retrieve_chunk_subset_into
if is_whole_chunk(&item) {
// See zarrs::array::Array::retrieve_chunk_into
if let Some(chunk_encoded) =
self.store.get(&item.key).map_py_err::<PyRuntimeError>()?
{
// Decode the encoded data into the output buffer
let chunk_encoded: Vec<u8> = chunk_encoded.into();
self.codec_chain.decode_into(
Cow::Owned(chunk_encoded),
&item.shape,
&self.data_type,
&self.fill_value,
target,
&codec_options,
)
} else {
// The chunk is missing, write the fill value
copy_fill_value_into(&self.data_type, &self.fill_value, target)
}
} else {
let key = &item.key;
let partial_decoder = partial_decoder_cache.get(key).ok_or_else(|| {
PyRuntimeError::new_err(format!("Partial decoder not found for key: {key}"))
})?;
partial_decoder.partial_decode_into(&item.chunk_subset, target, &codec_options)
}
.map_codec_err()
};
iter_concurrent_limit!(
chunk_concurrent_limit,
chunk_descriptions,
try_for_each,
update_chunk_subset
)?;
Ok(())
})
}
fn store_chunks_with_indices(
&self,
py: Python,
chunk_descriptions: Vec<chunk_item::ChunkItem>,
value: &Bound<'_, PyUntypedArray>,
write_empty_chunks: bool,
) -> PyResult<()> {
enum InputValue<'a> {
Array(ArrayBytes<'a>),
Constant(FillValue),
}
// Get input array
let input_slice = Self::nparray_to_slice(value)?;
let input = if value.ndim() > 0 {
// FIXME: Handle variable length data types, convert value to bytes and offsets
InputValue::Array(ArrayBytes::new_flen(Cow::Borrowed(input_slice)))
} else {
InputValue::Constant(FillValue::new(input_slice.to_vec()))
};
// Adjust the concurrency based on the codec chain and the first chunk description
let Some((chunk_concurrent_limit, mut codec_options)) =
chunk_descriptions.get_chunk_concurrent_limit_and_codec_options(self)?
else {
return Ok(());
};
codec_options.set_store_empty_chunks(write_empty_chunks);
py.detach(move || {
let store_chunk = |item: ChunkItem| match &input {
InputValue::Array(input) => {
let chunk_subset_bytes = input
.extract_array_subset(
&item.subset,
bytemuck::must_cast_slice(&item.array_shape),
&self.data_type,
)
.map_codec_err()?;
self.store_chunk_subset_bytes(
&item,
&self.codec_chain,
chunk_subset_bytes,
&codec_options,
)
}
InputValue::Constant(constant_value) => {
let chunk_subset_bytes = ArrayBytes::new_fill_value(
&self.data_type,
item.chunk_subset.num_elements(),
constant_value,
)
.map_py_err::<PyRuntimeError>()?;
self.store_chunk_subset_bytes(
&item,
&self.codec_chain,
chunk_subset_bytes,
&codec_options,
)
}
};
iter_concurrent_limit!(
chunk_concurrent_limit,
chunk_descriptions,
try_for_each,
store_chunk
)?;
Ok(())
})
}
}
/// A Python module implemented in Rust.
#[pymodule]
fn _internal(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add_class::<CodecPipelineImpl>()?;
m.add_class::<chunk_item::ChunkItem>()?;
Ok(())
}
define_stub_info_gatherer!(stub_info);