re_redap_tests 0.31.2

Official test suite for the Rerun Data Protocol
Documentation
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
use std::collections::HashMap;

use arrow::array::RecordBatch;
use re_arrow_util::concat_polymorphic_batches;
use re_protos::cloud::v1alpha1::ext::UnregisterFromDatasetRequest;
use re_protos::cloud::v1alpha1::index_properties::Props;
use re_protos::cloud::v1alpha1::rerun_cloud_service_server::RerunCloudService;
use re_protos::cloud::v1alpha1::{
    CreateIndexRequest, DeleteIndexesRequest, IndexColumn, IndexConfig, IndexProperties,
    InvertedIndex, ListIndexesRequest, SearchDatasetRequest, VectorIvfPqIndex,
};
use re_protos::common::v1alpha1::{ComponentDescriptor, EntityPath, IndexColumnSelector, Timeline};
use re_protos::headers::RerunHeadersInjectorExt as _;

use super::common::{
    DataSourcesDefinition, LayerDefinition, RerunCloudServiceExt as _, entry_name,
};

// --- Tests ---

/// Goes through the entire lifecycle of an index: creation, listing, search, deletion.
pub async fn index_lifecycle(service: impl RerunCloudService) {
    let data_sources_def = DataSourcesDefinition::new_with_tuid_prefix(
        1,
        [
            LayerDefinition::scalars("my_segment_id1").layer_name("scalars"), //
            LayerDefinition::text("my_segment_id1").layer_name("text"),       //
            LayerDefinition::embeddings("my_segment_id1", 256, 3).layer_name("embeddings"), //
        ],
    );

    let dataset_name = "my_dataset1";
    service.create_dataset_entry_with_name(dataset_name).await;
    service
        .register_with_dataset_name_blocking(dataset_name, data_sources_def.to_data_sources())
        .await;

    let indexes = list_indexes(&service, dataset_name).await.unwrap();
    assert!(indexes.is_empty());

    for req in generate_search_dataset_requests() {
        let code = service
            .search_dataset(
                tonic::Request::new(req)
                    .with_entry_name(entry_name(dataset_name))
                    .unwrap(),
            )
            .await
            .map(|_| ())
            .unwrap_err()
            .code();
        assert_eq!(code, tonic::Code::NotFound);
    }

    // TODO(cmc): At some point we will want to properly define what happens in case of concurrent
    // creations/deletions/listings, but we're not quite there yet.
    for _ in 0..3 {
        for req in generate_create_index_requests() {
            create_index(&service, dataset_name, req).await.unwrap();
        }

        for req in generate_create_index_requests() {
            let code = service
                .create_index(
                    tonic::Request::new(req)
                        .with_entry_name(entry_name(dataset_name))
                        .unwrap(),
                )
                .await
                .unwrap_err()
                .code();
            assert_eq!(code, tonic::Code::AlreadyExists);
        }

        let expected_indexes: HashMap<IndexColumn, IndexConfig> = generate_create_index_requests()
            .into_iter()
            .map(|index| {
                let config = index.config.unwrap();
                (config.column.clone().unwrap(), config)
            })
            .collect();

        let indexes = list_indexes(&service, dataset_name).await.unwrap();
        assert_eq!(expected_indexes, indexes);

        for req in generate_search_dataset_requests() {
            search_dataset(&service, dataset_name, req).await.unwrap();
        }

        let mut search_dataset_requests: HashMap<IndexColumn, SearchDatasetRequest> =
            generate_search_dataset_requests()
                .into_iter()
                .map(|req| (req.column.clone().unwrap(), req))
                .collect();
        for (column, config) in expected_indexes {
            let deleted_indexes = delete_indexes(
                &service,
                dataset_name,
                DeleteIndexesRequest {
                    column: Some(column.clone()),
                },
            )
            .await
            .unwrap();

            assert!(deleted_indexes.len() == 1);
            assert_eq!(config, deleted_indexes.into_values().next().unwrap());

            let indexes = list_indexes(&service, dataset_name).await.unwrap();
            assert!(!indexes.contains_key(&column));

            let code = service
                .search_dataset(
                    tonic::Request::new(search_dataset_requests.remove(&column).unwrap())
                        .with_entry_name(entry_name(dataset_name))
                        .unwrap(),
                )
                .await
                .map(|_| ())
                .unwrap_err()
                .code();
            assert_eq!(code, tonic::Code::NotFound);

            for req in search_dataset_requests.values() {
                search_dataset(&service, dataset_name, req.clone())
                    .await
                    .unwrap();
            }
        }

        let indexes = list_indexes(&service, dataset_name).await.unwrap();
        assert!(indexes.is_empty());
    }
}

