Skip to content

Commit da620e6

Browse files
authored
perf(linter): start tsgolint before the regular lint pass (#28824)
- #28179 oxlint runs its own rules first and only then starts tsgolint, so the two times add up even though the regular pass leaves most cores idle. this starts tsgolint first and only waits for it after the regular pass. its diagnostics still get filtered by the disable directives the regular pass collects, which is the reason they went sequential here: - #14052 with fixes on (`--fix` and friends) it stays sequential since the regular pass rewrites files tsgolint reads large private app with js plugins, 16 vcpu box, main vs this, 15 alternating runs: 26.7 -> 20.2 s (−24.5%), same instructions, identical output tradeoff is memory: tsgolint and the regular pass are alive at the same time now, so peak memory is roughly both added up written with help from an AI assistant (Claude)
1 parent 582b575 commit da620e6

3 files changed

Lines changed: 143 additions & 18 deletions

File tree

‎crates/oxc_linter/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ pub use crate::{
9595
service::{LintService, LintServiceOptions, OsFileSystem, RuntimeFileSystem},
9696
suppression::{OxlintSuppressionFileAction, SuppressionManager},
9797
timing::{RuleTimingRecord, RuleTimingSource, RuleTimingStore},
98-
tsgolint::TsGoLintState,
98+
tsgolint::{TsGoLintRun, TsGoLintState},
9999
utils::{read_to_arena_str, read_to_string},
100100
};
101101
use crate::{

‎crates/oxc_linter/src/lint_runner.rs‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ pub struct LintRunner {
2626
/// Current working directory
2727
cwd: PathBuf,
2828
type_check_only: bool,
29+
/// The regular pass writes fixed files, so type-aware linting must wait until it is done to
30+
/// read them.
31+
regular_pass_writes_files: bool,
2932
}
3033

3134
/// Manages disable directives across all linting engines.
@@ -239,6 +242,7 @@ impl LintRunnerBuilder {
239242
};
240243

241244
let cwd = self.lint_service_options.cwd().to_path_buf();
245+
let regular_pass_writes_files = self.regular_linter.options().fix.is_some();
242246
let mut lint_service = LintService::new(self.regular_linter, self.lint_service_options);
243247
lint_service.set_disable_directives_map(directives_coordinator.map());
244248

@@ -248,6 +252,7 @@ impl LintRunnerBuilder {
248252
directives_store: directives_coordinator,
249253
cwd,
250254
type_check_only: self.type_check_only,
255+
regular_pass_writes_files,
251256
})
252257
}
253258
}
@@ -270,6 +275,13 @@ impl LintRunner {
270275
) -> Result<Self, String> {
271276
let fs: &(dyn crate::RuntimeFileSystem + Sync + Send) = &OsFileSystem;
272277

278+
// Start type-aware linting first so it runs alongside the regular pass. Its diagnostics
279+
// are only filtered and reported after the regular pass has collected disable directives.
280+
let mut type_aware_run = None;
281+
if !self.regular_pass_writes_files {
282+
type_aware_run = self.type_aware_linter.take().map(|linter| linter.start(files));
283+
}
284+
273285
if self.type_check_only {
274286
self.lint_service.collect_parse_diagnostics(fs, files.to_owned(), &tx_error);
275287
} else {
@@ -282,9 +294,10 @@ impl LintRunner {
282294
);
283295
}
284296

285-
if let Some(type_aware_linter) = self.type_aware_linter.take() {
286-
type_aware_linter.lint(
287-
files,
297+
let type_aware_run = type_aware_run
298+
.or_else(|| self.type_aware_linter.take().map(|linter| linter.start(files)));
299+
if let Some(type_aware_run) = type_aware_run {
300+
type_aware_run.finish(
288301
self.directives_store.map(),
289302
tx_error,
290303
fs,

‎crates/oxc_linter/src/tsgolint.rs‎

Lines changed: 126 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ use std::{
55
io::{ErrorKind, Read, Write, stderr},
66
iter, mem,
77
path::{Path, PathBuf},
8-
sync::{Arc, Mutex},
8+
process::Child,
9+
sync::{Arc, Mutex, mpsc},
10+
thread::JoinHandle,
911
time::Duration,
1012
};
1113

@@ -136,6 +138,9 @@ impl TsGoLintState {
136138
self
137139
}
138140

141+
/// Runs `tsgolint` on `paths` to completion. Equivalent to [`Self::start`] followed by
142+
/// [`TsGoLintRun::finish`].
143+
///
139144
/// # Panics
140145
/// - when `stdin` of subprocess cannot be opened
141146
/// - when `stdout` of subprocess cannot be opened
@@ -152,15 +157,35 @@ impl TsGoLintState {
152157
diff_manager: &Arc<DiffManager>,
153158
rule_timing_store: Option<&RuleTimingStore>,
154159
) -> Result<(), String> {
160+
self.start(paths).finish(
161+
disable_directives_map,
162+
error_sender,
163+
file_system,
164+
diff_manager,
165+
rule_timing_store,
166+
)
167+
}
168+
169+
/// Spawns `tsgolint` for `paths` and decodes its output on a background thread, so it can
170+
/// run while the regular lint pass does.
171+
///
172+
/// Nothing is reported until [`TsGoLintRun::finish`], which must run after the regular pass:
173+
/// diagnostics are filtered by the disable directives that pass collects. Spawn errors are
174+
/// reported by `finish` as well.
175+
///
176+
/// # Panics
177+
/// - when `stdin` of subprocess cannot be opened
178+
/// - when `stdout` of subprocess cannot be opened
179+
pub fn start(self, paths: &[Arc<OsStr>]) -> TsGoLintRun {
155180
if paths.is_empty() {
156-
return Ok(());
181+
return TsGoLintRun { started: None };
157182
}
158183

159184
let mut resolved_configs: FxHashMap<PathBuf, ResolvedLinterState> = FxHashMap::default();
160185

161186
let json_input = self.json_input(paths, None, &mut resolved_configs);
162187
if json_input.configs.is_empty() {
163-
return Ok(());
188+
return TsGoLintRun { started: None };
164189
}
165190

166191
let all_paths = {
@@ -174,29 +199,97 @@ impl TsGoLintState {
174199
paths_buff
175200
};
176201

177-
let should_fix = self.fix || self.fix_suggestions;
178-
let cwd = self.cwd.clone();
202+
let process = self.spawn_tsgolint(&json_input).map(|mut child| {
203+
let stdout = child.stdout.take().expect("Failed to open tsgolint stdout");
204+
let (sender, messages) = mpsc::channel();
205+
// Drain stdout as it is written so `tsgolint` never blocks on a full pipe. Message
206+
// processing stops at the first error, so stop reading there too.
207+
let reader = std::thread::spawn(move || {
208+
for msg in TsGoLintMessageStream::new(stdout) {
209+
let is_error = !matches!(
210+
msg,
211+
Ok(TsGoLintMessage::Diagnostic(_) | TsGoLintMessage::Timing(_))
212+
);
213+
if sender.send(msg).is_err() || is_error {
214+
break;
215+
}
216+
}
217+
});
218+
TsGoLintProcess { child, messages, reader }
219+
});
220+
221+
TsGoLintRun {
222+
started: Some(StartedRun { state: self, resolved_configs, all_paths, process }),
223+
}
224+
}
225+
}
226+
227+
/// A `tsgolint` run started by [`TsGoLintState::start`].
228+
pub struct TsGoLintRun {
229+
/// `None` when there was nothing to lint.
230+
started: Option<StartedRun>,
231+
}
232+
233+
struct StartedRun {
234+
state: TsGoLintState,
235+
resolved_configs: FxHashMap<PathBuf, ResolvedLinterState>,
236+
all_paths: Vec<PathBuf>,
237+
/// The spawned process, or the error from spawning it.
238+
process: Result<TsGoLintProcess, String>,
239+
}
240+
241+
struct TsGoLintProcess {
242+
child: Child,
243+
/// Messages decoded from stdout by `reader`, in the order `tsgolint` wrote them.
244+
messages: mpsc::Receiver<Result<TsGoLintMessage, String>>,
245+
reader: JoinHandle<()>,
246+
}
247+
248+
impl TsGoLintRun {
249+
/// Waits for `tsgolint` to exit and reports its diagnostics, filtered by the disable
250+
/// directives that the regular lint pass collected, then applies its fixes.
251+
///
252+
/// # Panics
253+
/// - when `tsgolint` process cannot be awaited
254+
///
255+
/// # Errors
256+
/// A human-readable error message indicating why the linting failed.
257+
pub fn finish(
258+
mut self,
259+
disable_directives_map: Arc<Mutex<FxHashMap<PathBuf, DisableDirectives>>>,
260+
error_sender: DiagnosticSender,
261+
file_system: &(dyn crate::RuntimeFileSystem + Sync + Send),
262+
diff_manager: &Arc<DiffManager>,
263+
rule_timing_store: Option<&RuleTimingStore>,
264+
) -> Result<(), String> {
265+
let Some(StartedRun { state, resolved_configs, all_paths, process }) = self.started.take()
266+
else {
267+
return Ok(());
268+
};
269+
270+
let should_fix = state.fix || state.fix_suggestions;
271+
let cwd = state.cwd.clone();
179272
let sender_for_fixes = error_sender.clone();
180273

181274
let diff_manager_clone_to_ts_go = Arc::<DiffManager>::clone(diff_manager);
182275

183276
let handler = std::thread::spawn(move || {
184-
let mut child = self.spawn_tsgolint(&json_input)?;
185-
186-
let stdout = child.stdout.take().expect("Failed to open tsgolint stdout");
277+
let TsGoLintProcess { mut child, messages, reader } = process?;
187278

188-
// Process stdout stream in a separate thread to send diagnostics as they arrive
279+
// Process messages in a separate thread to send diagnostics as they arrive
189280
let stdout_handler = std::thread::spawn(move || -> Result<TsGoLintOutput, String> {
190281
let disable_directives_map =
191282
disable_directives_map.lock().expect("disable_directives_map mutex poisoned");
192283

193-
let mut diagnostic_handler =
194-
DiagnosticHandler::new(self.cwd.clone(), self.silent, should_fix, error_sender);
284+
let mut diagnostic_handler = DiagnosticHandler::new(
285+
state.cwd.clone(),
286+
state.silent,
287+
should_fix,
288+
error_sender,
289+
);
195290
let mut timings = vec![];
196291

197-
let msg_iter = TsGoLintMessageStream::new(stdout);
198-
199-
for msg in msg_iter {
292+
for msg in messages {
200293
match msg {
201294
Ok(TsGoLintMessage::Error(err)) => {
202295
return Err(err.error);
@@ -260,6 +353,12 @@ impl TsGoLintState {
260353
}
261354
}
262355

356+
// The channel also closes when decoding panicked. Fail this thread then, as it
357+
// did when it decoded stdout itself.
358+
if let Err(panic) = reader.join() {
359+
std::panic::resume_unwind(panic);
360+
}
361+
263362
Ok(TsGoLintOutput {
264363
messages_requiring_fixes: diagnostic_handler
265364
.into_messages_requiring_fixes(&diff_manager_clone_to_ts_go, all_paths),
@@ -356,7 +455,20 @@ impl TsGoLintState {
356455
Err(err) => Err(format!("Error running tsgolint: {err:?}")),
357456
}
358457
}
458+
}
359459

460+
impl Drop for TsGoLintRun {
461+
/// Stops `tsgolint` when the run is dropped without [`TsGoLintRun::finish`] (e.g. the regular
462+
/// pass unwound), so the process does not outlive the run.
463+
fn drop(&mut self) {
464+
if let Some(StartedRun { process: Ok(process), .. }) = &mut self.started {
465+
let _ = process.child.kill();
466+
let _ = process.child.wait();
467+
}
468+
}
469+
}
470+
471+
impl TsGoLintState {
360472
/// Spawn the tsgolint process with the given input.
361473
fn spawn_tsgolint(&self, json_input: &Payload) -> Result<std::process::Child, String> {
362474
let mut cmd = std::process::Command::new(&self.executable_path);

0 commit comments

Comments
 (0)