Repository navigation
Expand file tree
/
Copy pathZarrArray.cs
More file actions
1355 lines (1153 loc) · 49.9 KB
/
Copy pathZarrArray.cs
File metadata and controls
1355 lines (1153 loc) · 49.9 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
using System.Buffers;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ZarrNET;
using ZarrNET.Core.Zarr.Store;
namespace ZarrNET.Core.Zarr;
/// <summary>
/// Represents a single Zarr v3 array. Knows how to read and write chunks
/// via the store using the array's codec pipeline and chunk key encoding.
///
/// When sharding is active (Metadata.Sharding is non-null), the outer
/// ChunkShape represents the shard shape and the actual data granularity
/// is the inner chunk shape. ReadRegionAsync transparently handles both
/// cases — callers do not need to know whether sharding is in use.
///
/// Does not interpret array contents — that is the responsibility of callers
/// who know the OME axis semantics.
/// </summary>
public sealed class ZarrArray
{
private static int s_writeDebugCount = 0;
private static int s_readDebugCount = 0;
private static readonly ConcurrentDictionary<string, byte> s_writePlaneProbeLogged = new(StringComparer.Ordinal);
private static readonly ConcurrentDictionary<string, byte> s_readPlaneProbeLogged = new(StringComparer.Ordinal);
private readonly IZarrStore _store;
private readonly string _arrayPath; // store-relative path to the array root
private readonly CodecPipeline _pipeline;
// Effective chunk shape — inner chunk shape when sharding, outer chunk shape otherwise.
// This is the granularity at which ReadRegionAsync iterates and assembles data.
private readonly long[] _chunkShapeLong;
private readonly long _chunkElementCount;
private readonly long[] _chunkCounts;
private readonly int _fullChunkByteCount;
private readonly bool _canStoreDecodedBytesWithoutTransform;
public ZarrArrayMetadata Metadata { get; }
internal ZarrArray(IZarrStore store, string arrayPath, ZarrArrayMetadata metadata)
{
_store = store;
_arrayPath = arrayPath.TrimEnd('/');
Metadata = metadata;
_pipeline = CodecFactory.BuildPipeline(metadata);
// When sharding is active, the effective chunk shape is the inner chunk shape.
// The outer chunk shape (shard shape) is used only for building store keys.
var effectiveChunkShape = metadata.Sharding?.InnerChunkShape ?? metadata.ChunkShape;
_chunkShapeLong = effectiveChunkShape.Select(s => (long)s).ToArray();
_chunkElementCount = effectiveChunkShape.Aggregate(1L, (acc, s) => acc * s);
_chunkCounts = ComputeChunkCounts(_chunkShapeLong);
_fullChunkByteCount = checked((int)(_chunkElementCount * Metadata.DataType.ElementSize));
_canStoreDecodedBytesWithoutTransform = _pipeline.CanStoreDecodedBytesWithoutTransform;
}
// -------------------------------------------------------------------------
// Public API
// -------------------------------------------------------------------------
// Keep per-tile chunk fan-out low so panning does not build up large
// numbers of in-flight byte[] buffers before the previous viewport has
// finished decoding and uploading.
public const int MaxParallelChunks = 2;
// Global semaphore: caps the total number of concurrent chunk S3 fetches
// across all parallel tile requests to prevent memory spikes.
private static readonly SemaphoreSlim s_globalFetchSemaphore = new SemaphoreSlim(16, 16);
/// <summary>
/// Reads a region of the array defined by per-axis [start, end) ranges.
/// Returns the decoded bytes for that region, assembled from the
/// relevant chunks. Shape of the returned region is (end - start) per axis.
///
/// Chunks are fetched and decoded in parallel, bounded by maxParallelChunks.
/// Each chunk maps to a non-overlapping slice of the output buffer, so the
/// copy step is safe without locking.
/// </summary>
/// <param name="regionStart">Per-axis inclusive start indices.</param>
/// <param name="regionEnd">Per-axis exclusive end indices.</param>
/// <param name="maxParallelChunks">
/// Maximum number of chunks to fetch/decode concurrently.
/// Defaults to <see cref="Environment.ProcessorCount"/>.
/// HTTP callers may benefit from higher values (e.g. 16–32);
/// local disk callers can leave the default or lower it.
/// Pass 1 to disable parallelism.
/// </param>
/// <param name="ct">Cancellation token.</param>
public async Task<byte[]> ReadRegionAsync(
long[] regionStart,
long[] regionEnd,
int? maxParallelChunks = MaxParallelChunks,
CancellationToken ct = default)
{
ValidateRegion(regionStart, regionEnd);
var regionShape = ComputeRegionShape(regionStart, regionEnd);
var elementSize = Metadata.DataType.ElementSize;
var totalElements = ComputeTotalElements(regionShape);
var outputBuffer = new byte[totalElements * elementSize];
var chunkCoords = EnumerateChunkCoordinates(regionStart, regionEnd);
var parallelism = maxParallelChunks ?? Environment.ProcessorCount;
// When sharding is active, cache shard file bytes so that multiple inner
// chunks within the same shard don't trigger redundant store reads.
// The cache is scoped to this single ReadRegionAsync call.
var shardCache = Metadata.Sharding is not null
? new ConcurrentDictionary<string, Task<byte[]?>>(StringComparer.Ordinal)
: null;
var options = new ParallelOptions
{
MaxDegreeOfParallelism = Math.Max(1, parallelism),
CancellationToken = ct
};
await Parallel.ForEachAsync(chunkCoords, options, async (chunkCoord, token) =>
{
var chunkData = await ReadChunkAsync(chunkCoord, shardCache, token).ConfigureAwait(false);
if (chunkData != null)
CopyChunkRegionToOutput(
chunkCoord,
chunkData,
regionStart,
regionEnd,
regionShape,
outputBuffer,
elementSize);
}).ConfigureAwait(false);
return outputBuffer;
}
/// <summary>
/// Writes a region of the array defined by per-axis [start, end) ranges.
/// Data must be a flat byte array matching the region shape exactly.
/// Performs read-modify-write for partial chunk writes.
/// </summary>
public async Task WriteRegionAsync(
long[] regionStart,
long[] regionEnd,
byte[] data,
CancellationToken ct = default)
=> await WriteRegionAsync(regionStart, regionEnd, data.AsMemory(), ct).ConfigureAwait(false);
/// <summary>
/// Writes a region of the array defined by per-axis [start, end) ranges.
/// Data must be flat bytes matching the region shape exactly.
/// Performs read-modify-write for partial chunk writes.
/// </summary>
public async Task WriteRegionAsync(
long[] regionStart,
long[] regionEnd,
ReadOnlyMemory<byte> data,
CancellationToken ct = default)
{
ValidateRegion(regionStart, regionEnd);
var regionShape = ComputeRegionShape(regionStart, regionEnd);
var elementSize = Metadata.DataType.ElementSize;
var expectedBytes = ComputeTotalElements(regionShape) * elementSize;
if (data.Length != expectedBytes)
throw new ArgumentException(
$"Data length {data.Length} does not match region size {expectedBytes} bytes.");
var chunkCoords = EnumerateChunkCoordinates(regionStart, regionEnd);
foreach (var chunkCoord in chunkCoords)
{
ct.ThrowIfCancellationRequested();
await WriteChunkRegionAsync(
chunkCoord,
regionStart,
regionEnd,
regionShape,
data,
elementSize,
ct).ConfigureAwait(false);
}
}
/// <summary>
/// Enumerates every logical chunk in the array's regular chunk grid.
/// The returned chunk shape is clamped to the array extent for edge chunks.
/// </summary>
public async IAsyncEnumerable<ZarrChunkRef> EnumerateChunksAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
if (Metadata.Shape.Any(s => s == 0))
yield break;
var start = new long[Metadata.Rank];
var end = (long[])Metadata.Shape.Clone();
await foreach (var chunk in EnumerateChunksAsync(start, end, ct).ConfigureAwait(false))
yield return chunk;
}
/// <summary>
/// Enumerates logical chunks intersecting the region [regionStart, regionEnd).
/// The returned chunk shape is clamped to both the array extent and edge chunks,
/// but not to the requested region; each reference identifies a whole chunk.
/// </summary>
public async IAsyncEnumerable<ZarrChunkRef> EnumerateChunksAsync(
long[] regionStart,
long[] regionEnd,
[EnumeratorCancellation] CancellationToken ct = default)
{
ValidateRegion(regionStart, regionEnd);
foreach (var chunkCoord in EnumerateChunkCoordinates(regionStart, regionEnd))
{
ct.ThrowIfCancellationRequested();
yield return BuildChunkRef(chunkCoord);
}
await Task.CompletedTask.ConfigureAwait(false);
}
/// <summary>
/// Reads and decodes a full logical chunk without routing through a region
/// output buffer. Missing chunks are returned as fill-value chunks.
///
/// The returned buffer is padded to the full effective chunk shape used by
/// this array. Use <see cref="ZarrChunkRef.Shape"/> to identify the valid
/// in-array extent for edge chunks.
/// </summary>
public async Task<byte[]> ReadChunkDecodedAsync(
ZarrChunkRef chunk,
CancellationToken ct = default)
{
ValidateChunkRef(chunk);
var shardCache = Metadata.Sharding is not null
? new ConcurrentDictionary<string, Task<byte[]?>>(StringComparer.Ordinal)
: null;
return await ReadChunkAsync(chunk.ChunkCoord, shardCache, ct).ConfigureAwait(false);
}
/// <summary>
/// Reads a full logical chunk into caller-owned memory. The destination must be
/// at least the full effective chunk byte count. When <paramref name="allowBorrowedBuffer"/>
/// is true and the codec pipeline is a no-op bytes path, the store may read
/// directly into <paramref name="destination"/>.
/// </summary>
public async Task ReadChunkDecodedAsync(
ZarrChunkRef chunk,
Memory<byte> destination,
bool allowBorrowedBuffer,
CancellationToken ct = default)
{
ValidateChunkRef(chunk);
var expectedBytes = _fullChunkByteCount;
if (destination.Length < expectedBytes)
throw new ArgumentException(
$"Destination has {destination.Length} bytes, expected at least {expectedBytes} bytes " +
$"for full chunk shape [{string.Join(", ", _chunkShapeLong)}].",
nameof(destination));
var chunkDestination = destination[..expectedBytes];
if (allowBorrowedBuffer
&& Metadata.Sharding is null
&& _canStoreDecodedBytesWithoutTransform)
{
var key = BuildChunkContainingStoreKey(chunk.ChunkCoord);
var bytesRead = await _store.ReadAsync(key, chunkDestination, ct).ConfigureAwait(false);
if (bytesRead is null)
{
BuildFillValueChunk().CopyTo(chunkDestination);
return;
}
if (bytesRead.Value == expectedBytes)
return;
var normalized = PadOrValidateDecodedChunk(
chunkDestination[..bytesRead.Value].ToArray(),
chunk.ChunkCoord);
normalized.CopyTo(chunkDestination);
return;
}
var decoded = await ReadChunkDecodedAsync(chunk, ct).ConfigureAwait(false);
decoded.CopyTo(chunkDestination);
}
public Task ReadChunkDecodedAsync(
long[] chunkCoord,
Memory<byte> destination,
bool allowBorrowedBuffer,
CancellationToken ct = default)
=> ReadChunkDecodedAsync(
BuildChunkRef(chunkCoord),
destination,
allowBorrowedBuffer,
ct);
/// <summary>
/// Encodes and writes a full logical chunk without read-modify-write.
/// The input must be a full effective chunk buffer, including fill-value
/// padding for any edge region outside the array extent.
/// </summary>
public async Task WriteChunkDecodedAsync(
ZarrChunkRef chunk,
byte[] decodedData,
CancellationToken ct = default)
=> await WriteChunkDecodedAsync(
chunk,
decodedData.AsMemory(),
allowBorrowedBuffer: false,
ct).ConfigureAwait(false);
/// <summary>
/// Encodes and writes a full logical chunk without read-modify-write.
/// The input memory length must be the full effective chunk byte count.
/// Pooled buffers may be passed as a sliced memory region; the memory is
/// consumed or copied before the returned task completes.
/// </summary>
public async Task WriteChunkDecodedAsync(
ZarrChunkRef chunk,
ReadOnlyMemory<byte> decodedData,
CancellationToken ct = default)
=> await WriteChunkDecodedAsync(
chunk,
decodedData,
allowBorrowedBuffer: false,
ct).ConfigureAwait(false);
/// <summary>
/// Encodes and writes a full logical chunk without read-modify-write.
/// When <paramref name="allowBorrowedBuffer"/> is true and the codec pipeline is
/// a no-op bytes path, caller-owned memory is consumed directly by the store
/// before this task completes.
/// </summary>
public async Task WriteChunkDecodedAsync(
ZarrChunkRef chunk,
ReadOnlyMemory<byte> decodedData,
bool allowBorrowedBuffer,
CancellationToken ct = default)
{
if (Metadata.Sharding is not null)
throw new NotSupportedException(
"Decoded chunk writes are not supported for sharded arrays.");
ValidateChunkRef(chunk);
var expectedBytes = _fullChunkByteCount;
if (decodedData.Length != expectedBytes)
throw new ArgumentException(
$"decodedData has {decodedData.Length} bytes, expected {expectedBytes} bytes " +
$"for full chunk shape [{string.Join(", ", _chunkShapeLong)}].",
nameof(decodedData));
if (allowBorrowedBuffer && _canStoreDecodedBytesWithoutTransform)
{
var key = BuildChunkContainingStoreKey(chunk.ChunkCoord);
await _store.WriteAsync(key, decodedData, ct).ConfigureAwait(false);
return;
}
await WriteChunkAsync(
chunk.ChunkCoord,
ToExactArray(decodedData),
ct).ConfigureAwait(false);
}
public Task WriteChunkDecodedAsync(
long[] chunkCoord,
ReadOnlyMemory<byte> decodedData,
bool allowBorrowedBuffer,
CancellationToken ct = default)
=> WriteChunkDecodedAsync(
BuildChunkRef(chunkCoord),
decodedData,
allowBorrowedBuffer,
ct);
/// <summary>
/// Writes full decoded logical chunks with bounded concurrency. When
/// <paramref name="allowBorrowedBuffers"/> is true and the codec pipeline is
/// a no-op bytes path, payloads are written directly through the store batch
/// path with no encode/copy and no read-modify-write.
/// </summary>
public async Task WriteChunksDecodedAsync(
IReadOnlyList<ZarrDecodedChunkWrite> chunks,
int maxDegreeOfParallelism,
bool allowBorrowedBuffers,
CancellationToken ct = default)
{
if (Metadata.Sharding is not null)
throw new NotSupportedException(
"Decoded chunk writes are not supported for sharded arrays.");
ArgumentNullException.ThrowIfNull(chunks);
ValidateMaxDegreeOfParallelism(maxDegreeOfParallelism);
if (allowBorrowedBuffers && _canStoreDecodedBytesWithoutTransform)
{
var chunkCounts = _chunkCounts;
var fullChunkByteCount = _fullChunkByteCount;
for (var i = 0; i < chunks.Count; i++)
{
ct.ThrowIfCancellationRequested();
ValidateDecodedChunkWrite(chunks[i], chunkCounts, fullChunkByteCount);
}
if (_store is LocalFileSystemStore localStore)
{
await localStore.WriteDecodedChunksAsync(
chunks,
static chunk => chunk.Key,
maxDegreeOfParallelism,
ct).ConfigureAwait(false);
}
else
{
var writes = new ZarrStoreWrite[chunks.Count];
for (var i = 0; i < chunks.Count; i++)
{
ct.ThrowIfCancellationRequested();
var chunk = chunks[i];
writes[i] = new ZarrStoreWrite(chunk.Chunk.Key, chunk.DecodedBytes);
}
await _store.WriteManyAsync(writes, maxDegreeOfParallelism, ct).ConfigureAwait(false);
}
return;
}
var options = new ParallelOptions
{
MaxDegreeOfParallelism = maxDegreeOfParallelism,
CancellationToken = ct
};
await Parallel.ForEachAsync(chunks, options, async (chunk, token) =>
{
ValidateDecodedChunkWrite(chunk);
await WriteChunkDecodedAsync(
chunk.Chunk,
chunk.DecodedBytes,
allowBorrowedBuffer: false,
token).ConfigureAwait(false);
}).ConfigureAwait(false);
}
/// <summary>
/// Reads the encoded bytes for a non-sharded chunk directly from the store.
/// Returns null when the chunk key is absent, matching Zarr fill-value
/// semantics for sparse chunks.
/// </summary>
public async Task<byte[]?> ReadChunkEncodedAsync(
ZarrChunkRef chunk,
CancellationToken ct = default)
{
EnsureNonShardedEncodedChunkAccess();
ValidateChunkRef(chunk);
var key = BuildChunkContainingStoreKey(chunk.ChunkCoord);
return await _store.ReadAsync(key, ct).ConfigureAwait(false);
}
/// <summary>
/// Writes encoded bytes for a non-sharded chunk directly to the store.
/// Callers should only use this when the encoded bytes are compatible with
/// this array's metadata, chunk shape, dtype, and codec pipeline.
/// </summary>
public async Task WriteChunkEncodedAsync(
ZarrChunkRef chunk,
byte[] encodedData,
CancellationToken ct = default)
=> await WriteChunkEncodedAsync(
chunk,
encodedData.AsMemory(),
ct).ConfigureAwait(false);
/// <summary>
/// Writes encoded bytes for a non-sharded chunk directly to the store.
/// Pooled buffers may be passed as a sliced memory region; the memory is
/// consumed or copied before the returned task completes.
/// </summary>
public async Task WriteChunkEncodedAsync(
ZarrChunkRef chunk,
ReadOnlyMemory<byte> encodedData,
CancellationToken ct = default)
{
EnsureNonShardedEncodedChunkAccess();
ValidateChunkRef(chunk);
var key = BuildChunkContainingStoreKey(chunk.ChunkCoord);
await _store.WriteAsync(key, encodedData, ct).ConfigureAwait(false);
}
/// <summary>
/// Reads encoded bytes for non-sharded chunks in parallel, bounded by
/// <paramref name="maxDegreeOfParallelism"/>. Missing chunk keys are returned
/// as absent <see cref="ZarrEncodedChunk"/> values.
/// </summary>
public async Task<IReadOnlyList<ZarrEncodedChunk>> ReadChunksEncodedAsync(
IEnumerable<ZarrChunkRef> chunks,
int maxDegreeOfParallelism,
CancellationToken ct = default)
{
EnsureNonShardedEncodedChunkAccess();
ArgumentNullException.ThrowIfNull(chunks);
ValidateMaxDegreeOfParallelism(maxDegreeOfParallelism);
var indexedChunks = chunks
.Select((chunk, index) => (Chunk: chunk, Index: index))
.ToArray();
var results = new ZarrEncodedChunk[indexedChunks.Length];
var options = new ParallelOptions
{
MaxDegreeOfParallelism = maxDegreeOfParallelism,
CancellationToken = ct
};
await Parallel.ForEachAsync(indexedChunks, options, async (item, token) =>
{
var encoded = await ReadChunkEncodedAsync(item.Chunk, token).ConfigureAwait(false);
results[item.Index] = encoded is null
? ZarrEncodedChunk.Missing(item.Chunk)
: ZarrEncodedChunk.Present(item.Chunk, encoded);
}).ConfigureAwait(false);
return Array.AsReadOnly(results);
}
/// <summary>
/// Writes encoded bytes for non-sharded chunks in parallel, bounded by
/// <paramref name="maxDegreeOfParallelism"/>. Present chunks are written
/// directly with no read-modify-write. Absent chunks are skipped unless
/// <paramref name="deleteMissingChunks"/> is true.
/// </summary>
public async Task WriteChunksEncodedAsync(
IReadOnlyList<ZarrEncodedChunk> chunks,
int maxDegreeOfParallelism,
bool deleteMissingChunks = false,
CancellationToken ct = default)
{
EnsureNonShardedEncodedChunkAccess();
ArgumentNullException.ThrowIfNull(chunks);
ValidateMaxDegreeOfParallelism(maxDegreeOfParallelism);
var writes = new ZarrStoreWrite[chunks.Count];
var writeCount = 0;
var missingKeys = deleteMissingChunks ? new List<string>() : null;
var chunkCounts = _chunkCounts;
for (var i = 0; i < chunks.Count; i++)
{
ct.ThrowIfCancellationRequested();
var chunk = chunks[i];
ValidateChunkRef(chunk.Chunk, chunkCounts);
var key = GetChunkStoreKey(chunk.Chunk);
if (!chunk.IsPresent)
{
if (deleteMissingChunks)
missingKeys!.Add(key);
continue;
}
writes[writeCount++] = new ZarrStoreWrite(key, chunk.EncodedBytes);
}
if (writeCount != writes.Length)
Array.Resize(ref writes, writeCount);
await _store.WriteManyAsync(writes, maxDegreeOfParallelism, ct).ConfigureAwait(false);
if (missingKeys is not null && missingKeys.Count > 0)
await DeleteManyAsync(missingKeys, maxDegreeOfParallelism, ct).ConfigureAwait(false);
}
// -------------------------------------------------------------------------
// Chunk reading / writing
// -------------------------------------------------------------------------
private async Task<byte[]> ReadChunkAsync(
long[] chunkCoord,
ConcurrentDictionary<string, Task<byte[]?>>? shardCache,
CancellationToken ct)
{
// Sharded path — chunkCoord addresses an inner chunk, not a shard
if (Metadata.Sharding is not null)
return await ReadShardedChunkAsync(chunkCoord, shardCache!, ct).ConfigureAwait(false);
// Non-sharded path — one store key per chunk
return await ReadDirectChunkAsync(chunkCoord, ct).ConfigureAwait(false);
}
// -------------------------------------------------------------------------
// Non-sharded chunk read
// -------------------------------------------------------------------------
private async Task<byte[]> ReadDirectChunkAsync(long[] chunkCoord, CancellationToken ct)
{
var key = BuildChunkKey(chunkCoord);
await s_globalFetchSemaphore.WaitAsync(ct).ConfigureAwait(false);
byte[]? bytes;
try
{
bytes = await _store.ReadAsync(key, ct).ConfigureAwait(false);
}
finally
{
s_globalFetchSemaphore.Release();
}
if (bytes is null)
return BuildFillValueChunk();
var decoded = await _pipeline.DecodeAsync(bytes, ct).ConfigureAwait(false);
if (s_readDebugCount < 8)
{
Log($"[ZarrArray.ReadDirectChunkAsync] chunk={string.Join(",", chunkCoord)} encodedLen={bytes.Length} " +
$"encodedSample={SampleBytes(bytes)} decodedLen={decoded.Length} decodedSample={SampleBytes(decoded)} decodedU16={SampleU16(decoded)}");
s_readDebugCount++;
}
if (ShouldLogPlaneProbe(chunkCoord, s_readPlaneProbeLogged))
{
Log($"[ZarrArray.ReadDirectChunkAsync.Probe] chunk={string.Join(",", chunkCoord)} encodedLen={bytes.Length} " +
$"encodedSample={SampleBytes(bytes)} decodedLen={decoded.Length} decodedSample={SampleBytes(decoded)} decodedU16={SampleU16(decoded)}");
}
return PadOrValidateDecodedChunk(decoded, chunkCoord);
}
// -------------------------------------------------------------------------
// Sharded chunk read
// -------------------------------------------------------------------------
/// <summary>
/// Reads an inner chunk from within a shard file. The chunkCoord here is
/// the global inner-chunk coordinate (based on inner chunk shape). We compute
/// which shard it belongs to, fetch that shard (with caching), and extract
/// the inner chunk.
/// </summary>
private async Task<byte[]> ReadShardedChunkAsync(
long[] chunkCoord,
ConcurrentDictionary<string, Task<byte[]?>> shardCache,
CancellationToken ct)
{
var sharding = Metadata.Sharding!;
var rank = Metadata.Rank;
// Compute which shard this inner chunk belongs to, and its position within
var shardCoord = new long[rank];
var innerChunkCoord = new long[rank];
for (int d = 0; d < rank; d++)
{
var innersPerShard = sharding.InnerChunksPerShard[d];
var globalInnerIndex = chunkCoord[d];
shardCoord[d] = globalInnerIndex / innersPerShard;
innerChunkCoord[d] = globalInnerIndex % innersPerShard;
}
// Fetch the shard file, using the cache to avoid redundant reads
var shardKey = BuildChunkKey(shardCoord);
var shardBytes = await shardCache.GetOrAdd(
shardKey,
key => _store.ReadAsync(key, ct)
).ConfigureAwait(false);
if (shardBytes is null)
return BuildFillValueChunk();
// Extract the inner chunk from the shard
var innerChunkBytes = await ShardReader.ReadInnerChunkAsync(
shardBytes, innerChunkCoord, sharding, ct).ConfigureAwait(false);
if (innerChunkBytes is null)
return BuildFillValueChunk();
var padded = PadOrValidateDecodedChunk(innerChunkBytes, chunkCoord);
if (s_readDebugCount < 8)
{
Log($"[ZarrArray.ReadShardedChunkAsync] chunk={string.Join(",", chunkCoord)} innerLen={innerChunkBytes.Length} " +
$"innerSample={SampleBytes(innerChunkBytes)} paddedLen={padded.Length} paddedSample={SampleBytes(padded)} paddedU16={SampleU16(padded)}");
s_readDebugCount++;
}
return padded;
}
// -------------------------------------------------------------------------
// Decoded chunk validation / padding (shared by both paths)
// -------------------------------------------------------------------------
private byte[] PadOrValidateDecodedChunk(byte[] decoded, long[] chunkCoord)
{
var expectedBytes = _chunkElementCount * Metadata.DataType.ElementSize;
var actualBytes = decoded.Length;
if (actualBytes == expectedBytes)
return decoded;
// Truncated edge chunks: some implementations write only the valid portion
if (actualBytes < expectedBytes)
{
int elementSize = Metadata.DataType.ElementSize;
var padded = BuildFillValueChunk();
var truncatedShape = ComputeTruncatedChunkShape(chunkCoord);
var expectedTruncatedBytes = ComputeTotalElements(truncatedShape) * elementSize;
if (actualBytes == (int)expectedTruncatedBytes)
ExpandTruncatedChunk(decoded, truncatedShape, padded, _chunkShapeLong, elementSize);
else
Array.Copy(decoded, 0, padded, 0, decoded.Length); // unknown truncation — best effort
return padded;
}
throw new InvalidOperationException(
$"Decoded chunk at {string.Join(",", chunkCoord)} has {actualBytes} bytes, " +
$"expected {expectedBytes} bytes. Chunk shape: [{string.Join(", ", _chunkShapeLong)}], " +
$"element size: {Metadata.DataType.ElementSize} bytes.");
}
private async Task WriteChunkAsync(long[] chunkCoord, byte[] decodedData, CancellationToken ct)
{
if (s_writeDebugCount < 8)
{
Log($"[ZarrArray.WriteChunkAsync] chunk={string.Join(",", chunkCoord)} decodedLen={decodedData.Length} " +
$"decodedSample={SampleBytes(decodedData)} decodedU16={SampleU16(decodedData)}");
}
var encoded = await _pipeline.EncodeAsync(decodedData, ct).ConfigureAwait(false);
var key = BuildChunkKey(chunkCoord);
if (s_writeDebugCount < 8)
{
Log($"[ZarrArray.WriteChunkAsync] chunk={string.Join(",", chunkCoord)} encodedLen={encoded.Length} " +
$"encodedSample={SampleBytes(encoded)}");
s_writeDebugCount++;
}
await _store.WriteAsync(key, encoded, ct).ConfigureAwait(false);
}
private async Task WriteChunkRegionAsync(
long[] chunkCoord,
long[] regionStart,
long[] regionEnd,
long[] regionShape,
ReadOnlyMemory<byte> sourceData,
int elementSize,
CancellationToken ct)
{
// Write path doesn't use shard caching — pass null (non-sharded only for now)
var chunkData = await ReadChunkAsync(chunkCoord, shardCache: null, ct).ConfigureAwait(false);
var chunkOrigin = ComputeChunkOrigin(chunkCoord);
var clampedStart = ClampToChunk(regionStart, chunkOrigin, _chunkShapeLong, clampToStart: true);
var clampedEnd = ClampToChunk(regionEnd, chunkOrigin, _chunkShapeLong, clampToStart: false);
CopyNdRegion(
src: sourceData.Span,
srcOrigin: regionStart,
srcShape: regionShape,
dst: chunkData,
dstOrigin: chunkOrigin,
dstShape: _chunkShapeLong,
copyStart: clampedStart,
copyEnd: clampedEnd,
elementSize: elementSize);
if (s_writeDebugCount < 8)
{
Log($"[ZarrArray.WriteChunkRegionAsync] chunk={string.Join(",", chunkCoord)} srcShape={string.Join("x", regionShape)} " +
$"chunkOrigin={string.Join(",", chunkOrigin)} srcSample={SampleBytes(sourceData.Span)} chunkSample={SampleBytes(chunkData)} " +
$"srcU16={SampleU16(sourceData.Span)} chunkU16={SampleU16(chunkData)}");
}
if (ShouldLogPlaneProbe(chunkCoord, s_writePlaneProbeLogged))
{
Log($"[ZarrArray.WriteChunkRegionAsync.Probe] chunk={string.Join(",", chunkCoord)} srcShape={string.Join("x", regionShape)} " +
$"chunkOrigin={string.Join(",", chunkOrigin)} srcSample={SampleBytes(sourceData.Span)} chunkSample={SampleBytes(chunkData)} " +
$"srcU16={SampleU16(sourceData.Span)} chunkU16={SampleU16(chunkData)}");
}
await WriteChunkAsync(chunkCoord, chunkData, ct).ConfigureAwait(false);
}
// -------------------------------------------------------------------------
// Region/chunk copy — row-contiguous fast path
// -------------------------------------------------------------------------
/// <summary>
/// Copies the relevant portion of a decoded chunk into the output buffer
/// at the correct offset for the requested region.
///
/// Uses a row-contiguous fast path: the innermost (last) axis is copied
/// with a single Buffer.BlockCopy per row rather than element-by-element.
/// The outer axes are iterated with a reusable coordinate array to avoid
/// per-element heap allocations.
/// </summary>
private void CopyChunkRegionToOutput(
long[] chunkCoord,
byte[] chunkData,
long[] regionStart,
long[] regionEnd,
long[] regionShape,
byte[] outputBuffer,
int elementSize)
{
var chunkOrigin = ComputeChunkOrigin(chunkCoord);
var rank = Metadata.Rank;
var copyStart = new long[rank];
var copyEnd = new long[rank];
for (int d = 0; d < rank; d++)
{
copyStart[d] = Math.Max(regionStart[d], chunkOrigin[d]);
copyEnd[d] = Math.Min(regionEnd[d], chunkOrigin[d] + _chunkShapeLong[d]);
}
CopyNdRegion(
src: chunkData,
srcOrigin: chunkOrigin,
srcShape: _chunkShapeLong,
dst: outputBuffer,
dstOrigin: regionStart,
dstShape: regionShape,
copyStart: copyStart,
copyEnd: copyEnd,
elementSize: elementSize);
}
/// <summary>
/// General-purpose N-dimensional copy between two C-order flat buffers.
/// Copies the region [copyStart, copyEnd) from src into dst, where each
/// buffer has its own origin and shape.
///
/// The innermost axis is copied as a contiguous row with a single
/// Buffer.BlockCopy call. Outer axes are iterated with a single reusable
/// coordinate array — no per-element heap allocations.
/// </summary>
private static void CopyNdRegion(
ReadOnlySpan<byte> src,
long[] srcOrigin,
long[] srcShape,
Span<byte> dst,
long[] dstOrigin,
long[] dstShape,
long[] copyStart,
long[] copyEnd,
int elementSize)
{
var rank = srcShape.Length;
// How many elements to copy along the innermost axis per row
var innerCount = copyEnd[rank - 1] - copyStart[rank - 1];
var rowBytes = (int)(innerCount * elementSize);
if (rowBytes <= 0)
return;
// Pre-compute strides for src and dst (C-order: last axis has stride 1)
var srcStrides = ComputeStrides(srcShape);
var dstStrides = ComputeStrides(dstShape);
// For rank-1 arrays, just do one copy
if (rank == 1)
{
var srcByteOffset = (int)((copyStart[0] - srcOrigin[0]) * srcStrides[0] * elementSize);
var dstByteOffset = (int)((copyStart[0] - dstOrigin[0]) * dstStrides[0] * elementSize);
src.Slice(srcByteOffset, rowBytes).CopyTo(dst.Slice(dstByteOffset, rowBytes));
return;
}
// Iterate outer axes [0..rank-2], copy full inner row each time.
// Uses a single reusable coordinate array — no per-iteration allocations.
var outerRank = rank - 1;
var current = new long[outerRank];
for (int d = 0; d < outerRank; d++)
current[d] = copyStart[d];
while (true)
{
// Compute flat byte offsets for the start of this row in src and dst
long srcElement = (copyStart[rank - 1] - srcOrigin[rank - 1]);
long dstElement = (copyStart[rank - 1] - dstOrigin[rank - 1]);
for (int d = 0; d < outerRank; d++)
{
srcElement += (current[d] - srcOrigin[d]) * srcStrides[d];
dstElement += (current[d] - dstOrigin[d]) * dstStrides[d];
}
var srcByteOffset = (int)(srcElement * elementSize);
var dstByteOffset = (int)(dstElement * elementSize);
src.Slice(srcByteOffset, rowBytes).CopyTo(dst.Slice(dstByteOffset, rowBytes));
// Advance outer coordinates (last outer axis first, C order)
int axis = outerRank - 1;
while (axis >= 0)
{
current[axis]++;
if (current[axis] < copyEnd[axis])
break;
current[axis] = copyStart[axis];
axis--;
}
if (axis < 0)
break;
}
}
/// <summary>
/// Computes C-order strides for a given shape.
/// stride[d] = product of shape[d+1..rank-1]. stride[rank-1] = 1.
/// </summary>
private static long[] ComputeStrides(long[] shape)
{
var rank = shape.Length;
var strides = new long[rank];
strides[rank - 1] = 1;
for (int d = rank - 2; d >= 0; d--)
strides[d] = strides[d + 1] * shape[d + 1];
return strides;
}
// -------------------------------------------------------------------------
// Chunk enumeration and key building
// -------------------------------------------------------------------------
private IEnumerable<long[]> EnumerateChunkCoordinates(long[] regionStart, long[] regionEnd)
{
var rank = Metadata.Rank;
// Use inner chunk shape when sharded, outer chunk shape otherwise.
// _chunkShapeLong is already set to the effective shape in the constructor.
var chunkShape = _chunkShapeLong;
var firstChunk = new long[rank];
var lastChunkExclusive = new long[rank];
for (int d = 0; d < rank; d++)
{
firstChunk[d] = regionStart[d] / chunkShape[d];
// Last chunk that intersects the region, then +1 for exclusive end
lastChunkExclusive[d] = ((regionEnd[d] - 1) / chunkShape[d]) + 1;
}
return IterateNdCoordinates(firstChunk, lastChunkExclusive, rank);
}
private ZarrChunkRef BuildChunkRef(long[] chunkCoord)
{
var coord = (long[])chunkCoord.Clone();
var origin = ComputeChunkOrigin(coord);
var shape = ComputeTruncatedChunkShape(coord);
var key = BuildChunkContainingStoreKey(coord);
return new ZarrChunkRef(coord, origin, shape, key);
}
private string BuildChunkContainingStoreKey(long[] chunkCoord)
{
if (Metadata.Sharding is null)
return BuildChunkKey(chunkCoord);
var shardCoord = ComputeShardCoord(chunkCoord);
return BuildChunkKey(shardCoord);
}
private long[] ComputeShardCoord(long[] innerChunkCoord)
{
var sharding = Metadata.Sharding
?? throw new InvalidOperationException("Array is not sharded.");
var shardCoord = new long[Metadata.Rank];
for (int d = 0; d < Metadata.Rank; d++)
shardCoord[d] = innerChunkCoord[d] / sharding.InnerChunksPerShard[d];