-
Notifications
You must be signed in to change notification settings - Fork 413
/
Copy pathquery.rs
2708 lines (2378 loc) · 104 KB
/
query.rs
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
use std::{
collections::BTreeSet,
sync::{
atomic::{AtomicU64, Ordering},
OnceLock,
},
};
use arrow2::{
array::{
Array as ArrowArray, BooleanArray as ArrowBooleanArray,
PrimitiveArray as ArrowPrimitiveArray,
},
chunk::Chunk as ArrowChunk,
datatypes::Schema as ArrowSchema,
Either,
};
use itertools::Itertools;
use nohash_hasher::{IntMap, IntSet};
use re_chunk::{
Chunk, ComponentName, EntityPath, RangeQuery, RowId, TimeInt, Timeline, UnitChunkShared,
};
use re_chunk_store::{
ColumnDescriptor, ColumnSelector, ComponentColumnDescriptor, ComponentColumnSelector, Index,
IndexValue, QueryExpression, SparseFillStrategy, TimeColumnDescriptor, TimeColumnSelector,
};
use re_log_types::ResolvedTimeRange;
use re_types_core::components::ClearIsRecursive;
use crate::{QueryEngine, RecordBatch};
// ---
// TODO(cmc): (no specific order) (should we make issues for these?)
// * [x] basic thing working
// * [x] custom selection
// * [x] support for overlaps (slow)
// * [x] pagination (any solution, even a slow one)
// * [x] pov support
// * [x] latestat sparse-filling
// * [x] sampling support
// * [x] clears
// * [x] pagination (fast)
// * [x] take kernel duplicates all memory
// * [x] dedupe-latest without allocs/copies
// * [ ] allocate null arrays once
// * [ ] overlaps (less dumb)
// * [ ] selector-based `filtered_index`
// * [ ] configurable cache bypass
/// A handle to a dataframe query, ready to be executed.
///
/// Cheaply created via [`QueryEngine::query`].
///
/// See [`QueryHandle::next_row`] or [`QueryHandle::into_iter`].
pub struct QueryHandle<'a> {
/// Handle to the [`QueryEngine`].
pub(crate) engine: &'a QueryEngine<'a>,
/// The original query expression used to instantiate this handle.
pub(crate) query: QueryExpression,
/// Internal private state. Lazily computed.
///
/// It is important that handles stay cheap to create.
state: OnceLock<QueryHandleState>,
}
/// Internal private state. Lazily computed.
struct QueryHandleState {
/// Describes the columns that make up this view.
///
/// See [`QueryExpression::view_contents`].
view_contents: Vec<ColumnDescriptor>,
/// Describes the columns specifically selected to be returned from this view.
///
/// All returned rows will have an Arrow schema that matches this selection.
///
/// Columns that do not yield any data will still be present in the results, filled with null values.
///
/// The extra `usize` is the index in [`QueryHandleState::view_contents`] that this selection
/// points to.
///
/// See also [`QueryHandleState::arrow_schema`].
selected_contents: Vec<(usize, ColumnDescriptor)>,
/// This keeps track of the static data associated with each entry in `selected_contents`, if any.
///
/// This is queried only once during init, and will override all cells that follow.
///
/// `selected_contents`: [`QueryHandleState::selected_contents`]
selected_static_values: Vec<Option<UnitChunkShared>>,
/// The actual index filter in use, since the user-specified one is optional.
///
/// This just defaults to `Index::default()` if the user hasn't specified any: the actual
/// value is irrelevant since this means we are only concerned with static data anyway.
filtered_index: Index,
/// The Arrow schema that corresponds to the `selected_contents`.
///
/// All returned rows will have this schema.
arrow_schema: ArrowSchema,
/// All the [`Chunk`]s included in the view contents.
///
/// These are already sorted, densified, vertically sliced, and [latest-deduped] according
/// to the query.
///
/// The atomic counter is used as a cursor which keeps track of our current position within
/// each individual chunk.
/// Because chunks are allowed to overlap, we might need to rebound between two or more chunks
/// during our iteration.
///
/// This vector's entries correspond to those in [`QueryHandleState::view_contents`].
/// Note: time and column entries don't have chunks -- inner vectors will be empty.
///
/// [latest-deduped]: [`Chunk::deduped_latest_on_index`]
//
// NOTE: Reminder: we have to query everything in the _view_, irrelevant of the current selection.
view_chunks: Vec<Vec<(AtomicU64, Chunk)>>,
/// Tracks the current row index: the position of the iterator. For [`QueryHandle::next_row`].
///
/// This represents the number of rows that the caller has iterated on: it is completely
/// unrelated to the cursors used to track the current position in each individual chunk.
///
/// The corresponding index value can be obtained using `unique_index_values[cur_row]`.
///
/// `unique_index_values[cur_row]`: [`QueryHandleState::unique_index_values`]
cur_row: AtomicU64,
/// All unique index values that can possibly be returned by this query.
///
/// Guaranteed ascendingly sorted and deduped.
///
/// See also [`QueryHandleState::cur_row`].
unique_index_values: Vec<IndexValue>,
}
impl<'a> QueryHandle<'a> {
pub(crate) fn new(engine: &'a QueryEngine<'a>, query: QueryExpression) -> Self {
Self {
engine,
query,
state: Default::default(),
}
}
}
impl QueryHandle<'_> {
/// Lazily initialize internal private state.
///
/// It is important that query handles stay cheap to create.
fn init(&self) -> &QueryHandleState {
self.state.get_or_init(|| self.init_())
}
// NOTE: This is split in its own method otherwise it completely breaks `rustfmt`.
fn init_(&self) -> QueryHandleState {
re_tracing::profile_scope!("init");
let store = self.engine.store.read();
// The timeline doesn't matter if we're running in static-only mode.
let filtered_index = self.query.filtered_index.unwrap_or_default();
// 1. Compute the schema for the query.
let view_contents = store.schema_for_query(&self.query);
// 2. Compute the schema of the selected contents.
//
// The caller might have selected columns that do not exist in the view: they should
// still appear in the results.
let selected_contents: Vec<(_, _)> = if let Some(selection) = self.query.selection.as_ref()
{
self.compute_user_selection(&view_contents, selection)
} else {
view_contents.clone().into_iter().enumerate().collect()
};
// 3. Compute the Arrow schema of the selected components.
//
// Every result returned using this `QueryHandle` will match this schema exactly.
let arrow_schema = ArrowSchema {
fields: selected_contents
.iter()
.map(|(_, descr)| descr.to_arrow_field())
.collect_vec(),
metadata: Default::default(),
};
// 4. Perform the query and keep track of all the relevant chunks.
let query = {
let index_range = if self.query.filtered_index.is_none() {
ResolvedTimeRange::EMPTY // static-only
} else if let Some(using_index_values) = self.query.using_index_values.as_ref() {
using_index_values
.first()
.and_then(|start| using_index_values.last().map(|end| (start, end)))
.map_or(ResolvedTimeRange::EMPTY, |(start, end)| {
ResolvedTimeRange::new(*start, *end)
})
} else {
self.query
.filtered_index_range
.unwrap_or(ResolvedTimeRange::EVERYTHING)
};
RangeQuery::new(filtered_index, index_range)
.keep_extra_timelines(true) // we want all the timelines we can get!
.keep_extra_components(false)
};
let (view_pov_chunks_idx, mut view_chunks) = self.fetch_view_chunks(&query, &view_contents);
// 5. Collect all relevant clear chunks and update the view accordingly.
//
// We'll turn the clears into actual empty arrays of the expected component type.
{
re_tracing::profile_scope!("clear_chunks");
let clear_chunks = self.fetch_clear_chunks(&query, &view_contents);
for (view_idx, chunks) in view_chunks.iter_mut().enumerate() {
let Some(ColumnDescriptor::Component(descr)) = view_contents.get(view_idx) else {
continue;
};
// NOTE: It would be tempting to concatenate all these individual clear chunks into one
// single big chunk, but that'd be a mistake: 1) it's costly to do so but more
// importantly 2) that would lead to likely very large chunk overlap, which is very bad
// for business.
if let Some(clear_chunks) = clear_chunks.get(&descr.entity_path) {
chunks.extend(clear_chunks.iter().map(|chunk| {
let child_datatype = match &descr.store_datatype {
arrow2::datatypes::DataType::List(field)
| arrow2::datatypes::DataType::LargeList(field) => {
field.data_type().clone()
}
arrow2::datatypes::DataType::Dictionary(_, datatype, _) => {
(**datatype).clone()
}
datatype => datatype.clone(),
};
let mut chunk = chunk.clone();
// Only way this could fail is if the number of rows did not match.
#[allow(clippy::unwrap_used)]
chunk
.add_component(
descr.component_name,
re_chunk::util::new_list_array_of_empties(
child_datatype,
chunk.num_rows(),
),
)
.unwrap();
(AtomicU64::new(0), chunk)
}));
// The chunks were sorted that way before, and it needs to stay that way after.
chunks.sort_by_key(|(_cursor, chunk)| {
// NOTE: The chunk has been densified already: its global time range is the same as
// the time range for the specific component of interest.
chunk
.timelines()
.get(&filtered_index)
.map(|time_column| time_column.time_range())
.map_or(TimeInt::STATIC, |time_range| time_range.min())
});
}
}
}
// 6. Collect all unique index values.
//
// Used to achieve ~O(log(n)) pagination.
let unique_index_values = if self.query.filtered_index.is_none() {
vec![TimeInt::STATIC]
} else if let Some(using_index_values) = self.query.using_index_values.as_ref() {
using_index_values
.iter()
.filter(|index_value| !index_value.is_static())
.copied()
.collect_vec()
} else {
re_tracing::profile_scope!("index_values");
let mut view_chunks = view_chunks.iter();
let view_chunks = if let Some(view_pov_chunks_idx) = view_pov_chunks_idx {
Either::Left(view_chunks.nth(view_pov_chunks_idx).into_iter())
} else {
Either::Right(view_chunks)
};
let mut all_unique_index_values: BTreeSet<TimeInt> = view_chunks
.flat_map(|chunks| {
chunks.iter().filter_map(|(_cursor, chunk)| {
chunk
.timelines()
.get(&filtered_index)
.map(|time_column| time_column.times())
})
})
.flatten()
.collect();
if let Some(filtered_index_values) = self.query.filtered_index_values.as_ref() {
all_unique_index_values.retain(|time| filtered_index_values.contains(time));
}
all_unique_index_values
.into_iter()
.filter(|index_value| !index_value.is_static())
.collect_vec()
};
let selected_static_values = {
re_tracing::profile_scope!("static_values");
selected_contents
.iter()
.map(|(_view_idx, descr)| match descr {
ColumnDescriptor::Time(_) => None,
ColumnDescriptor::Component(descr) => {
let query =
re_chunk::LatestAtQuery::new(Timeline::default(), TimeInt::STATIC);
let results = self.engine.cache.latest_at(
&query,
&descr.entity_path,
[descr.component_name],
);
results.components.get(&descr.component_name).cloned()
}
})
.collect_vec()
};
QueryHandleState {
view_contents,
selected_contents,
selected_static_values,
filtered_index,
arrow_schema,
view_chunks,
cur_row: AtomicU64::new(0),
unique_index_values,
}
}
#[allow(clippy::unused_self)]
fn compute_user_selection(
&self,
view_contents: &[ColumnDescriptor],
selection: &[ColumnSelector],
) -> Vec<(usize, ColumnDescriptor)> {
selection
.iter()
.map(|column| {
match column {
ColumnSelector::Time(selected_column) => {
let TimeColumnSelector {
timeline: selected_timeline,
} = selected_column;
view_contents
.iter()
.enumerate()
.filter_map(|(idx, view_column)| match view_column {
ColumnDescriptor::Time(view_descr) => Some((idx, view_descr)),
ColumnDescriptor::Component(_) => None,
})
.find(|(_idx, view_descr)| {
*view_descr.timeline.name() == *selected_timeline
})
.map_or_else(
|| {
(
usize::MAX,
ColumnDescriptor::Time(TimeColumnDescriptor {
// TODO(cmc): I picked a sequence here because I have to pick something.
// It doesn't matter, only the name will remain in the Arrow schema anyhow.
timeline: Timeline::new_sequence(*selected_timeline),
datatype: arrow2::datatypes::DataType::Null,
}),
)
},
|(idx, view_descr)| {
(idx, ColumnDescriptor::Time(view_descr.clone()))
},
)
}
ColumnSelector::Component(selected_column) => {
let ComponentColumnSelector {
entity_path: selected_entity_path,
component_name: selected_component_name,
} = selected_column;
view_contents
.iter()
.enumerate()
.filter_map(|(idx, view_column)| match view_column {
ColumnDescriptor::Component(view_descr) => Some((idx, view_descr)),
ColumnDescriptor::Time(_) => None,
})
.find(|(_idx, view_descr)| {
view_descr.entity_path == *selected_entity_path
&& view_descr.component_name.matches(selected_component_name)
})
.map_or_else(
|| {
(
usize::MAX,
ColumnDescriptor::Component(ComponentColumnDescriptor {
entity_path: selected_entity_path.clone(),
archetype_name: None,
archetype_field_name: None,
component_name: ComponentName::from(
selected_component_name.clone(),
),
store_datatype: arrow2::datatypes::DataType::Null,
is_static: false,
is_indicator: false,
is_tombstone: false,
is_semantically_empty: false,
}),
)
},
|(idx, view_descr)| {
(idx, ColumnDescriptor::Component(view_descr.clone()))
},
)
}
}
})
.collect_vec()
}
fn fetch_view_chunks(
&self,
query: &RangeQuery,
view_contents: &[ColumnDescriptor],
) -> (Option<usize>, Vec<Vec<(AtomicU64, Chunk)>>) {
let mut view_pov_chunks_idx = self.query.filtered_is_not_null.as_ref().map(|_| usize::MAX);
let view_chunks = view_contents
.iter()
.enumerate()
.map(|(idx, selected_column)| match selected_column {
ColumnDescriptor::Time(_) => Vec::new(),
ColumnDescriptor::Component(column) => {
let chunks = self
.fetch_chunks(query, &column.entity_path, [column.component_name])
.unwrap_or_default();
if let Some(pov) = self.query.filtered_is_not_null.as_ref() {
if pov.entity_path == column.entity_path
&& column.component_name.matches(&pov.component_name)
{
view_pov_chunks_idx = Some(idx);
}
}
chunks
}
})
.collect();
(view_pov_chunks_idx, view_chunks)
}
/// Returns all potentially relevant clear [`Chunk`]s for each unique entity path in the view contents.
///
/// These chunks take recursive clear semantics into account and are guaranteed to be properly densified.
/// The component data is stripped out, only the indices are left.
fn fetch_clear_chunks(
&self,
query: &RangeQuery,
view_contents: &[ColumnDescriptor],
) -> IntMap<EntityPath, Vec<Chunk>> {
/// Returns all the ancestors of an [`EntityPath`].
///
/// Doesn't return `entity_path` itself.
fn entity_path_ancestors(entity_path: &EntityPath) -> impl Iterator<Item = EntityPath> {
std::iter::from_fn({
let mut entity_path = entity_path.parent();
move || {
let yielded = entity_path.clone()?;
entity_path = yielded.parent();
Some(yielded)
}
})
}
/// Given a [`Chunk`] containing a [`ClearIsRecursive`] column, returns a filtered version
/// of that chunk where only rows with `ClearIsRecursive=true` are left.
///
/// Returns `None` if the chunk either doesn't contain a `ClearIsRecursive` column or if
/// the end result is an empty chunk.
fn chunk_filter_recursive_only(chunk: &Chunk) -> Option<Chunk> {
let list_array = chunk.components().get(&ClearIsRecursive::name())?;
let values = list_array
.values()
.as_any()
.downcast_ref::<ArrowBooleanArray>()?;
let indices = ArrowPrimitiveArray::from_vec(
values
.iter()
.enumerate()
.filter_map(|(index, is_recursive)| {
(is_recursive == Some(true)).then_some(index as i32)
})
.collect_vec(),
);
let chunk = chunk.taken(&indices);
(!chunk.is_empty()).then_some(chunk)
}
use re_types_core::Loggable as _;
let component_names = [re_types_core::components::ClearIsRecursive::name()];
// All unique entity paths present in the view contents.
let entity_paths: IntSet<EntityPath> = view_contents
.iter()
.filter_map(|col| match col {
ColumnDescriptor::Component(descr) => Some(descr.entity_path.clone()),
ColumnDescriptor::Time(_) => None,
})
.collect();
entity_paths
.iter()
.filter_map(|entity_path| {
// For the entity itself, any chunk that contains clear data is relevant, recursive or not.
// Just fetch everything we find.
let flat_chunks = self
.fetch_chunks(query, entity_path, component_names)
.map(|chunks| {
chunks
.into_iter()
.map(|(_cursor, chunk)| chunk)
.collect_vec()
})
.unwrap_or_default();
let recursive_chunks =
entity_path_ancestors(entity_path).flat_map(|ancestor_path| {
self.fetch_chunks(query, &ancestor_path, component_names)
.into_iter() // option
.flat_map(|chunks| chunks.into_iter().map(|(_cursor, chunk)| chunk))
// NOTE: Ancestors' chunks are only relevant for the rows where `ClearIsRecursive=true`.
.filter_map(|chunk| chunk_filter_recursive_only(&chunk))
});
let chunks = flat_chunks
.into_iter()
.chain(recursive_chunks)
// The component data is irrelevant.
// We do not expose the actual tombstones to end-users, only their _effect_.
.map(|chunk| chunk.components_removed())
.collect_vec();
(!chunks.is_empty()).then(|| (entity_path.clone(), chunks))
})
.collect()
}
fn fetch_chunks<const N: usize>(
&self,
query: &RangeQuery,
entity_path: &EntityPath,
component_names: [ComponentName; N],
) -> Option<Vec<(AtomicU64, Chunk)>> {
// NOTE: Keep in mind that the range APIs natively make sure that we will
// either get a bunch of relevant _static_ chunks, or a bunch of relevant
// _temporal_ chunks, but never both.
//
// TODO(cmc): Going through the cache is very useful in a Viewer context, but
// not so much in an SDK context. Make it configurable.
let results = self.engine.cache.range(query, entity_path, component_names);
debug_assert!(
results.components.len() <= 1,
"cannot possibly get more than one component with this query"
);
results
.components
.into_iter()
.next()
.map(|(_component_name, chunks)| {
chunks
.into_iter()
.map(|chunk| {
// NOTE: Keep in mind that the range APIs would have already taken care
// of A) sorting the chunk on the `filtered_index` (and row-id) and
// B) densifying it according to the current `component_name`.
// Both of these are mandatory requirements for the deduplication logic to
// do what we want: keep the latest known value for `component_name` at all
// remaining unique index values all while taking row-id ordering semantics
// into account.
debug_assert!(
if let Some(index) = self.query.filtered_index.as_ref() {
chunk.is_timeline_sorted(index)
} else {
chunk.is_sorted()
},
"the query cache should have already taken care of sorting (and densifying!) the chunk",
);
// TODO(cmc): That'd be more elegant, but right now there is no way to
// avoid allocations and copies when using Arrow's `ListArray`.
//
// let chunk = chunk.deduped_latest_on_index(&query.timeline);
(AtomicU64::default(), chunk)
})
.collect_vec()
})
}
/// The query used to instantiate this handle.
#[inline]
pub fn query(&self) -> &QueryExpression {
&self.query
}
/// Describes the columns that make up this view.
///
/// See [`QueryExpression::view_contents`].
#[inline]
pub fn view_contents(&self) -> &[ColumnDescriptor] {
&self.init().view_contents
}
/// Describes the columns that make up this selection.
///
/// The extra `usize` is the index in [`Self::view_contents`] that this selection points to.
///
/// See [`QueryExpression::selection`].
#[inline]
pub fn selected_contents(&self) -> &[(usize, ColumnDescriptor)] {
&self.init().selected_contents
}
/// All results returned by this handle will strictly follow this Arrow schema.
///
/// Columns that do not yield any data will still be present in the results, filled with null values.
#[inline]
pub fn schema(&self) -> &ArrowSchema {
&self.init().arrow_schema
}
/// Advance all internal cursors so that the next row yielded will correspond to `row_idx`.
///
/// Does nothing if `row_idx` is out of bounds.
///
/// ## Concurrency
///
/// Cursors are implemented using atomic variables, which means calling any of the `seek_*`
/// while iteration is concurrently ongoing is memory-safe but logically undefined racy
/// behavior. Be careful.
///
/// ## Performance
///
/// This requires going through every chunk once, and for each chunk running a binary search if
/// the chunk's time range contains the `index_value`.
///
/// I.e.: it's pretty cheap already.
#[inline]
pub fn seek_to_row(&self, row_idx: usize) {
let state = self.init();
let Some(index_value) = state.unique_index_values.get(row_idx) else {
return;
};
state.cur_row.store(row_idx as _, Ordering::Relaxed);
self.seek_to_index_value(*index_value);
}
/// Advance all internal cursors so that the next row yielded will correspond to `index_value`.
///
/// If `index_value` isn't present in the dataset, this seeks to the first index value
/// available past that point, if any.
///
/// ## Concurrency
///
/// Cursors are implemented using atomic variables, which means calling any of the `seek_*`
/// while iteration is concurrently ongoing is memory-safe but logically undefined racy
/// behavior. Be careful.
///
/// ## Performance
///
/// This requires going through every chunk once, and for each chunk running a binary search if
/// the chunk's time range contains the `index_value`.
///
/// I.e.: it's pretty cheap already.
fn seek_to_index_value(&self, index_value: IndexValue) {
re_tracing::profile_function!();
let state = self.init();
if index_value.is_static() {
for chunks in &state.view_chunks {
for (cursor, _chunk) in chunks {
cursor.store(0, Ordering::Relaxed);
}
}
return;
}
for chunks in &state.view_chunks {
for (cursor, chunk) in chunks {
// NOTE: The chunk has been densified already: its global time range is the same as
// the time range for the specific component of interest.
let Some(time_column) = chunk.timelines().get(&state.filtered_index) else {
continue;
};
let time_range = time_column.time_range();
let new_cursor = if index_value < time_range.min() {
0
} else if index_value > time_range.max() {
chunk.num_rows() as u64 /* yes, one past the end -- not a mistake */
} else {
time_column
.times_raw()
.partition_point(|&time| time < index_value.as_i64())
as u64
};
cursor.store(new_cursor, Ordering::Relaxed);
}
}
}
/// How many rows of data will be returned?
///
/// The number of rows depends and only depends on the _view contents_.
/// The _selected contents_ has no influence on this value.
pub fn num_rows(&self) -> u64 {
let num_rows = self.init().unique_index_values.len() as _;
// NOTE: This is too slow to run in practice, even for debug builds.
// Do keep this around though, it does come in handy.
#[allow(clippy::overly_complex_bool_expr)]
if false && cfg!(debug_assertions) {
let expected_num_rows =
self.engine.query(self.query.clone()).into_iter().count() as u64;
assert_eq!(expected_num_rows, num_rows);
}
num_rows
}
/// Returns the next row's worth of data.
///
/// The returned vector of Arrow arrays strictly follows the schema specified by [`Self::schema`].
/// Columns that do not yield any data will still be present in the results, filled with null values.
///
/// Each cell in the result corresponds to the latest _locally_ known value at that particular point in
/// the index, for each respective `ColumnDescriptor`.
/// See [`QueryExpression::sparse_fill_strategy`] to go beyond local resolution.
///
/// Example:
/// ```ignore
/// while let Some(row) = query_handle.next_row() {
/// // …
/// }
/// ```
///
/// ## Pagination
///
/// Use [`Self::seek_to_row`]:
/// ```ignore
/// query_handle.seek_to_row(42);
/// for row in query_handle.into_iter().take(len) {
/// // …
/// }
/// ```
pub fn next_row(&self) -> Option<Vec<Box<dyn ArrowArray>>> {
re_tracing::profile_function!();
/// Temporary state used to resolve the streaming join for the current iteration.
#[derive(Debug)]
struct StreamingJoinStateEntry<'a> {
/// Which `Chunk` is this?
chunk: &'a Chunk,
/// How far are we into this `Chunk`?
cursor: u64,
/// What's the `RowId` at the current cursor?
row_id: RowId,
}
/// Temporary state used to resolve the streaming join for the current iteration.
///
/// Possibly retrofilled, see [`QueryExpression::sparse_fill_strategy`].
#[derive(Debug)]
enum StreamingJoinState<'a> {
/// Incoming data for the current iteration.
StreamingJoinState(StreamingJoinStateEntry<'a>),
/// Data retrofilled through an extra query.
///
/// See [`QueryExpression::sparse_fill_strategy`].
Retrofilled(UnitChunkShared),
}
let state = self.init();
let row_idx = state.cur_row.fetch_add(1, Ordering::Relaxed);
let cur_index_value = state.unique_index_values.get(row_idx as usize)?;
// First, we need to find, among all the chunks available for the current view contents,
// what is their index value for the current row?
//
// NOTE: Non-component columns don't have a streaming state, hence the optional layer.
let mut view_streaming_state: Vec<Option<StreamingJoinStateEntry<'_>>> =
// NOTE: cannot use vec![], it has limitations with non-cloneable options.
// vec![None; state.view_chunks.len()];
std::iter::repeat(())
.map(|_| None)
.take(state.view_chunks.len())
.collect();
for (view_column_idx, view_chunks) in state.view_chunks.iter().enumerate() {
let streaming_state = &mut view_streaming_state[view_column_idx];
'overlaps: for (cur_cursor, cur_chunk) in view_chunks {
// TODO(cmc): This can easily be optimized by looking ahead and breaking as soon as chunks
// stop overlapping.
// NOTE: Too soon to increment the cursor, we cannot know yet which chunks will or
// will not be part of the current row.
let mut cur_cursor_value = cur_cursor.load(Ordering::Relaxed);
let cur_index_times_empty: &[i64] = &[];
let cur_index_times = cur_chunk
.timelines()
.get(&state.filtered_index)
.map_or(cur_index_times_empty, |time_column| time_column.times_raw());
let cur_index_row_ids = cur_chunk.row_ids_raw();
// NOTE: "Deserializing" everything into a native vec is way too much for rustc to
// follow and doesn't get optimized at all -- we have to work with raw arrow data
// all the way, so this gets a bit complicated.
let cur_index_row_id_at = |at: usize| {
let (times, incs) = cur_index_row_ids;
let times = times.values().as_slice();
let incs = incs.values().as_slice();
let time = *times.get(at)?;
let inc = *incs.get(at)?;
Some(RowId::from_u128(((time as u128) << 64) | (inc as u128)))
};
let (index_value, cur_row_id) = 'walk: loop {
let (Some(mut index_value), Some(mut cur_row_id)) = (
cur_index_times
.get(cur_cursor_value as usize)
.copied()
.map(TimeInt::new_temporal),
cur_index_row_id_at(cur_cursor_value as usize),
) else {
continue 'overlaps;
};
if index_value == *cur_index_value {
// TODO(cmc): Because of Arrow's `ListArray` limitations, we inline the
// "deduped_latest_on_index" logic here directly, which prevents a lot of
// unnecessary allocations and copies.
while let (Some(next_index_value), Some(next_row_id)) = (
cur_index_times
.get(cur_cursor_value as usize + 1)
.copied()
.map(TimeInt::new_temporal),
cur_index_row_id_at(cur_cursor_value as usize + 1),
) {
if next_index_value == *cur_index_value {
index_value = next_index_value;
cur_row_id = next_row_id;
cur_cursor_value = cur_cursor.fetch_add(1, Ordering::Relaxed) + 1;
} else {
break;
}
}
break 'walk (index_value, cur_row_id);
}
if index_value > *cur_index_value {
continue 'overlaps;
}
cur_cursor_value = cur_cursor.fetch_add(1, Ordering::Relaxed) + 1;
};
debug_assert_eq!(index_value, *cur_index_value);
if let Some(streaming_state) = streaming_state.as_mut() {
let StreamingJoinStateEntry {
chunk,
cursor,
row_id,
} = streaming_state;
if cur_row_id > *row_id {
*chunk = cur_chunk;
*cursor = cur_cursor_value;
*row_id = cur_row_id;
}
} else {
*streaming_state = Some(StreamingJoinStateEntry {
chunk: cur_chunk,
cursor: cur_cursor_value,
row_id: cur_row_id,
});
};
}
}
let mut view_streaming_state = view_streaming_state
.into_iter()
.map(|streaming_state| streaming_state.map(StreamingJoinState::StreamingJoinState))
.collect_vec();
// Static always wins, no matter what.
for (selected_idx, static_state) in state.selected_static_values.iter().enumerate() {
if let static_state @ Some(_) =
static_state.clone().map(StreamingJoinState::Retrofilled)
{
let Some(view_idx) = state
.selected_contents
.get(selected_idx)
.map(|(view_idx, _)| *view_idx)
else {
debug_assert!(false, "selected_idx out of bounds");
continue;
};
let Some(streaming_state) = view_streaming_state.get_mut(view_idx) else {
debug_assert!(false, "view_idx out of bounds");
continue;
};
*streaming_state = static_state;
}
}
match self.query.sparse_fill_strategy {
SparseFillStrategy::None => {}
SparseFillStrategy::LatestAtGlobal => {
// Everything that yielded `null` for the current iteration.
let null_streaming_states = view_streaming_state
.iter_mut()
.enumerate()
.filter(|(_view_idx, streaming_state)| streaming_state.is_none());
for (view_idx, streaming_state) in null_streaming_states {
let Some(ColumnDescriptor::Component(descr)) =
state.view_contents.get(view_idx)
else {
continue;
};
// NOTE: While it would be very tempting to resolve the latest-at state
// of the entire view contents at `filtered_index_range.start - 1` once
// during `QueryHandle` initialization, and then bootstrap off of that, that
// would effectively close the door to efficient pagination forever, since
// we'd have to iterate over all the pages to compute the right latest-at
// value at t+n (i.e. no more random access).
// Therefore, it is better to simply do this the "dumb" way.
//
// TODO(cmc): Still, as always, this can be made faster and smarter at
// the cost of some extra complexity (e.g. caching the result across
// consecutive nulls etc). Later.
let query =
re_chunk::LatestAtQuery::new(state.filtered_index, *cur_index_value);
let results = self.engine.cache.latest_at(
&query,
&descr.entity_path,
[descr.component_name],