Skip to main content

ursa_engine/graph/view/
rows.rs

1//! Rows of a table by their numbers: how the inspector reads an edge's row
2//! once the graph's index has said which it is (#489).
3//!
4//! [`take`] gives the rows of a table numbered so, when the table is read as
5//! one partition (as every table is in the browser): then its rows come in
6//! one order, and the edge index numbered them in it.
7//!
8//! - **A Parquet file** is read with a row selection ([`selected`]): the
9//!   reader skips the row groups the rows are not in, and in a row group
10//!   passes over the pages before a row without decoding them.
11//! - **Any other table** is read from its start up to the last of the rows.
12//!
13//! A Parquet reader still asks for a row group's whole column chunks, unless
14//! the file has a page index: 3.8 MB for a million edges, and in the browser
15//! a request of the server for every row read. So the bytes read for a
16//! selection are kept ([`ReadCache`]), a session's last [`CACHE_BYTES`] of
17//! them, under the file's size, time and entity tag, which a scan looks up
18//! afresh: the next row of the same row group asks the server for nothing,
19//! and a file that has changed is read again.
20
21use std::collections::HashMap;
22use std::ops::Range;
23use std::sync::{Arc, Mutex};
24
25use bytes::Bytes;
26use datafusion::arrow::array::RecordBatch;
27use datafusion::common::stats::Precision;
28use datafusion::dataframe::DataFrame;
29use datafusion::datasource::listing::PartitionedFile;
30use datafusion::datasource::physical_plan::parquet::{
31    DefaultParquetFileReaderFactory, ParquetFileReaderFactory, ParquetRowSelection,
32};
33use datafusion::datasource::physical_plan::{
34    FileGroup, FileScanConfig, FileScanConfigBuilder, FileSource, ParquetSource,
35};
36use datafusion::datasource::source::DataSourceExec;
37use datafusion::error::Result;
38use datafusion::parquet::arrow::arrow_reader::{ArrowReaderOptions, RowSelection};
39use datafusion::parquet::arrow::async_reader::AsyncFileReader;
40use datafusion::parquet::file::metadata::ParquetMetaData;
41use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
42use datafusion::physical_plan::projection::ProjectionExec;
43use datafusion::physical_plan::{
44    replace_children_if_necessary, ExecutionPlan, ExecutionPlanProperties,
45};
46use datafusion::prelude::{SessionConfig, SessionContext};
47use futures::future::BoxFuture;
48use futures::{FutureExt, StreamExt};
49
50/// The most bytes a session keeps of what it read for rows by number.
51pub const CACHE_BYTES: usize = 64 << 20;
52
53/// The rows of `frame` numbered `rows` (ascending, each once), in that
54/// order: fewer when it ends before one of them. `None` when it is read as
55/// several partitions: its rows then come in no one order, and a row number
56/// finds nothing.
57pub async fn take(
58    ctx: &SessionContext,
59    frame: DataFrame,
60    rows: &[u64],
61) -> Result<Option<Vec<RecordBatch>>> {
62    let plan = frame.create_physical_plan().await?;
63    if plan.output_partitioning().partition_count() != 1 {
64        return Ok(None);
65    }
66    let mut taken = Vec::with_capacity(rows.len());
67    if let Some(plan) = selected(ctx, &plan, rows) {
68        let mut stream = plan.execute(0, ctx.task_ctx())?;
69        while let Some(batch) = stream.next().await {
70            taken.push(batch?);
71        }
72    } else {
73        let mut stream = plan.execute(0, ctx.task_ctx())?;
74        let (mut wanted, mut passed) = (rows.iter().copied().peekable(), 0u64);
75        while wanted.peek().is_some() {
76            let Some(batch) = stream.next().await else {
77                break;
78            };
79            let batch = batch?;
80            let end = passed + batch.num_rows() as u64;
81            while let Some(row) = wanted.next_if(|&row| row < end) {
82                taken.push(batch.slice((row - passed) as usize, 1));
83            }
84            passed = end;
85        }
86    }
87    Ok(Some(taken))
88}
89
90/// `plan` reading only its rows numbered `rows` (ascending), when it is a
91/// scan of one whole Parquet file with a known number of rows, under nothing
92/// but projections: the file's scan with a row selection, its reads kept in
93/// the session's [`ReadCache`]. `None` for any other plan, and when a row is
94/// past the file's end.
95fn selected(
96    ctx: &SessionContext,
97    plan: &Arc<dyn ExecutionPlan>,
98    rows: &[u64],
99) -> Option<Arc<dyn ExecutionPlan>> {
100    if let Some(projection) = plan.downcast_ref::<ProjectionExec>() {
101        let input = selected(ctx, projection.input(), rows)?;
102        return replace_children_if_necessary(Arc::clone(plan), vec![input]).ok();
103    }
104    let config = plan
105        .downcast_ref::<DataSourceExec>()?
106        .data_source()
107        .downcast_ref::<FileScanConfig>()?;
108    let source = config.file_source().downcast_ref::<ParquetSource>()?;
109    let [group] = config.file_groups.as_slice() else {
110        return None;
111    };
112    let [file] = group.files() else {
113        return None;
114    };
115    // The whole file, every row: no filter in the scan, no limit, and no
116    // range but the whole file (a scan of a file over HTTP, as the browser
117    // reads a dataset, names the whole file as its range).
118    let whole = file
119        .range
120        .as_ref()
121        .is_none_or(|r| r.start <= 0 && r.end >= file.object_meta.size as i64);
122    if config.limit.is_some() || !whole || source.filter().is_some() {
123        return None;
124    }
125    let Precision::Exact(total) = file.statistics.as_ref()?.num_rows else {
126        return None;
127    };
128    if rows.last().is_none_or(|&last| last >= total as u64) {
129        return None;
130    }
131    let selection = RowSelection::from_consecutive_ranges(
132        rows.iter().map(|&row| row as usize..row as usize + 1),
133        total,
134    );
135    let file = file
136        .clone()
137        .with_extension(ParquetRowSelection::new(selection));
138    let mut builder = FileScanConfigBuilder::from(config.clone())
139        .with_file_groups(vec![FileGroup::new(vec![file])]);
140    if let Some(cache) = ctx.state().config().get_extension::<ReadCache>() {
141        let inner = match source.parquet_file_reader_factory() {
142            Some(factory) => Arc::clone(factory),
143            None => {
144                let store = ctx.runtime_env().object_store(&config.object_store_url);
145                Arc::new(DefaultParquetFileReaderFactory::new(store.ok()?))
146            }
147        };
148        let readers = Arc::new(KeptReads {
149            inner,
150            cache,
151            store: config.object_store_url.to_string(),
152        });
153        builder = builder.with_source(Arc::new(
154            source.clone().with_parquet_file_reader_factory(readers),
155        ));
156    }
157    Some(DataSourceExec::from_data_source(builder.build()))
158}
159
160/// Install an empty [`ReadCache`] on `config`.
161pub(crate) fn with_read_cache(config: SessionConfig) -> SessionConfig {
162    config.with_extension(Arc::new(ReadCache::default()))
163}
164
165/// A file as it was when its bytes were read: its store and path, and the
166/// size, time and entity tag the store gave for it.
167#[derive(Debug, Clone, PartialEq, Eq, Hash)]
168struct FileVersion {
169    store: String,
170    location: String,
171    size: u64,
172    modified: i64,
173    e_tag: Option<String>,
174}
175
176/// The bytes a session read for rows by number (a session config
177/// extension): byte ranges of files, the least recently used dropped once
178/// they pass [`CACHE_BYTES`]. A range longer than that is not kept.
179#[derive(Debug, Default)]
180pub struct ReadCache {
181    held: Mutex<Held>,
182}
183
184#[derive(Debug, Default)]
185struct Held {
186    ranges: HashMap<(FileVersion, Range<u64>), (Bytes, u64)>,
187    bytes: usize,
188    /// Bumped on every use, to find the least recently used range.
189    clock: u64,
190}
191
192impl ReadCache {
193    fn get(&self, file: &FileVersion, range: &Range<u64>) -> Option<Bytes> {
194        let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner());
195        held.clock += 1;
196        let now = held.clock;
197        let (bytes, used) = held.ranges.get_mut(&(file.clone(), range.clone()))?;
198        *used = now;
199        Some(bytes.clone())
200    }
201
202    fn put(&self, file: &FileVersion, range: Range<u64>, bytes: &Bytes) {
203        if bytes.len() > CACHE_BYTES {
204            return;
205        }
206        let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner());
207        // Another version of the file is of no use again.
208        let stale = |(other, _): &(FileVersion, Range<u64>)| {
209            other != file && other.store == file.store && other.location == file.location
210        };
211        let mut freed = 0;
212        held.ranges.retain(|key, (bytes, _)| {
213            let keep = !stale(key);
214            if !keep {
215                freed += bytes.len();
216            }
217            keep
218        });
219        held.bytes -= freed;
220        held.clock += 1;
221        let now = held.clock;
222        if let Some((old, _)) = held
223            .ranges
224            .insert((file.clone(), range), (bytes.clone(), now))
225        {
226            held.bytes -= old.len();
227        }
228        held.bytes += bytes.len();
229        while held.bytes > CACHE_BYTES {
230            let Some(oldest) = held
231                .ranges
232                .iter()
233                .min_by_key(|(_, (_, used))| *used)
234                .map(|(key, _)| key.clone())
235            else {
236                break;
237            };
238            if let Some((bytes, _)) = held.ranges.remove(&oldest) {
239                held.bytes -= bytes.len();
240            }
241        }
242    }
243
244    /// How many bytes are held: for tests.
245    pub fn bytes(&self) -> usize {
246        self.held.lock().unwrap_or_else(|e| e.into_inner()).bytes
247    }
248}
249
250/// Parquet readers whose reads are kept in a [`ReadCache`]: `inner`'s, which
251/// read the file (and keep its footer, if they do).
252#[derive(Debug)]
253struct KeptReads {
254    inner: Arc<dyn ParquetFileReaderFactory>,
255    cache: Arc<ReadCache>,
256    store: String,
257}
258
259impl ParquetFileReaderFactory for KeptReads {
260    fn create_reader(
261        &self,
262        partition_index: usize,
263        partitioned_file: PartitionedFile,
264        metadata_size_hint: Option<usize>,
265        metrics: &ExecutionPlanMetricsSet,
266    ) -> Result<Box<dyn AsyncFileReader + Send>> {
267        let meta = &partitioned_file.object_meta;
268        let file = FileVersion {
269            store: self.store.clone(),
270            location: meta.location.to_string(),
271            size: meta.size,
272            modified: meta.last_modified.timestamp_nanos_opt().unwrap_or(i64::MAX),
273            e_tag: meta.e_tag.clone(),
274        };
275        let inner = self.inner.create_reader(
276            partition_index,
277            partitioned_file,
278            metadata_size_hint,
279            metrics,
280        )?;
281        Ok(Box::new(KeptReader {
282            inner,
283            cache: Arc::clone(&self.cache),
284            file,
285        }))
286    }
287}
288
289/// A Parquet reader that asks its [`ReadCache`] first.
290struct KeptReader {
291    inner: Box<dyn AsyncFileReader + Send>,
292    cache: Arc<ReadCache>,
293    file: FileVersion,
294}
295
296impl AsyncFileReader for KeptReader {
297    fn get_bytes(
298        &mut self,
299        range: Range<u64>,
300    ) -> BoxFuture<'_, datafusion::parquet::errors::Result<Bytes>> {
301        async move {
302            if let Some(bytes) = self.cache.get(&self.file, &range) {
303                return Ok(bytes);
304            }
305            let bytes = self.inner.get_bytes(range.clone()).await?;
306            self.cache.put(&self.file, range, &bytes);
307            Ok(bytes)
308        }
309        .boxed()
310    }
311
312    fn get_byte_ranges(
313        &mut self,
314        ranges: Vec<Range<u64>>,
315    ) -> BoxFuture<'_, datafusion::parquet::errors::Result<Vec<Bytes>>> {
316        async move {
317            let mut found: Vec<Option<Bytes>> = ranges
318                .iter()
319                .map(|range| self.cache.get(&self.file, range))
320                .collect();
321            let missing: Vec<Range<u64>> = ranges
322                .iter()
323                .zip(&found)
324                .filter(|(_, found)| found.is_none())
325                .map(|(range, _)| range.clone())
326                .collect();
327            if !missing.is_empty() {
328                // One request for all of them, as the reader would make.
329                let read = self.inner.get_byte_ranges(missing.clone()).await?;
330                let mut read = missing.into_iter().zip(read);
331                for slot in found.iter_mut().filter(|slot| slot.is_none()) {
332                    if let Some((range, bytes)) = read.next() {
333                        self.cache.put(&self.file, range, &bytes);
334                        *slot = Some(bytes);
335                    }
336                }
337            }
338            found
339                .into_iter()
340                .map(|bytes| {
341                    bytes.ok_or_else(|| {
342                        datafusion::parquet::errors::ParquetError::General(
343                            "a byte range was not read".into(),
344                        )
345                    })
346                })
347                .collect()
348        }
349        .boxed()
350    }
351
352    fn get_metadata<'a>(
353        &'a mut self,
354        options: Option<&'a ArrowReaderOptions>,
355    ) -> BoxFuture<'a, datafusion::parquet::errors::Result<Arc<ParquetMetaData>>> {
356        self.inner.get_metadata(options)
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363    use datafusion::arrow::array::Int64Array;
364
365    async fn plan_of(ctx: &SessionContext, query: &str) -> Arc<dyn ExecutionPlan> {
366        let frame = ctx.sql(query).await.unwrap();
367        frame.create_physical_plan().await.unwrap()
368    }
369
370    /// Column `at` of what `plan` reads.
371    async fn column(ctx: &SessionContext, plan: Arc<dyn ExecutionPlan>, at: usize) -> Vec<i64> {
372        let batches = datafusion::physical_plan::collect(plan, ctx.task_ctx())
373            .await
374            .unwrap();
375        batches
376            .iter()
377            .flat_map(|b| {
378                let c = b.column(at).as_any().downcast_ref::<Int64Array>().unwrap();
379                c.values().to_vec()
380            })
381            .collect()
382    }
383
384    fn cached(ctx: &SessionContext) -> usize {
385        let cache = ctx.state().config().get_extension::<ReadCache>();
386        cache.expect("a session has a read cache").bytes()
387    }
388
389    /// A scan of one Parquet file reads rows by number with a row selection,
390    /// across its row groups and under a projection, and keeps what it read;
391    /// anything else has no selection, and `take` passes over its rows.
392    #[tokio::test]
393    async fn a_parquet_scan_reads_rows_by_a_selection() {
394        let dir = tempfile::tempdir().unwrap();
395        let file = |name: &str| dir.path().join(name).display().to_string();
396        let ctx = crate::new_session();
397        for sql in [
398            "SET datafusion.execution.target_partitions = 1".to_string(),
399            "SET datafusion.execution.parquet.max_row_group_size = 100".to_string(),
400            format!(
401                "COPY (SELECT value AS i, value * 2 AS j FROM range(0, 1000) ORDER BY i) TO '{}'",
402                file("t.parquet")
403            ),
404            format!(
405                "COPY (SELECT value AS i FROM range(0, 1000) ORDER BY i) TO '{}'",
406                file("t.csv")
407            ),
408        ] {
409            ctx.sql(&sql).await.unwrap().collect().await.unwrap();
410        }
411        let table = format!("'{}'", file("t.parquet"));
412
413        let plan = plan_of(&ctx, &format!("SELECT * FROM {table}")).await;
414        let rows = [0, 99, 100, 101, 555, 999];
415        assert_eq!(cached(&ctx), 0);
416        let read = selected(&ctx, &plan, &rows).expect("a row selection");
417        assert_eq!(column(&ctx, read, 0).await, [0, 99, 100, 101, 555, 999]);
418        // What it read is kept, and read from there the next time: the
419        // same rows, and nothing more is kept for them.
420        let kept = cached(&ctx);
421        assert!(kept > 0);
422        let again = selected(&ctx, &plan, &[99, 555]).unwrap();
423        assert_eq!(column(&ctx, again, 1).await, [198, 1110]);
424        assert_eq!(cached(&ctx), kept);
425        // Under a projection, the same rows.
426        let plan = plan_of(&ctx, &format!("SELECT j + 1 AS k, i FROM {table}")).await;
427        let read = selected(&ctx, &plan, &[7, 640]).expect("a selection under a projection");
428        assert_eq!(column(&ctx, read, 0).await, [15, 1281]);
429
430        // A scan that names the whole file as its range (as one of a file
431        // over HTTP does) is of every row; one of part of the file is not.
432        let ranged = |end: Option<i64>| {
433            let config = plan
434                .downcast_ref::<DataSourceExec>()
435                .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
436                .expect("a scan of the file");
437            let file = config.file_groups[0].files()[0].clone();
438            let size = file.object_meta.size as i64;
439            let file = file.with_range(0, end.unwrap_or(size));
440            let config = FileScanConfigBuilder::from(config.clone())
441                .with_file_groups(vec![FileGroup::new(vec![file])])
442                .build();
443            DataSourceExec::from_data_source(config) as Arc<dyn ExecutionPlan>
444        };
445        let read = selected(&ctx, &ranged(None), &[3, 640]).expect("the whole file's range");
446        assert_eq!(column(&ctx, read, 1).await, [3, 640]);
447        assert!(selected(&ctx, &ranged(Some(100)), &[3]).is_none());
448
449        // A row past the file's end, no rows, a filter, a limit, and a file
450        // of another format: no selection.
451        let plan = plan_of(&ctx, &format!("SELECT * FROM {table}")).await;
452        assert!(selected(&ctx, &plan, &[5, 1000]).is_none());
453        assert!(selected(&ctx, &plan, &[]).is_none());
454        for query in [
455            format!("SELECT * FROM {table} WHERE i > 500"),
456            format!("SELECT * FROM {table} LIMIT 10"),
457            format!("SELECT * FROM '{}'", file("t.csv")),
458        ] {
459            let plan = plan_of(&ctx, &query).await;
460            assert!(selected(&ctx, &plan, &[5]).is_none(), "{query}");
461        }
462        // `take` reads those from their start, and stops at the table's end.
463        let csv = ctx
464            .sql(&format!("SELECT * FROM '{}'", file("t.csv")))
465            .await
466            .unwrap();
467        let taken = take(&ctx, csv, &[3, 998, 1000]).await.unwrap().unwrap();
468        let rows: usize = taken.iter().map(|b| b.num_rows()).sum();
469        assert_eq!(rows, 2);
470
471        // The file written again: its rows are read again, not the old ones.
472        std::thread::sleep(std::time::Duration::from_millis(20));
473        ctx.sql(&format!(
474            "COPY (SELECT value + 5000 AS i, value AS j FROM range(0, 1000) ORDER BY i) TO {table}"
475        ))
476        .await
477        .unwrap()
478        .collect()
479        .await
480        .unwrap();
481        let plan = plan_of(&ctx, &format!("SELECT * FROM {table}")).await;
482        let read = selected(&ctx, &plan, &[99, 555]).unwrap();
483        assert_eq!(column(&ctx, read, 0).await, [5099, 5555]);
484    }
485
486    #[test]
487    fn the_read_cache_drops_the_least_recently_used_and_stale_versions() {
488        let cache = ReadCache::default();
489        let version = |location: &str, size: u64| FileVersion {
490            store: "file:///".into(),
491            location: location.into(),
492            size,
493            modified: 0,
494            e_tag: None,
495        };
496        let block = Bytes::from(vec![0u8; CACHE_BYTES / 2 - 1]);
497        let (a, b) = (version("a", 1), version("b", 1));
498        cache.put(&a, 0..1, &block);
499        cache.put(&b, 0..1, &block);
500        assert!(cache.get(&a, &(0..1)).is_some());
501        // A third does not fit: b, used longest ago, goes.
502        cache.put(&a, 1..2, &block);
503        assert!(cache.get(&b, &(0..1)).is_none());
504        assert!(cache.get(&a, &(0..1)).is_some() && cache.get(&a, &(1..2)).is_some());
505        // Another version of a: the old one's ranges go.
506        cache.put(&version("a", 2), 0..1, &Bytes::from_static(b"new"));
507        assert!(cache.get(&a, &(0..1)).is_none());
508        assert_eq!(cache.bytes(), 3);
509        // More than the cache holds is not kept.
510        cache.put(&b, 0..1, &Bytes::from(vec![0u8; CACHE_BYTES + 1]));
511        assert_eq!(cache.bytes(), 3);
512    }
513}