1use std::ops::Range;
5
6use vortex_error::VortexResult;
7use vortex_error::vortex_err;
8
9use crate::ExecutionCtx;
10use crate::array::ArrayView;
11use crate::array::OperationsVTable;
12use crate::array::ProbeChildren;
13use crate::array::ProbeState;
14use crate::arrays::Primitive;
15use crate::arrays::patched::Patched;
16use crate::arrays::patched::PatchedArrayExt;
17use crate::arrays::patched::PatchedSlots;
18use crate::scalar::Scalar;
19
20const MAX_CACHED_INDICES: usize = 64;
22
23#[derive(Default)]
25pub struct PatchedProbeState {
26 last_lane: Option<CachedLane>,
27}
28
29struct CachedLane {
30 index: usize,
31 range: Range<usize>,
32 decoded_indices: Option<Vec<u16>>,
33}
34
35impl OperationsVTable<Patched> for Patched {
36 type ProbeState = PatchedProbeState;
37
38 fn probe_scalar(
39 state: &mut ProbeState<'_, Patched>,
40 index: usize,
41 ctx: &mut ExecutionCtx,
42 ) -> VortexResult<Scalar> {
43 let array = state.array();
44 if !state.is_valid(index, ctx)? {
45 return Ok(Scalar::null(array.dtype().clone()));
46 }
47
48 let physical_index = index + array.offset();
49 let chunk = physical_index / 1024;
50 #[expect(
51 clippy::cast_possible_truncation,
52 reason = "Index modulo 1024 fits in u16"
53 )]
54 let chunk_index = (physical_index % 1024) as u16;
55 let lane = physical_index % array.n_lanes();
56 let lane_index = chunk * array.n_lanes() + lane;
57 let (mut cache, mut children) = state.split();
58 let cached_range = cache
59 .as_ref()
60 .and_then(|cache| cache.last_lane.as_ref())
61 .filter(|cached| cached.index == lane_index)
62 .map(|cached| cached.range.clone());
63 let cache_hit = cached_range.is_some();
64 let range = if let Some(range) = cached_range {
65 range
66 } else {
67 let range = lane_range(&mut children, lane_index, ctx)?;
68 if let Some(cache) = cache.as_mut() {
69 cache.last_lane = Some(CachedLane {
70 index: lane_index,
71 range: range.clone(),
72 decoded_indices: None,
73 });
74 }
75 range
76 };
77
78 let patch_position =
79 patch_position(&mut children, cache, cache_hit, range, chunk_index, ctx)?;
80
81 if let Some(position) = patch_position {
82 return children
83 .slot(PatchedSlots::PATCH_VALUES)?
84 .ok_or_else(|| vortex_err!("Patched values slot is missing"))?
85 .execute_scalar(position, ctx)?
86 .cast(array.dtype());
87 }
88
89 children
90 .slot(PatchedSlots::INNER)?
91 .ok_or_else(|| vortex_err!("Patched inner slot is missing"))?
92 .execute_scalar(index, ctx)
93 }
94
95 fn scalar_at(
96 array: ArrayView<'_, Patched>,
97 index: usize,
98 ctx: &mut ExecutionCtx,
99 ) -> VortexResult<Scalar> {
100 Self::probe_scalar(&mut ProbeState::once(array), index, ctx)
101 }
102}
103
104fn patch_position(
105 children: &mut ProbeChildren<'_, '_, Patched>,
106 cache: Option<&mut PatchedProbeState>,
107 cache_hit: bool,
108 range: Range<usize>,
109 chunk_index: u16,
110 ctx: &mut ExecutionCtx,
111) -> VortexResult<Option<usize>> {
112 let mut indices = children
113 .slot(PatchedSlots::PATCH_INDICES)?
114 .ok_or_else(|| vortex_err!("Patched indices slot is missing"))?;
115 if let Some(primitive) = indices.array().as_opt::<Primitive>() {
116 return Ok(primitive
117 .as_slice::<u16>()
118 .get(range.clone())
119 .ok_or_else(|| vortex_err!("Patched lane range is out of bounds"))?
120 .iter()
121 .position(|&value| value == chunk_index)
122 .map(|position| range.start + position));
123 }
124 if range.start > range.end || range.end > indices.array().len() {
125 return Err(vortex_err!("Patched lane range is out of bounds"));
126 }
127
128 if let Some(decoded) = cache
129 .as_ref()
130 .and_then(|cache| cache.last_lane.as_ref())
131 .and_then(|lane| lane.decoded_indices.as_ref())
132 {
133 return Ok(decoded
134 .iter()
135 .position(|&value| value == chunk_index)
136 .map(|position| range.start + position));
137 }
138
139 if cache_hit
141 && range.len() <= MAX_CACHED_INDICES
142 && let Some(cache) = cache
143 {
144 let decoded = range
145 .clone()
146 .map(|position| patch_index_at(&mut indices, position, ctx))
147 .collect::<VortexResult<Vec<_>>>()?;
148 let found = decoded
149 .iter()
150 .position(|&value| value == chunk_index)
151 .map(|position| range.start + position);
152 if let Some(lane) = &mut cache.last_lane {
153 lane.decoded_indices = Some(decoded);
154 }
155 return Ok(found);
156 }
157
158 for position in range {
159 if patch_index_at(&mut indices, position, ctx)? == chunk_index {
160 return Ok(Some(position));
161 }
162 }
163 Ok(None)
164}
165
166fn patch_index_at(
167 indices: &mut crate::array::ArrayProbe<'_>,
168 position: usize,
169 ctx: &mut ExecutionCtx,
170) -> VortexResult<u16> {
171 indices
172 .execute_scalar(position, ctx)?
173 .as_primitive()
174 .as_::<u16>()
175 .ok_or_else(|| vortex_err!("Patched index is not a u16"))
176}
177
178fn lane_range(
179 children: &mut ProbeChildren<'_, '_, Patched>,
180 lane_index: usize,
181 ctx: &mut ExecutionCtx,
182) -> VortexResult<Range<usize>> {
183 let mut offsets = children
184 .slot(PatchedSlots::LANE_OFFSETS)?
185 .ok_or_else(|| vortex_err!("Patched lane offsets slot is missing"))?;
186 if let Some(primitive) = offsets.array().as_opt::<Primitive>() {
187 let values = primitive.as_slice::<u32>();
188 let start = *values
189 .get(lane_index)
190 .ok_or_else(|| vortex_err!("Patched lane start is out of bounds"))?;
191 let end = *values
192 .get(lane_index + 1)
193 .ok_or_else(|| vortex_err!("Patched lane end is out of bounds"))?;
194 let start = usize::try_from(start)
195 .map_err(|_| vortex_err!("Patched lane start does not fit usize"))?;
196 let end =
197 usize::try_from(end).map_err(|_| vortex_err!("Patched lane end does not fit usize"))?;
198 return Ok(start..end);
199 }
200
201 let start = offsets
202 .execute_scalar(lane_index, ctx)?
203 .as_primitive()
204 .as_::<usize>()
205 .ok_or_else(|| vortex_err!("Patched lane start is not an offset"))?;
206 let end = offsets
207 .execute_scalar(lane_index + 1, ctx)?
208 .as_primitive()
209 .as_::<usize>()
210 .ok_or_else(|| vortex_err!("Patched lane end is not an offset"))?;
211 Ok(start..end)
212}
213
214#[cfg(test)]
215mod tests {
216 use std::ops::Range;
217 use std::sync::LazyLock;
218
219 use rstest::rstest;
220 use vortex_buffer::buffer;
221 use vortex_error::VortexExpect;
222 use vortex_error::VortexResult;
223 use vortex_session::VortexSession;
224
225 use crate::ArrayRef;
226 use crate::IntoArray;
227 use crate::VortexSessionExecute;
228 use crate::arrays::ChunkedArray;
229 use crate::arrays::Patched;
230 use crate::arrays::PrimitiveArray;
231 use crate::arrays::patched::PatchedArrayExt;
232 use crate::arrays::patched::PatchedArraySlotsExt;
233 use crate::arrays::patched::PatchedSlots;
234 use crate::dtype::Nullability;
235 use crate::optimizer::ArrayOptimizer;
236 use crate::patches::Patches;
237 use crate::scalar::Scalar;
238
239 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
240
241 #[test]
242 fn test_simple() {
243 let mut ctx = SESSION.create_execution_ctx();
244 let values = buffer![0u16; 1024].into_array();
245 let patches = Patches::new(
246 1024,
247 0,
248 buffer![1u32, 2, 3].into_array(),
249 buffer![1u16; 3].into_array(),
250 None,
251 &mut ctx,
252 )
253 .unwrap();
254
255 let mut ctx = SESSION.create_execution_ctx();
256
257 let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
258 .unwrap()
259 .into_array();
260
261 assert_eq!(
262 array
263 .execute_scalar(0, &mut SESSION.create_execution_ctx())
264 .unwrap(),
265 Scalar::primitive(0u16, Nullability::NonNullable)
266 );
267 assert_eq!(
268 array
269 .execute_scalar(1, &mut SESSION.create_execution_ctx())
270 .unwrap(),
271 Scalar::primitive(1u16, Nullability::NonNullable)
272 );
273 assert_eq!(
274 array
275 .execute_scalar(2, &mut SESSION.create_execution_ctx())
276 .unwrap(),
277 Scalar::primitive(1u16, Nullability::NonNullable)
278 );
279 assert_eq!(
280 array
281 .execute_scalar(3, &mut SESSION.create_execution_ctx())
282 .unwrap(),
283 Scalar::primitive(1u16, Nullability::NonNullable)
284 );
285 }
286
287 #[test]
288 fn test_multi_chunk() {
289 let mut ctx = SESSION.create_execution_ctx();
290 let values = buffer![0u16; 4096].into_array();
291 let patches = Patches::new(
292 4096,
293 0,
294 buffer![1u32, 2, 3].into_array(),
295 buffer![1u16; 3].into_array(),
296 None,
297 &mut ctx,
298 )
299 .unwrap();
300
301 let mut ctx = SESSION.create_execution_ctx();
302
303 let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
304 .unwrap()
305 .into_array();
306
307 for index in 0..array.len() {
308 let value = array
309 .execute_scalar(index, &mut SESSION.create_execution_ctx())
310 .unwrap();
311
312 if [1, 2, 3].contains(&index) {
313 assert_eq!(value, 1u16.into());
314 } else {
315 assert_eq!(value, 0u16.into());
316 }
317 }
318 }
319
320 #[test]
321 fn test_multi_chunk_sliced() {
322 let mut ctx = SESSION.create_execution_ctx();
323 let values = buffer![0u16; 4096].into_array();
324 let patches = Patches::new(
325 4096,
326 0,
327 buffer![1u32, 2, 3].into_array(),
328 buffer![1u16; 3].into_array(),
329 None,
330 &mut ctx,
331 )
332 .unwrap();
333
334 let mut ctx = SESSION.create_execution_ctx();
335
336 let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
337 .unwrap()
338 .into_array()
339 .slice(3..4096)
340 .unwrap()
341 .optimize_ctx(&SESSION)
342 .unwrap();
343
344 assert!(array.is::<Patched>());
345
346 assert_eq!(
347 array
348 .execute_scalar(0, &mut SESSION.create_execution_ctx())
349 .unwrap(),
350 1u16.into()
351 );
352 for index in 1..array.len() {
353 assert_eq!(
354 array
355 .execute_scalar(index, &mut SESSION.create_execution_ctx())
356 .unwrap(),
357 0u16.into()
358 );
359 }
360 }
361
362 fn probe_fixture() -> VortexResult<ArrayRef> {
363 let mut ctx = SESSION.create_execution_ctx();
364 let values = PrimitiveArray::from_option_iter(
365 (0..3072).map(|index| (![32, 65, 1024].contains(&index)).then_some(index as u32)),
366 )
367 .into_array();
368 let patches = Patches::new(
369 3072,
370 0,
371 buffer![31u32, 32, 1024, 1056, 2048].into_array(),
372 buffer![9001u32, 9002, 9003, 9004, 9005].into_array(),
373 None,
374 &mut ctx,
375 )?;
376 Ok(Patched::from_array_and_patches(values, &patches, &mut ctx)?.into_array())
377 }
378
379 fn expected(index: usize) -> Option<u32> {
380 match index {
381 32 | 65 | 1024 => None,
382 31 => Some(9001),
383 1056 => Some(9004),
384 2048 => Some(9005),
385 _ => Some(u32::try_from(index).vortex_expect("fixture index fits u32")),
386 }
387 }
388
389 fn check_probe(
390 array: &ArrayRef,
391 start: usize,
392 ctx: &mut crate::ExecutionCtx,
393 ) -> VortexResult<()> {
394 let mut repeated = array.repeated_probe();
395 for absolute in [
396 0, 31, 32, 33, 63, 64, 65, 1023, 1024, 1025, 1056, 2048, 2099, 3071, 31, 1056, 32,
397 ] {
398 if absolute < start || absolute >= start + array.len() {
399 continue;
400 }
401 let index = absolute - start;
402 let expected = Scalar::from(expected(absolute));
403 assert_eq!(array.execute_scalar(index, ctx)?, expected);
404 assert_eq!(repeated.execute_scalar(index, ctx)?, expected);
405 assert_eq!(repeated.execute_is_valid(index, ctx)?, !expected.is_null());
406 }
407 Ok(())
408 }
409
410 #[test]
411 fn probe_nullable_patches_and_slices() -> VortexResult<()> {
412 let array = probe_fixture()?;
413 let mut ctx = SESSION.create_execution_ctx();
414 check_probe(&array, 0, &mut ctx)?;
415 check_probe(&array.slice(30..1100)?, 30, &mut ctx)?;
416 check_probe(&array.slice(1020..2100)?, 1020, &mut ctx)
417 }
418
419 fn chunked_child(child: &ArrayRef) -> VortexResult<ArrayRef> {
420 let middle = child.len() / 2;
421 Ok(ChunkedArray::try_new(
422 [child.slice(0..middle)?, child.slice(middle..child.len())?],
423 child.dtype().clone(),
424 )?
425 .into_array())
426 }
427
428 fn with_chunked_children(array: &ArrayRef) -> VortexResult<ArrayRef> {
429 let patched = array.as_opt::<Patched>().expect("Patched fixture");
430 let slots = PatchedSlots {
431 inner: patched.inner().clone(),
432 lane_offsets: chunked_child(patched.lane_offsets())?,
433 patch_indices: chunked_child(patched.patch_indices())?,
434 patch_values: patched.patch_values().clone(),
435 };
436
437 unsafe { array.clone().with_slots(slots.into_slots()) }
439 }
440
441 #[test]
442 fn probe_chunked_offsets_and_indices() -> VortexResult<()> {
443 let array = with_chunked_children(&probe_fixture()?)?;
444 let mut ctx = SESSION.create_execution_ctx();
445 check_probe(&array, 0, &mut ctx)?;
446 check_probe(&array.slice(30..1100)?, 30, &mut ctx)
447 }
448
449 #[rstest]
453 #[case::primitive_children(false, None)]
454 #[case::chunked_children(true, None)]
455 #[case::primitive_children_sliced(false, Some(1030..2100))]
456 #[case::chunked_children_sliced(true, Some(1030..2100))]
457 fn probe_revisits_one_lane(
458 #[case] chunked: bool,
459 #[case] slice: Option<Range<usize>>,
460 ) -> VortexResult<()> {
461 let mut array = probe_fixture()?;
462 if chunked {
463 array = with_chunked_children(&array)?;
464 }
465
466 let start = slice.as_ref().map_or(0, |range| range.start);
467 if let Some(range) = slice {
468 array = array.slice(range)?.optimize_ctx(&SESSION)?;
469 let patched = array
470 .as_opt::<Patched>()
471 .vortex_expect("the slice reduces to a Patched array");
472 assert_eq!(patched.offset(), start % 1024);
473 }
474
475 let mut ctx = SESSION.create_execution_ctx();
476 let expected = array
477 .clone()
478 .execute::<PrimitiveArray>(&mut ctx)?
479 .into_array();
480 let mut probe = array.repeated_probe();
481
482 for absolute in [1088, 1056, 1024, 1056, 1120, 1056, 1088, 1024] {
485 if absolute < start {
486 continue;
487 }
488
489 let index = absolute - start;
490 assert_eq!(
491 probe.execute_scalar(index, &mut ctx)?,
492 expected.execute_scalar(index, &mut ctx)?,
493 "row {absolute}"
494 );
495 }
496
497 Ok(())
498 }
499}