pub async fn index_incremental(service: impl RerunCloudService) {
    let dataset_name = "my_dataset1";
    service.create_dataset_entry_with_name(dataset_name).await;

    let data_sources_def = DataSourcesDefinition::new_with_tuid_prefix(
        1,
        [
            LayerDefinition::text("my_segment_id1").layer_name("text"), //
        ],
    );
    service
        .register_with_dataset_name_blocking(dataset_name, data_sources_def.to_data_sources())
        .await;

    create_index(
        &service,
        dataset_name,
        generate_create_index_requests()[1].clone(),
    )
    .await
    .unwrap();

    let results = search_dataset(
        &service,
        dataset_name,
        generate_search_dataset_requests()[1].clone(),
    )
    .await
    .unwrap();
    assert_eq!(2, results.num_rows());

    let data_sources_def = DataSourcesDefinition::new_with_tuid_prefix(
        1,
        [
            LayerDefinition::text("my_segment_id2").layer_name("text"), //
        ],
    );
    service
        .register_with_dataset_name_blocking(dataset_name, data_sources_def.to_data_sources())
        .await;

    let results = search_dataset(
        &service,
        dataset_name,
        generate_search_dataset_requests()[1].clone(),
    )
    .await
    .unwrap();
    assert_eq!(4, results.num_rows());

    service
        .unregister_from_dataset(
            tonic::Request::new(
                UnregisterFromDatasetRequest {
                    segments_to_drop: vec!["my_segment_id1".to_owned().into()],
                    layers_to_drop: vec![],
                    force: false,
                }
                .into(),
            )
            .with_entry_name(entry_name(dataset_name))
            .unwrap(),
        )
        .await
        .unwrap();

    let results = search_dataset(
        &service,
        dataset_name,
        generate_search_dataset_requests()[1].clone(),
    )
    .await
    .unwrap();
    assert_eq!(2, results.num_rows());

    service
        .unregister_from_dataset(
            tonic::Request::new(
                UnregisterFromDatasetRequest {
                    segments_to_drop: vec!["my_segment_id2".to_owned().into()],
                    layers_to_drop: vec![],
                    force: false,
                }
                .into(),
            )
            .with_entry_name(entry_name(dataset_name))
            .unwrap(),
        )
        .await
        .unwrap();

    let results = search_dataset(
        &service,
        dataset_name,
        generate_search_dataset_requests()[1].clone(),
    )
    .await
    .unwrap();
    assert_eq!(0, results.num_rows());
}

pub async fn dataset_doesnt_exist(service: impl RerunCloudService) {
    let dataset_name = "doesnt_exist";

    let create_index_request = generate_create_index_requests().into_iter().next().unwrap();
    let search_dataset_request = generate_search_dataset_requests()
        .into_iter()
        .next()
        .unwrap();

    let code = service
        .list_indexes(
            tonic::Request::new(ListIndexesRequest {})
                .with_entry_name(entry_name(dataset_name))
                .unwrap(),
        )
        .await
        .unwrap_err()
        .code();

    assert_eq!(code, tonic::Code::NotFound);

    let code = service
        .search_dataset(
            tonic::Request::new(search_dataset_request)
                .with_entry_name(entry_name(dataset_name))
                .unwrap(),
        )
        .await
        .map(|_| ())
        .unwrap_err()
        .code();
    assert_eq!(code, tonic::Code::NotFound);

    let code = service
        .create_index(
            tonic::Request::new(create_index_request.clone())
                .with_entry_name(entry_name(dataset_name))
                .unwrap(),
        )
        .await
        .unwrap_err()
        .code();
    assert_eq!(code, tonic::Code::NotFound);

    let code = service
        .delete_indexes(
            tonic::Request::new(DeleteIndexesRequest {
                column: create_index_request.config.unwrap().column,
            })
            .with_entry_name(entry_name(dataset_name))
            .unwrap(),
        )
        .await
        .unwrap_err()
        .code();
    assert_eq!(code, tonic::Code::NotFound);
}

