Unverified Commit b677feb0 authored by Benjamin Woodruff ‮'s avatar Benjamin Woodruff Committed by GitHub

Turbopack: More aggressively debounce filesystem watch events if we detected…

Turbopack: More aggressively debounce filesystem watch events if we detected changes to node_modules (#96116)

Previously, we were debouncing update by sleeping 1ms at a time on macos
and windows, and 10ms at a time on Linux.

During a slow `pnpm install`, or a `git checkout`, this could cause us
to do a bunch of extra throwaway work.

Changes:
- Increase the debounce interval to a consistent 10ms everywhere. This
should still be small enough that it's not noticable on macos or
windows.
- If an event touches `node_modules`, there's a good chance that a
package manager is running and many other files will be modified, so
extend the batch deadline by 200ms instead of 10ms.
- Because there's a chance that the batch deadline could get extended
indefinitely (this was always possible, just more likely now) include a
compilation event that gets logged after 5 seconds.
parent dc5fe225
......@@ -93,7 +93,7 @@ use turbopack_node::child_process_backend;
use turbopack_node::execution_context::ExecutionContext;
#[cfg(feature = "worker_pool")]
use turbopack_node::worker_threads_backend;
use turbopack_nodejs::NodeJsChunkingContext;
use turbopack_nodejs::{NodeJsChunkingContext, fs::NodeModulesPathMatcher};
use crate::{
aggregate_hmr::{AggregateHmrVersion, ChunkListUpdateBuilder, DiffResult, diff_chunks_against},
......@@ -1094,10 +1094,13 @@ impl Project {
*self.root_path,
vec![denied_path, denied_profiles_path],
DiskWatcherConfig {
recursive_mode: None,
poll_interval: self.watch.poll_interval,
// the dev server reports these to the user
report_invalidation_reason: true,
extended_batch_delay_matcher: Some(ResolvedVc::upcast(
NodeModulesPathMatcher.resolved_cell(),
)),
..Default::default()
},
))
}
......
......@@ -496,6 +496,7 @@ export async function createHotReloaderTurbopack(
'StartupCacheInvalidationEvent',
'TimingEvent',
'SlowFilesystemEvent',
'FilesystemSettlingEvent',
'TraceEvent',
],
parentSpan: hotReloaderSpan,
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
// Importing this package makes Turbopack read (and therefore watch) the file
// inside `node_modules`, so the writes the test performs generate watcher
// events. This matters on Linux, where the watcher is non-recursive and only
// watches directories it has been asked to read.
import counter from 'fs-settling-fixture-pkg'
export default function Page() {
return <p>counter: {counter}</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
import fs from 'fs'
import path from 'path'
// The `FilesystemSettlingEvent` compilation event is Turbopack-only.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'fs-settling-event',
() => {
const { next } = nextTestSetup({ files: __dirname })
it('logs a settling event during sustained node_modules churn', async () => {
// Compile the page first so the imported `node_modules` file is watched.
await next.render('/')
const pkgFile = path.join(
next.testDir,
'node_modules/fs-settling-fixture-pkg/index.js'
)
const outputIndex = next.cliOutput.length
// Rewrite the imported module every 20ms. Since 20ms is well below the
// extended `node_modules` batch delay (200ms), the watcher keeps a single
// batch of events open, which triggers the settling event after ~5s.
let i = 0
const interval = setInterval(() => {
fs.writeFileSync(pkgFile, `export default ${i++}\n`)
}, 20)
try {
await retry(
() => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('waiting for the filesystem to settle')
},
// The event fires after ~5s; allow a generous window to avoid flakes.
15000,
500
)
} finally {
clearInterval(interval)
}
})
}
)
{
"name": "fs-settling-fixture-pkg",
"version": "1.0.0",
"main": "index.js"
}
......@@ -60,7 +60,7 @@ pub use crate::{
path::{FileSystemPath, FileSystemPathOption, RealPathResult, RealPathResultError, rebase},
read_glob::ReadGlobResult,
virtual_fs::VirtualFileSystem,
watcher::{DiskWatcherConfig, DiskWatcherRecursiveMode},
watcher::{DiskWatcherConfig, DiskWatcherPathMatcher, DiskWatcherRecursiveMode},
windows::to_verbatim_with_case_folded_disk,
};
......
use std::{
sync::{
Arc,
mpsc::{Receiver, RecvTimeoutError},
},
time::{Duration, Instant},
};
use serde::Serialize;
use turbo_tasks::message_queue::{CompilationEvent, Severity};
use crate::{DiskWatcherConfig, watcher::fs_api::DiskFileSystemWatcherApi};
/// Decides how long a batch of watcher events stays open, and emits a repeated
/// [`FilesystemSettlingEvent`] for as long as it does.
pub struct BatchSchedule {
settling_event_initial_delay: Duration,
settling_event_max_delay: Duration,
pending: Option<PendingBatch>,
}
/// A batch that has at least one event in it and hasn't been flushed yet.
struct PendingBatch {
started: Instant,
/// The batch is flushed once this passes without any further events.
deadline: Instant,
/// When to emit the next [`FilesystemSettlingEvent`].
settling_event_next_at: Instant,
/// Grows exponentially (up to [`BatchSchedule::settling_event_max_delay`]) so that a writer
/// holding a batch open for minutes doesn't flood the compilation event queue.
event_interval: Duration,
}
impl BatchSchedule {
pub fn new(config: &DiskWatcherConfig) -> Self {
Self {
settling_event_initial_delay: config.settling_event_initial_delay,
settling_event_max_delay: config.settling_event_max_delay,
pending: None,
}
}
/// Keeps the batch open for at least `delay` from now, opening a new batch if there isn't one.
pub fn extend(&mut self, delay: Duration) {
let now = Instant::now();
let deadline = now.checked_add(delay).unwrap_or_else(far_future);
match &mut self.pending {
Some(pending) => pending.deadline = pending.deadline.max(deadline),
None => {
self.pending = Some(PendingBatch {
started: now,
deadline,
settling_event_next_at: now
.checked_add(self.settling_event_initial_delay)
.unwrap_or_else(far_future),
event_interval: self.settling_event_initial_delay,
})
}
}
}
/// Waits for the next watcher event, emitting [`FilesystemSettlingEvent`]s while the pending
/// batch keeps growing. If no batch is pending, this blocks until an event arrives.
///
/// [`RecvTimeoutError::Timeout`] means the pending batch's deadline has passed *and* nothing
/// more is queued, so the batch is complete and should be flushed.
pub fn recv_event<FsApi: DiskFileSystemWatcherApi>(
&mut self,
rx: &Receiver<notify::Result<notify::Event>>,
fs: &FsApi,
) -> Result<notify::Result<notify::Event>, RecvTimeoutError> {
let max_event_delay = self.settling_event_max_delay;
loop {
let Some(pending) = &mut self.pending else {
// no pending batch: wait indefinitely
return rx.recv().map_err(|_| RecvTimeoutError::Disconnected);
};
let now = Instant::now();
if now >= pending.settling_event_next_at {
pending.emit_settling_event(fs, now, max_event_delay);
}
let timeout = pending
.deadline
.min(pending.settling_event_next_at)
.saturating_duration_since(now);
match rx.recv_timeout(timeout) {
Ok(event) => {
return Ok(event);
}
Err(RecvTimeoutError::Timeout) => {
if Instant::now() >= pending.deadline {
self.pending = None;
return Err(RecvTimeoutError::Timeout);
}
continue;
}
Err(err) => return Err(err),
}
}
}
/// Closes the pending batch, used when a rescan happens.
pub fn reset(&mut self) {
self.pending = None;
}
}
impl PendingBatch {
fn emit_settling_event<FsApi: DiskFileSystemWatcherApi>(
&mut self,
fs: &FsApi,
now: Instant,
max_event_delay: Duration,
) {
let _guard = fs.tokio_handle().enter();
if let Some(turbo_tasks) = fs.turbo_tasks() {
turbo_tasks.send_compilation_event(Arc::new(FilesystemSettlingEvent {
elapsed_secs: (now - self.started).as_secs_f64(),
}));
}
self.event_interval = self.event_interval.saturating_mul(2).min(max_event_delay);
// Schedule from "now" instead of accumulating intervals, so that emitting late (e.g. under
// heavy load) doesn't produce a catch-up burst of events.
self.settling_event_next_at = now
.checked_add(self.event_interval)
.unwrap_or_else(far_future);
}
}
/// Emitted when frequent filesystem updates cause us to keep a batch open for an extended period of
/// time. Informing the user when this happens may help them understand what's happening, and that
/// Turbopack is not stalled.
#[derive(Debug, Clone, Serialize)]
pub struct FilesystemSettlingEvent {
/// How long the current batch has been held open, in seconds.
pub elapsed_secs: f64,
}
impl CompilationEvent for FilesystemSettlingEvent {
fn type_name(&self) -> &'static str {
"FilesystemSettlingEvent"
}
fn severity(&self) -> Severity {
Severity::Info
}
fn message(&self) -> String {
format!(
"Turbopack has seen frequent file updates and is waiting for the filesystem to settle \
({:.1}s elapsed so far).",
self.elapsed_secs
)
}
fn to_json(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
// from https://github.com/tokio-rs/tokio/blob/29cd6ec1ec6f90a7ee1ad641c03e0e00badbcb0e/tokio/src/time/instant.rs#L57-L63
fn far_future() -> Instant {
// Roughly 30 years from now.
// API does not provide a way to obtain max `Instant`
// or convert specific date in the future to instant.
// 1000 years overflows on macOS, 100 years overflows on FreeBSD.
Instant::now() + Duration::from_secs(86400 * 365 * 30)
}
mod batch_schedule;
mod fs_api;
#[cfg(test)]
mod mock_fs_api;
......@@ -11,7 +12,7 @@ use std::{
Arc, LazyLock,
mpsc::{Receiver, RecvTimeoutError, channel},
},
time::{Duration, Instant},
time::Duration,
};
use anyhow::{Context, Result};
......@@ -31,7 +32,7 @@ use tokio::sync::{RwLock, RwLockWriteGuard};
use tracing::instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{
FxIndexSet, InvalidationReason, InvalidationReasonKind, Invalidator, NonLocalValue, TaskInput,
FxIndexSet, InvalidationReason, InvalidationReasonKind, Invalidator, ResolvedVc, TraitRef,
TurboTasksApi, spawn_thread, trace::TraceRawVcs, util::StaticOrArc,
};
......@@ -40,7 +41,7 @@ use crate::{
invalidation::{WatchChange, WatchStart},
invalidator_map::InvalidatorMap,
path_map::OrderedPathMapExt,
watcher::fs_api::DiskFileSystemWatcherApi,
watcher::{batch_schedule::BatchSchedule, fs_api::DiskFileSystemWatcherApi},
};
/// Overrides [`DiskWatcherConfig::recursive_mode`]. Users shouldn't need to set this, this is
......@@ -59,9 +60,8 @@ static FORCED_WATCH_RECURSIVE_MODE: LazyLock<Option<DiskWatcherRecursiveMode>> =
},
);
#[derive(
Clone, Copy, Debug, Default, Eq, PartialEq, Hash, TraceRawVcs, NonLocalValue, Encode, Decode,
)]
#[turbo_tasks::task_input]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, TraceRawVcs, Encode, Decode)]
pub struct DiskWatcherConfig {
/// Whether to let the [`notify::Watcher`] recurse into subdirectories itself, or to track and
/// watch each directory we care about ourselves.
......@@ -85,14 +85,54 @@ pub struct DiskWatcherConfig {
/// This costs an extra allocation per invalidated path, so it's only worth enabling when
/// something actually consumes the reasons.
pub report_invalidation_reason: bool,
/// How long to keep a batch of filesystem events open, waiting for more events, before
/// flushing invalidations. Batching coalesces bursts (e.g. a `git checkout`) into a single
/// invalidation pass and avoids reading half-written files.
///
/// If set too low (<10ms), this is known to cause partial file reads on Linux where `inotify`
/// has very low latency.
pub batch_delay: Duration,
/// When [`DiskWatcherPathMatcher::match_path`] returns `true`, we will extend the batch by
/// [`Self::extended_batch_delay_duration`].
pub extended_batch_delay_matcher: Option<ResolvedVc<Box<dyn DiskWatcherPathMatcher>>>,
/// The idle period required to close a batch once [`Self::extended_batch_delay_matcher`] has
/// matched. Unused when there is no matcher.
pub extended_batch_delay_duration: Duration,
/// If a single batch stays open at least this long, emit a `FilesystemSettlingEvent`
/// compilation event so the user knows why work has stalled. Repeated events within the same
/// batch back off exponentially, up to [`Self::settling_event_max_delay`].
pub settling_event_initial_delay: Duration,
/// Upper bound for the exponentially increasing interval between repeated
/// `FilesystemSettlingEvent`s within a single batch.
pub settling_event_max_delay: Duration,
}
impl TaskInput for DiskWatcherConfig {
fn is_transient(&self) -> bool {
false
impl Default for DiskWatcherConfig {
fn default() -> Self {
Self {
recursive_mode: None,
poll_interval: None,
report_invalidation_reason: false,
batch_delay: Duration::from_millis(10),
extended_batch_delay_matcher: None,
extended_batch_delay_duration: Duration::from_millis(200),
settling_event_initial_delay: Duration::from_millis(500),
settling_event_max_delay: Duration::from_secs(60),
}
}
}
/// Matches absolute paths reported by the filesystem watcher. See
/// [`DiskWatcherConfig::extended_batch_delay_matcher`].
#[turbo_tasks::value_trait]
pub trait DiskWatcherPathMatcher {
/// Called on the watcher thread once per path of every incoming event, so this should be
/// cheap and must not block.
fn match_path(&self, path: &Path) -> bool;
}
/// Equivalent to [`notify::RecursiveMode`], but implements traits needed by [`turbo_tasks`].
///
/// When using [`Self::Recursive`], [`notify::Watcher`] will recursively track all contents
......@@ -101,7 +141,8 @@ impl TaskInput for DiskWatcherConfig {
///
/// When using [`Self::NonRecursive`], we only track previously read files and their parent
/// directories.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, TraceRawVcs, NonLocalValue, Encode, Decode)]
#[turbo_tasks::task_input]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, TraceRawVcs, Encode, Decode)]
pub enum DiskWatcherRecursiveMode {
Recursive,
NonRecursive,
......@@ -147,15 +188,6 @@ impl DiskWatcherConfig {
}
}
/// How long to extend an invalidation batch by when receiving new events, before flushing. This
/// reduces invalidations if the same file or directory is modified many times.
///
/// Linux watching is too fast, so we need a longer delay there to avoid reading wip files.
#[cfg(target_os = "linux")]
const BATCH_DELAY: Duration = Duration::from_millis(10);
#[cfg(not(target_os = "linux"))]
const BATCH_DELAY: Duration = Duration::from_millis(1);
pub(crate) struct DiskWatcher {
state: State,
config: DiskWatcherConfig,
......@@ -451,6 +483,10 @@ mod non_recursive_helpers {
impl DiskWatcher {
pub fn new(config: DiskWatcherConfig) -> Self {
assert!(
config.extended_batch_delay_duration >= config.batch_delay,
"extended_batch_delay_duration must be at least batch_delay"
);
Self {
state: State::new_stopped(config.resolve_recursive_mode()),
config,
......@@ -459,6 +495,13 @@ impl DiskWatcher {
pub async fn start_watching<FsApi: DiskFileSystemWatcherApi>(fs: Arc<FsApi>) -> Result<()> {
let watcher: &Self = fs.watcher();
// read in the turbo-task context and before acquiring the lock
let extended_batch_delay_matcher = match watcher.config.extended_batch_delay_matcher {
Some(matcher) => Some(matcher.into_trait_ref().await?),
None => None,
};
let state_guard = watcher.state.write().await;
// bail out if we're already watching
......@@ -513,7 +556,7 @@ impl DiskWatcher {
spawn_thread({
let fs = fs.clone();
move || Self::watch_thread(fs, rx)
move || Self::watch_thread(fs, rx, extended_batch_delay_matcher)
});
// Updating `self.state` is done last. If we panic while setting up the watcher, it'll
......@@ -551,24 +594,20 @@ impl DiskWatcher {
fn watch_thread<FsApi: DiskFileSystemWatcherApi>(
fs: Arc<FsApi>,
rx: Receiver<notify::Result<notify::Event>>,
extended_batch_delay_matcher: Option<TraitRef<Box<dyn DiskWatcherPathMatcher>>>,
) {
let watcher: &Self = fs.watcher();
let report_invalidation_reason = watcher.config.report_invalidation_reason;
let config = &watcher.config;
let report_invalidation_reason = config.report_invalidation_reason;
let mut batch = BatchedInvalidations::new(
watcher.state.recursive_mode(),
watcher.config.poll_interval.is_some(),
config.poll_interval.is_some(),
);
let mut schedule = BatchSchedule::new(config);
'outer: loop {
let mut deadline: Option<Instant> = None;
loop {
let event_result = match deadline {
None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected),
Some(deadline) => {
rx.recv_timeout(deadline.saturating_duration_since(Instant::now()))
}
};
match event_result {
match schedule.recv_event(&rx, &*fs) {
Ok(Ok(event)) => {
// TODO: We might benefit from some user-facing diagnostics if it rescans
// occur frequently (i.e. more than X times in Y minutes)
......@@ -613,13 +652,23 @@ impl DiskWatcher {
// no need to process the rest of the batch as we just
// invalidated everything
batch.clear();
schedule.reset();
break;
}
// Only an event that contributes to the batch keeps it open for another
// `BATCH_DELAY`.
// Any event that contributes to the batch keeps it open for another
// `batch_delay`. A path matching `extended_batch_delay_matcher` (e.g. a
// package-manager install target) keeps it open for
// `extended_batch_delay_duration` instead.
let mut delay = config.batch_delay;
if let Some(matcher) = &extended_batch_delay_matcher
&& event.paths.iter().any(|path| matcher.match_path(path))
{
delay = delay.max(config.extended_batch_delay_duration);
}
if batch.add_event(event) {
deadline = Some(Instant::now() + BATCH_DELAY);
schedule.extend(delay);
}
}
// Error raised by notify watcher itself
......@@ -629,16 +678,16 @@ impl DiskWatcher {
let flags = InvalidationFlags::PATH_AND_CHILDREN
| InvalidationFlags::PATH_AND_CHILDREN_DIR;
if paths.is_empty() {
batch.mark(fs.root_path().into(), flags);
batch.mark(Box::from(fs.root_path()), flags);
} else {
for path in paths {
batch.mark(path.into_boxed_path(), flags);
}
}
deadline = Some(Instant::now() + BATCH_DELAY);
schedule.extend(config.batch_delay);
}
Err(RecvTimeoutError::Timeout) => {
// The batch is complete: break out to invalidate the collected paths.
// the batch is complete: break out to invalidate the collected paths.
break;
}
Err(RecvTimeoutError::Disconnected) => {
......@@ -1016,7 +1065,10 @@ impl InvalidationReasonKind for InvalidateRescanKind {
#[cfg(test)]
mod tests {
use std::{fs, time::SystemTime};
use std::{
fs,
time::{Instant, SystemTime},
};
use rstest::rstest;
use turbo_tasks::TurboTasks;
......@@ -1078,6 +1130,7 @@ mod tests {
recursive_mode: Some(recursive_mode),
poll_interval,
report_invalidation_reason: true,
..Default::default()
});
let sub_dir = fs.root_path.join("sub");
let file_path = sub_dir.join("file.txt");
......
use std::{
ffi::OsStr,
path::{Component, Path},
};
use turbo_tasks_fs::DiskWatcherPathMatcher;
/// Matches anything inside of a `node_modules` directory.
///
/// Package managers churn `node_modules` heavily while the dev server is running. More aggressively
/// batching these may reduce system load during an installation.
#[turbo_tasks::value(shared)]
pub struct NodeModulesPathMatcher;
#[turbo_tasks::value_impl]
impl DiskWatcherPathMatcher for NodeModulesPathMatcher {
fn match_path(&self, path: &Path) -> bool {
path.components()
.any(|component| component == Component::Normal(OsStr::new("node_modules")))
}
}
......@@ -3,5 +3,6 @@
pub(crate) mod chunking_context;
pub mod ecmascript;
pub mod fs;
pub use chunking_context::{NodeJsChunkingContext, NodeJsChunkingContextBuilder};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment