Skip to content

Commit 09fbbc1

Browse files
committed
perf(io): coordinate owned local reads by inode
1 parent 121b625 commit 09fbbc1

5 files changed

Lines changed: 374 additions & 31 deletions

File tree

‎.github/workflows/t210-input-lifetime.yml‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ jobs:
3737
print(io[0])
3838
print("lance-examples benchmark has no lance-io/test-util feature")
3939
PYFEATURES
40+
- name: Verify owned local read coordination and cancellation
41+
env:
42+
LANCE_CPU_THREADS: 1
43+
run: |
44+
cargo test --profile ci --locked -p lance-io --lib local::admitted_read::tests:: -- --nocapture
45+
cargo test --profile ci --locked -p lance-io --lib reserved_read::tests:: -- --nocapture
46+
cargo test --profile ci --locked -p lance-io --lib scheduler::read_into::tests:: -- --nocapture
47+
cargo test --profile ci --locked -p lance-file --lib reader::admitted_fullzip_tests::multi:: -- --nocapture
48+
cargo test --profile ci --locked -p lance-file --lib reader::admitted_fullzip_tests::take:: -- --nocapture
4049
- name: Verify fragment hint ownership and real dataset composition
4150
env:
4251
LANCE_CPU_THREADS: 1
@@ -54,6 +63,6 @@ jobs:
5463
- name: Lint benchmark paths
5564
if: ${{ !cancelled() }}
5665
run: cargo clippy --profile ci --locked -p lance-examples --example admitted_dataset --no-deps -- -D warnings
57-
- name: Lint Lance composition
66+
- name: Lint owned I/O and Lance composition
5867
if: ${{ !cancelled() }}
59-
run: cargo clippy --profile ci --locked -p lance --all-features --all-targets --no-deps -- -D warnings
68+
run: cargo clippy --profile ci --locked -p lance-io -p lance-file -p lance --all-features --all-targets --no-deps -- -D warnings

‎rust/lance-io/src/local.rs‎

Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ use crate::object_writer::WriteResult;
3232
use crate::traits::{ByteStream, Reader, Writer};
3333
use crate::utils::tracking_store::IOTracker;
3434

