-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathtests.rs
More file actions
433 lines (371 loc) · 12.9 KB
/
tests.rs
File metadata and controls
433 lines (371 loc) · 12.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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
use std::sync::Arc;
use anyhow::anyhow;
use datafusion::arrow::array::Int32Array;
use datafusion::arrow::util::pretty::pretty_format_batches;
use datafusion::datasource::provider::DefaultTableFactory;
use datafusion::execution::SessionStateBuilder;
use datafusion::prelude::SessionConfig;
use datafusion::prelude::SessionContext;
use datafusion_common::GetExt;
use datafusion_physical_plan::display::DisplayableExecutionPlan;
use insta::assert_snapshot;
use object_store::ObjectStore;
use object_store::memory::InMemory;
use rstest::rstest;
use vortex::VortexSessionDefault;
use vortex::array::IntoArray;
use vortex::array::arrays::ChunkedArray;
use vortex::array::arrays::StructArray;
use vortex::array::arrays::VarBinArray;
use vortex::array::validity::Validity;
use vortex::buffer::Buffer;
use vortex::buffer::buffer;
use vortex::file::OpenOptionsSessionExt;
use vortex::file::WriteOptionsSessionExt;
use vortex::io::VortexWrite;
use vortex::io::object_store::ObjectStoreReadAt;
use vortex::io::object_store::ObjectStoreWrite;
use vortex::layout::LayoutStrategy;
use vortex::layout::layouts::chunked::writer::ChunkedLayoutStrategy;
use vortex::layout::layouts::flat::writer::FlatLayoutStrategy;
use vortex::layout::layouts::table::TableStrategy;
use vortex::session::VortexSession;
use crate::VortexFormatFactory;
use crate::common_tests::TestSessionContext;
fn make_session(
object_store: Arc<dyn ObjectStore>,
repartition_file_scans: bool,
) -> SessionContext {
let factory = Arc::new(VortexFormatFactory::new());
let config = SessionConfig::new()
.with_target_partitions(4)
.with_repartition_file_scans(repartition_file_scans)
.with_repartition_file_min_size(0);
let mut state = SessionStateBuilder::new()
.with_config(config)
.with_default_features()
.with_table_factory(
factory.get_ext().to_uppercase(),
Arc::new(DefaultTableFactory::new()),
)
.with_object_store(&url::Url::try_from("file://").unwrap(), object_store);
if let Some(file_formats) = state.file_formats() {
file_formats.push(factory as _);
}
SessionContext::new_with_state(state.build()).enable_url_table()
}
async fn count_query_partitions(ctx: &SessionContext, sql: &str) -> anyhow::Result<usize> {
let explain = ctx.sql(&format!("EXPLAIN {sql}")).await?.collect().await?;
let plan = pretty_format_batches(&explain)?.to_string();
let marker = "DataSourceExec: file_groups={";
let start = plan
.find(marker)
.ok_or_else(|| anyhow!("EXPLAIN plan did not contain a DataSourceExec"))?
+ marker.len();
let partitions = plan[start..]
.chars()
.take_while(|ch| ch.is_ascii_digit())
.collect::<String>();
Ok(partitions.parse()?)
}
fn batch_values(batches: &[datafusion::arrow::array::RecordBatch]) -> Vec<i32> {
let mut values = Vec::with_capacity(batches.iter().map(|batch| batch.num_rows()).sum());
for batch in batches {
let array = batch
.column(0)
.as_any()
.downcast_ref::<Int32Array>()
.expect("value column should be Int32");
values.extend(array.values().iter().copied());
}
values
}
#[rstest]
#[tokio::test]
async fn test_query_file(#[values(Some(1), None)] limit: Option<usize>) -> anyhow::Result<()> {
let ctx = TestSessionContext::default();
let session = VortexSession::default();
let strings = ChunkedArray::from_iter([
VarBinArray::from(vec!["ab", "foo", "bar", "baz"]).into_array(),
VarBinArray::from(vec!["ab", "foo", "bar", "baz"]).into_array(),
])
.into_array();
let numbers = ChunkedArray::from_iter([
buffer![1u32, 2, 3, 4].into_array(),
buffer![5u32, 6, 7, 8].into_array(),
])
.into_array();
let st = StructArray::try_new(
["strings", "numbers"].into(),
vec![strings, numbers],
8,
Validity::NonNullable,
)?;
let mut writer = ObjectStoreWrite::new(Arc::clone(&ctx.store), &"test.vortex".into()).await?;
let summary = session
.write_options()
.write(&mut writer, st.into_array().to_array_stream())
.await?;
writer.shutdown().await?;
assert_eq!(summary.row_count(), 8);
let read_row_count = ctx
.session
.sql("SELECT * from '/test.vortex'")
.await?
.limit(0, limit)?
.count()
.await?;
assert_eq!(read_row_count, limit.unwrap_or(8));
Ok(())
}
#[tokio::test]
async fn test_addition_pushdown() -> anyhow::Result<()> {
let ctx = TestSessionContext::default();
ctx.session
.sql(
"CREATE EXTERNAL TABLE written_data \
(a TINYINT NOT NULL) \
STORED AS vortex \
LOCATION '/test/'",
)
.await?;
ctx.session
.sql("INSERT INTO written_data VALUES (0), (1), (2), (3), (4)")
.await?
.collect()
.await?;
let result = ctx
.session
.sql("SELECT a, a + 5 as five, a + 6 as six FROM written_data WHERE a + 5 > 7")
.await?
.collect()
.await?;
assert_snapshot!(pretty_format_batches(&result)?, @r"
+---+------+-----+
| a | five | six |
+---+------+-----+
| 3 | 8 | 9 |
| 4 | 9 | 10 |
+---+------+-----+
");
Ok(())
}
#[tokio::test]
async fn create_table_ordered_by() -> anyhow::Result<()> {
let ctx = TestSessionContext::default();
// Vortex
ctx.session
.sql(
"CREATE EXTERNAL TABLE my_tbl_vx \
(c1 VARCHAR NOT NULL, c2 INT NOT NULL) \
STORED AS vortex \
WITH ORDER (c1 ASC)
LOCATION '/test/'",
)
.await?;
ctx.session
.sql("INSERT INTO my_tbl_vx VALUES ('air', 5), ('balloon', 42)")
.await?
.collect()
.await?;
ctx.session
.sql("INSERT INTO my_tbl_vx VALUES ('zebra', 5)")
.await?
.collect()
.await?;
ctx.session
.sql("INSERT INTO my_tbl_vx VALUES ('texas', 2000), ('alabama', 2000)")
.await?
.collect()
.await?;
let df = ctx
.session
.sql("SELECT * FROM my_tbl_vx ORDER BY c1 ASC limit 3")
.await?;
let physical_plan = ctx
.session
.state()
.create_physical_plan(df.logical_plan())
.await?;
insta::assert_snapshot!(DisplayableExecutionPlan::new(physical_plan.as_ref())
.tree_render().to_string(), @r"
┌───────────────────────────┐
│ SortPreservingMergeExec │
│ -------------------- │
│ c1 ASC NULLS LAST │
│ │
│ limit: 3 │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ DataSourceExec │
│ -------------------- │
│ files: 3 │
│ format: vortex │
└───────────────────────────┘
");
let r = df.collect().await?;
insta::assert_snapshot!(pretty_format_batches(&r)?.to_string(), @r"
+---------+------+
| c1 | c2 |
+---------+------+
| air | 5 |
| alabama | 2000 |
| balloon | 42 |
+---------+------+
");
Ok(())
}
/// Doc example: demonstrates creating, writing, reading, and filtering a Vortex table.
#[tokio::test]
async fn doc_example() -> anyhow::Result<()> {
// [setup]
use std::sync::Arc;
use datafusion::datasource::provider::DefaultTableFactory;
use datafusion::execution::SessionStateBuilder;
use datafusion::prelude::SessionContext;
use datafusion_common::GetExt;
use object_store::memory::InMemory;
use crate::VortexFormatFactory;
let factory = Arc::new(VortexFormatFactory::new());
let state = SessionStateBuilder::new()
.with_default_features()
.with_table_factory(
factory.get_ext().to_uppercase(),
Arc::new(DefaultTableFactory::new()),
)
.with_file_formats(vec![factory])
.build();
let ctx = SessionContext::new_with_state(state).enable_url_table();
// [setup]
// Register an in-memory object store for the test.
let store = Arc::new(InMemory::new());
ctx.register_object_store(&url::Url::try_from("file://").unwrap(), store);
// [create]
ctx.sql(
"CREATE EXTERNAL TABLE my_table \
(name VARCHAR NOT NULL, age INT NOT NULL) \
STORED AS vortex \
LOCATION '/demo/'",
)
.await?;
// [create]
// [write]
ctx.sql(
"INSERT INTO my_table VALUES \
('Alice', 30), ('Bob', 25), ('Charlie', 35), ('Diana', 28)",
)
.await?
.collect()
.await?;
// [write]
// [query]
let result = ctx
.sql("SELECT name, age FROM my_table WHERE age > 28 ORDER BY age")
.await?
.collect()
.await?;
// [query]
assert_snapshot!(pretty_format_batches(&result)?, @r"
+---------+-----+
| name | age |
+---------+-----+
| Alice | 30 |
| Charlie | 35 |
+---------+-----+
");
Ok(())
}
#[tokio::test]
async fn test_repartitioned_scan_matches_non_repartitioned_for_uneven_splits() -> anyhow::Result<()>
{
let store = Arc::new(InMemory::new()) as _;
let session = VortexSession::default();
let path = object_store::path::Path::parse("/split-aligned-repartition.vortex")?;
let chunk_1_len = 2_000;
let chunk_2_len = 5_000;
let chunk_3_len = 6_000;
let row_count = chunk_1_len + chunk_2_len + chunk_3_len;
let chunk_1 = StructArray::try_new(
["value"].into(),
vec![Buffer::from_iter(0_i32..chunk_1_len).into_array()],
usize::try_from(chunk_1_len)?,
Validity::NonNullable,
)?;
let chunk_2 = StructArray::try_new(
["value"].into(),
vec![Buffer::from_iter(chunk_1_len..(chunk_1_len + chunk_2_len)).into_array()],
usize::try_from(chunk_2_len)?,
Validity::NonNullable,
)?;
let chunk_3 = StructArray::try_new(
["value"].into(),
vec![Buffer::from_iter((chunk_1_len + chunk_2_len)..row_count).into_array()],
usize::try_from(chunk_3_len)?,
Validity::NonNullable,
)?;
let table = ChunkedArray::from_iter([
chunk_1.into_array(),
chunk_2.into_array(),
chunk_3.into_array(),
])
.into_array();
let flat: Arc<dyn LayoutStrategy> = Arc::new(FlatLayoutStrategy::default());
let strategy: Arc<dyn LayoutStrategy> = Arc::new(TableStrategy::new(
Arc::clone(&flat),
Arc::new(ChunkedLayoutStrategy::new(FlatLayoutStrategy::default())),
));
let mut writer = ObjectStoreWrite::new(Arc::clone(&store), &path).await?;
let summary = session
.write_options()
.with_strategy(strategy)
.write(&mut writer, table.into_array().to_array_stream())
.await?;
writer.shutdown().await?;
let reader = Arc::new(ObjectStoreReadAt::new(
Arc::clone(&store),
path.clone(),
vortex::io::runtime::Handle::find().expect("tokio runtime should be available in tests"),
));
let vxf = session
.open_options()
.with_file_size(summary.size())
.open_read(reader)
.await?;
let split_ranges = vxf.splits()?;
let split_lengths = split_ranges
.iter()
.map(|range| range.end - range.start)
.collect::<Vec<_>>();
assert!(split_ranges.len() > 1);
assert!(
split_lengths
.windows(2)
.any(|window| window[0] != window[1])
);
let serial_ctx = make_session(Arc::clone(&store), false);
let repartitioned_ctx = make_session(Arc::clone(&store), true);
let repartitioned_partitions = count_query_partitions(
&repartitioned_ctx,
"SELECT value FROM '/split-aligned-repartition.vortex'",
)
.await?;
assert!(repartitioned_partitions > 1);
let serial = serial_ctx
.sql("SELECT value FROM '/split-aligned-repartition.vortex' ORDER BY value")
.await?
.collect()
.await?;
let repartitioned = repartitioned_ctx
.sql("SELECT value FROM '/split-aligned-repartition.vortex' ORDER BY value")
.await?
.collect()
.await?;
let serial_values = batch_values(&serial);
let repartitioned_values = batch_values(&repartitioned);
let expected = (0_i32..row_count).collect::<Vec<_>>();
assert_eq!(serial_values, expected);
assert_eq!(repartitioned_values, serial_values);
Ok(())
}