pub async fn column_doesnt_exist(service: impl RerunCloudService) {
    let data_sources_def = DataSourcesDefinition::new_with_tuid_prefix(
        1,
        [
            LayerDefinition::scalars("my_segment_id1").layer_name("scalars"), //
            LayerDefinition::text("my_segment_id1").layer_name("text"),       //
            LayerDefinition::embeddings("my_segment_id1", 256, 3).layer_name("embeddings"), //
        ],
    );

    let dataset_name = "my_dataset1";
    service.create_dataset_entry_with_name(dataset_name).await;
    service
        .register_with_dataset_name_blocking(dataset_name, data_sources_def.to_data_sources())
        .await;

    let mut create_index_requests = generate_create_index_requests();
    for req in &mut create_index_requests {
        let entity_path = &mut req
            .config
            .as_mut()
            .unwrap()
            .column
            .as_mut()
            .unwrap()
            .entity_path
            .as_mut()
            .unwrap()
            .path;

        *entity_path = "doesnt_exist".to_owned();
    }

    let mut search_dataset_requests = generate_search_dataset_requests();
    for req in &mut search_dataset_requests {
        let entity_path = &mut req
            .column
            .as_mut()
            .unwrap()
            .entity_path
            .as_mut()
            .unwrap()
            .path;

        *entity_path = "doesnt_exist".to_owned();
    }

    let indexes = list_indexes(&service, dataset_name).await.unwrap();
    assert!(indexes.is_empty());

    for req in search_dataset_requests {
        let code = service
            .search_dataset(
                tonic::Request::new(req)
                    .with_entry_name(entry_name(dataset_name))
                    .unwrap(),
            )
            .await
            .map(|_| ())
            .unwrap_err()
            .code();

        // TODO(RR-3100)
        assert!(code == tonic::Code::InvalidArgument || code == tonic::Code::NotFound);
    }

    for req in &create_index_requests {
        let deleted_indexes = delete_indexes(
            &service,
            dataset_name,
            DeleteIndexesRequest {
                column: req.config.clone().unwrap().column,
            },
        )
        .await
        .unwrap();

        assert!(deleted_indexes.is_empty());
    }

    for req in &create_index_requests {
        let code = service
            .create_index(
                tonic::Request::new(req.clone())
                    .with_entry_name(entry_name(dataset_name))
                    .unwrap(),
            )
            .await
            .unwrap_err()
            .code();

        // TODO(RR-3100)
        assert!(code == tonic::Code::InvalidArgument || code == tonic::Code::NotFound);
    }
}

// --- Helpers ---

/// Generates a bunch of [`CreateIndexRequest`]s for every kind of index.
fn generate_create_index_requests() -> Vec<CreateIndexRequest> {
    vec![
        // scalars / btree
        CreateIndexRequest {
            config: Some(IndexConfig {
                properties: Some(IndexProperties {
                    props: Some(Props::Btree(re_protos::cloud::v1alpha1::BTreeIndex {})),
                }),
                time_index: Some(IndexColumnSelector {
                    timeline: Some(Timeline {
                        name: "log_time".to_owned(),
                    }),
                }),
                column: Some(IndexColumn {
                    entity_path: Some(EntityPath {
                        path: "/my_scalars".to_owned(),
                    }),
                    component: Some(ComponentDescriptor {
                        component: Some("scalar".to_owned()),
                        ..Default::default()
                    }),
                }),
            }),
        },
        // text / fts
        CreateIndexRequest {
            config: Some(IndexConfig {
                properties: Some(IndexProperties {
                    props: Some(Props::Inverted(InvertedIndex {
                        store_position: Some(false),
                        base_tokenizer: Some("simple".to_owned()),
                    })),
                }),
                time_index: Some(IndexColumnSelector {
                    timeline: Some(Timeline {
                        name: "log_time".to_owned(),
                    }),
                }),
                column: Some(IndexColumn {
                    entity_path: Some(EntityPath {
                        path: "/my_text".to_owned(),
                    }),
                    component: Some(ComponentDescriptor {
                        component_type: Some("rerun.components.Text".to_owned()),
                        archetype: Some("rerun.archetypes.TextLog".to_owned()),
                        component: Some("TextLog:text".to_owned()),
                    }),
                }),
            }),
        },
        // embeddings / vector
        CreateIndexRequest {
            config: Some(IndexConfig {
                properties: Some(IndexProperties {
                    props: Some(Props::Vector(VectorIvfPqIndex {
                        target_partition_num_rows: Some(128),
                        num_sub_vectors: Some(16),
                        distance_metrics: re_protos::cloud::v1alpha1::VectorDistanceMetric::L2
                            as i32,
                    })),
                }),
                time_index: Some(IndexColumnSelector {
                    timeline: Some(Timeline {
                        name: "log_time".to_owned(),
                    }),
                }),
                column: Some({
                    IndexColumn {
                        entity_path: Some(EntityPath {
                            path: "/my_embeddings".to_owned(),
                        }),
                        component: Some(ComponentDescriptor {
                            archetype: None,
                            component: Some("embedding".to_owned()),
                            component_type: None,
                        }),
                    }
                }),
            }),
        },
    ]
}