35+
mod admitted_read;
36+
3537
/// Convert an [`object_store::path::Path`] to a [`std::path::Path`].
3638
pub fn to_local_path(path: &Path) -> String {
3739
if cfg!(windows) {
@@ -241,6 +243,9 @@ pub struct LocalObjectReader {
241243
/// File handler.
242244
file: Arc<File>,
243245

246+
/// Lazy coordination for owned reads; ordinary reads bypass it.
247+
admitted_read: admitted_read::ReadGate,
248+
244249
/// Fie path.
245250
path: Path,
246251

@@ -303,6 +308,7 @@ impl LocalObjectReader {
303308
let size = OnceCell::new_with(known_size);
304309
Ok(Box::new(Self {
305310
file: Arc::new(file),
311+
admitted_read: Default::default(),
306312
block_size,
307313
size,
308314
path,
@@ -398,14 +404,16 @@ impl Reader for LocalObjectReader {
398404
let metrics = io_tracker.begin_io("get");
399405
// The blocking operation owns the reservation. Dropping the async
400406
// waiter must not refund memory while the read still writes into it.
401-
let result = join_local_io(tokio::task::spawn_blocking(move || {
402-
#[cfg(unix)]
403-
file.read_exact_at(output.as_mut(), range.start as u64)?;
404-
#[cfg(windows)]
405-
read_exact_at(file, output.as_mut(), range.start as u64)?;
406-
Ok(output)
407-
}))
408-
.await;
407+
let result = self
408+
.admitted_read
409+
.run(file, move |file| {
410+
#[cfg(unix)]
411+
file.read_exact_at(output.as_mut(), range.start as u64)?;
412+
#[cfg(windows)]
413+
read_exact_at(file, output.as_mut(), range.start as u64)?;
414+
Ok(output)
415+
})
416+
.await;
409417
metrics.record(&result, bytes);
410418
if result.is_ok() {
411419
io_tracker.record_read("get_range_into", path, bytes, Some(range_u64));
@@ -434,27 +442,30 @@ impl Reader for LocalObjectReader {
434442
}
435443
// One blocking dispatch, still one positional read and metric per
436444
// range. The closure owns every buffer even if its waiter is dropped.
437-
Ok(join_local_io(tokio::task::spawn_blocking(move || {
438-
let mut outputs = Vec::with_capacity(requests.len());
439-
for (range, mut output) in requests {
440-
let metrics = io_tracker.begin_io("get");
441-
#[cfg(unix)]
442-
let result = file.read_exact_at(output.as_mut(), range.start as u64);
443-
#[cfg(windows)]
444-
let result = read_exact_at(file.clone(), output.as_mut(), range.start as u64);
445-
metrics.record(&result, range.len() as u64);
446-
result?;
447-
io_tracker.record_read(
448-
"get_range_into",
449-
path.clone(),
450-
range.len() as u64,
451-
Some(range.start as u64..range.end as u64),
452-
);
453-
outputs.push(output);
454-
}
455-
Ok(outputs)
456-
}))
457-
.await?)
445+
Ok(self
446+
.admitted_read
447+
.run(file, move |file| {
448+
let mut outputs = Vec::with_capacity(requests.len());
449+
for (range, mut output) in requests {
450+
let metrics = io_tracker.begin_io("get");
451+
#[cfg(unix)]
452+
let result = file.read_exact_at(output.as_mut(), range.start as u64);
453+
#[cfg(windows)]
454+
let result =
455+
read_exact_at(file.clone(), output.as_mut(), range.start as u64);
456+
metrics.record(&result, range.len() as u64);
457+
result?;
458+
io_tracker.record_read(
459+
"get_range_into",
460+
path.clone(),
461+
range.len() as u64,
462+
Some(range.start as u64..range.end as u64),
463+
);
464+
outputs.push(output);
465+
}
466+
Ok(outputs)
467+
})
468+
.await?)
458469
})
459470
}
460471

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// SPDX-FileCopyrightText: Copyright The Lance Authors
3+
4+
//! Coordinate Linux owned reads to the same inode without parking an executor
5+
//! thread. Ordinary local reads do not consult this gate. The registry holds
6+
//! only weak metadata references, never file handles or payload allocations.
7+
8+
use std::fs::File;
9+
use std::sync::Arc;
10+
11+
#[cfg(target_os = "linux")]
12+
use std::{collections::HashMap, os::unix::fs::MetadataExt, sync::OnceLock, sync::Weak};
13+
#[cfg(target_os = "linux")]
14+
use tokio::sync::{Mutex, OnceCell};
15+
16+
use super::join_local_io;
17+
18+
#[derive(Debug, Default)]
19+
pub(super) struct ReadGate {
20+
#[cfg(target_os = "linux")]
21+
gate: OnceCell<Arc<Mutex<()>>>,
22+
}
23+
24+
#[cfg(target_os = "linux")]
25+
#[derive(Default)]
26+
struct Registry {
27+
gates: HashMap<(u64, u64), Weak<Mutex<()>>>,
28+
}
29+
30+
#[cfg(target_os = "linux")]
31+
impl Registry {
32+
fn get(&mut self, key: (u64, u64)) -> Arc<Mutex<()>> {
33+
self.gates.retain(|_, gate| gate.strong_count() != 0);
34+
// Reclaim metadata from a previous high-water mark as readers close.
35+
self.gates.shrink_to(self.gates.len().saturating_mul(2));
36+
if let Some(gate) = self.gates.get(&key).and_then(Weak::upgrade) {
37+
return gate;
38+
}
39+
let gate = Arc::new(Mutex::new(()));
40+
self.gates.insert(key, Arc::downgrade(&gate));
41+
gate
42+
}
43+
}
44+
45+
impl ReadGate {
46+
#[cfg(target_os = "linux")]
47+
async fn get(&self, file: Arc<File>) -> object_store::Result<Arc<Mutex<()>>> {
48+
self.gate
49+
.get_or_try_init(|| async move {
50+
join_local_io(tokio::task::spawn_blocking(move || {
51+
// fstat identifies the opened file, including hard links and
52+
// paths replaced after open. It runs only on first owned I/O.
53+
let metadata = file.metadata()?;
54+
static REGISTRY: OnceLock<std::sync::Mutex<Registry>> = OnceLock::new();
55+
let mut registry = REGISTRY
56+
.get_or_init(Default::default)
57+
.lock()
58+
.map_err(|_| std::io::Error::other("local read gate registry poisoned"))?;
59+
Ok(registry.get((metadata.dev(), metadata.ino())))
60+
}))
61+
.await
62+
})
63+
.await
64+
.cloned()
65+
}
66+
67+
pub(super) async fn run<T, F>(&self, file: Arc<File>, operation: F) -> object_store::Result<T>
68+
where
69+
T: Send + 'static,
70+
F: FnOnce(Arc<File>) -> std::io::Result<T> + Send + 'static,
71+
{
72+
#[cfg(target_os = "linux")]
73+
let guard = self.get(file.clone()).await?.lock_owned().await;
74+
join_local_io(tokio::task::spawn_blocking(move || {
75+
// Cancellation of the async waiter detaches this closure. Both the
76+
// gate and the caller's buffers must remain here until I/O ends.
77+
#[cfg(target_os = "linux")]
78+
let _guard = guard;
79+
operation(file)
80+
}))
81+
.await
82+
}
83+
}
84+
85+
#[cfg(all(test, target_os = "linux"))]
86+
mod tests;

0 commit comments

Comments
 (0)