/// Generates a bunch of [`SearchDatasetRequest`]s for every kind of index.
fn generate_search_dataset_requests() -> Vec<SearchDatasetRequest> {
    use std::sync::Arc;

    use arrow::array::{Float32Array, RecordBatch, StringArray};
    use arrow::datatypes::Field;
    use re_protos::cloud::v1alpha1::index_query_properties::Props;
    use re_protos::cloud::v1alpha1::{
        BTreeIndexQuery, IndexQueryProperties, InvertedIndexQuery, VectorIndexQuery,
    };

    let mut create_index_requests = generate_create_index_requests().into_iter();
    vec![
        // scalars / btree
        SearchDatasetRequest {
            column: create_index_requests.next().unwrap().config.unwrap().column,
            query: Some(
                RecordBatch::try_new(
                    Arc::new(arrow::datatypes::Schema::new(vec![Field::new(
                        "query",
                        arrow::datatypes::DataType::Utf8,
                        false,
                    )])),
                    vec![Arc::new(StringArray::from(vec!["42.0"]))],
                )
                .unwrap()
                .into(),
            ),
            properties: Some(IndexQueryProperties {
                props: Some(Props::Btree(BTreeIndexQuery {})),
            }),
            scan_parameters: None,
        },
        // text / fts
        SearchDatasetRequest {
            column: create_index_requests.next().unwrap().config.unwrap().column,
            query: Some(
                RecordBatch::try_new(
                    Arc::new(arrow::datatypes::Schema::new(vec![Field::new(
                        "query",
                        arrow::datatypes::DataType::Utf8,
                        false,
                    )])),
                    vec![Arc::new(StringArray::from(vec!["the wind cries mary"]))],
                )
                .unwrap()
                .into(),
            ),
            properties: Some(IndexQueryProperties {
                props: Some(Props::Inverted(InvertedIndexQuery {})),
            }),
            scan_parameters: None,
        },
        // embeddings / vector
        SearchDatasetRequest {
            column: create_index_requests.next().unwrap().config.unwrap().column,
            query: Some(
                RecordBatch::try_new(
                    Arc::new(arrow::datatypes::Schema::new(vec![Field::new(
                        "query",
                        arrow::datatypes::DataType::Float32,
                        false,
                    )])),
                    vec![Arc::new(Float32Array::from_iter_values(
                        (0..256).map(|_| 42.0f32),
                    ))],
                )
                .unwrap()
                .into(),
            ),
            properties: Some(IndexQueryProperties {
                props: Some(
                    re_protos::cloud::v1alpha1::index_query_properties::Props::Vector(
                        VectorIndexQuery { top_k: Some(5) },
                    ),
                ),
            }),
            scan_parameters: None,
        },
    ]
}

/// Returns `Ok(())` if the operation is not supported.
async fn create_index(
    service: &impl RerunCloudService,
    dataset_name: &str,
    req: CreateIndexRequest,
) -> tonic::Result<()> {
    let _res = service
        .create_index(tonic::Request::new(req).with_entry_name(entry_name(dataset_name))?)
        .await?;

    Ok(())
}

async fn search_dataset(
    service: &impl RerunCloudService,
    dataset_name: &str,
    req: SearchDatasetRequest,
) -> tonic::Result<RecordBatch> {
    let res = service
        .search_dataset(tonic::Request::new(req).with_entry_name(entry_name(dataset_name))?)
        .await?;

    use futures::StreamExt as _;
    let batches = res
        .into_inner()
        .map(|r| r.unwrap().data.unwrap().try_into().unwrap())
        .collect::<Vec<_>>()
        .await;

    let batch = concat_polymorphic_batches(&batches).unwrap();

    Ok(batch)
}

async fn list_indexes(
    service: &impl RerunCloudService,
    dataset_name: &str,
) -> tonic::Result<HashMap<IndexColumn, IndexConfig>> {
    let res = service
        .list_indexes(
            tonic::Request::new(ListIndexesRequest {}).with_entry_name(entry_name(dataset_name))?,
        )
        .await?;

    let indexes: HashMap<IndexColumn, IndexConfig> = res
        .into_inner()
        .indexes
        .into_iter()
        .map(|config| (config.column.clone().unwrap(), config))
        .collect();

    Ok(indexes)
}

async fn delete_indexes(
    service: &impl RerunCloudService,
    dataset_name: &str,
    req: DeleteIndexesRequest,
) -> tonic::Result<HashMap<IndexColumn, IndexConfig>> {
    let res = service
        .delete_indexes(tonic::Request::new(req).with_entry_name(entry_name(dataset_name))?)
        .await?;

    let indexes: HashMap<IndexColumn, IndexConfig> = res
        .into_inner()
        .indexes
        .into_iter()
        .map(|config| (config.column.clone().unwrap(), config))
        .collect();

    Ok(indexes)
}