From 5cd4b61bc7e572ed278816eb0214374a1b0f0275 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 5 Dec 2026 12:11:05 +0900 Subject: [PATCH 1/6] perf(binding): extract a batch on worker threads with in-order numbering Class names are numbered first come, first served, so extraction had to run one file at a time. A file now takes an ordered turn: its first class or file number waits until every earlier file has finished naming, and the turn passes as soon as the outermost extraction reaches code generation. A file that names anything after its turn passed (or reads a file number another file may still add) is marked out of order; the batch then restores a snapshot of the class, file and reservation state and extracts one by one. The new core `extract_batch` runs sources on scoped worker threads, asks the host resolver on the calling thread once per (specifier, importer), commits the outputs in source order and stays sequential under atom hoisting or with one thread. Existing single-file extraction is unchanged: outside a turn the hooks do nothing. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_numbering_order.json | 8 + libs/binding/src/batch.rs | 432 +++++++++++++++ libs/binding/src/batch/tests.rs | 37 ++ libs/binding/src/lib.rs | 4 + libs/binding/tests/batch.rs | 499 ++++++++++++++++++ libs/css/src/file_map.rs | 2 + libs/css/src/lib.rs | 2 + libs/css/src/numbering_order.rs | 183 +++++++ libs/css/src/numbering_order/tests.rs | 142 +++++ libs/css/src/slot_reservation.rs | 4 + libs/extractor/src/lib.rs | 3 + 11 files changed, 1316 insertions(+) create mode 100644 .changepacks/changepack_log_numbering_order.json create mode 100644 libs/binding/src/batch.rs create mode 100644 libs/binding/src/batch/tests.rs create mode 100644 libs/binding/tests/batch.rs create mode 100644 libs/css/src/numbering_order.rs create mode 100644 libs/css/src/numbering_order/tests.rs diff --git a/.changepacks/changepack_log_numbering_order.json b/.changepacks/changepack_log_numbering_order.json new file mode 100644 index 000000000..50b941573 --- /dev/null +++ b/.changepacks/changepack_log_numbering_order.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch" + }, + "note": "Let extraction run on several threads while class names stay numbered as one by one in order would: the first name a file hands out waits for every earlier file to finish naming, and a file that names anything after its turn passed is extracted again in order. Add a core batch extractor that runs sources on worker threads, asks the module resolver on the calling thread once per import and importer, and falls back to one by one under atom hoisting. No behaviour change for existing callers: the generated CSS, class names and exported maps are byte-identical.", + "date": "2026-12-05T00:00:00.000Z" +} diff --git a/libs/binding/src/batch.rs b/libs/binding/src/batch.rs new file mode 100644 index 000000000..404a121da --- /dev/null +++ b/libs/binding/src/batch.rs @@ -0,0 +1,432 @@ +//! Extract many sources at once, as extracting them one by one in their order +//! would, but on several threads. +//! +//! Worker threads take the sources in order and extract them at once, each +//! numbering classes and files only in its turn (see +//! [`css::numbering_order`]), so every number comes out as one by one. The +//! calling thread, the only one that may run the host's module resolver, +//! answers the workers' resolver requests, then commits the outputs to the +//! stylesheet in source order. An extraction that numbered out of its turn +//! sends the whole batch back to extracting one by one. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, Sender, SyncSender, channel, sync_channel}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::thread::{Builder, Scope, ScopedJoinHandle}; + +use css::numbering_order::{Snapshot, Turn}; +use extractor::{ + ExtractOption, ExtractOutput, ResolvedModule, extract, extract_with_modules, + extract_without_source_map, +}; + +use crate::output::{CssOptions, Output, SourceMapMode}; +use crate::resolver_state::{ResolverState, resolved_module}; + +/// Worker stacks: the build-time evaluator recurses deeply. +const STACK_SIZE: usize = 16 * 1024 * 1024; + +/// Past this many workers the resolver on the calling thread is the bottleneck. +const MAX_DEFAULT_THREADS: usize = 8; + +/// Workers to use when the caller names none: the cores, at most eight. +#[must_use] +pub fn default_threads() -> usize { + std::thread::available_parallelism() + .map_or(1, std::num::NonZero::get) + .min(MAX_DEFAULT_THREADS) +} + +/// One source of a batch: its name, its code and the directory its CSS goes to. +pub struct BatchSource { + pub filename: String, + pub code: String, + pub css_dir: String, +} + +/// What every source of a batch is extracted with. +pub struct BatchOptions { + /// The extraction options; each source's `css_dir` replaces theirs. + pub option: ExtractOption, + pub source_map: SourceMapMode, + /// Import the main stylesheet from emitted file CSS. + pub import_main_css_in_css: bool, + /// Worker threads to extract on; below two, the batch extracts one by one. + pub threads: usize, +} + +/// What the host's module resolver answered. +#[derive(Clone)] +pub enum HostAnswer { + /// The module the import resolves to. + Module { path: String, code: String }, + /// The resolver's own failure, reported at the import. + Failed(String), + /// The import names no module the resolver knows. + Unresolved, + /// Calling the resolver failed; the extraction fails with this error. + Transport(String), +} + +/// Asks the host to resolve an import, on the thread that holds it. +pub type Ask = Rc HostAnswer>; + +/// The outputs of a batch, in source order. Outputs keep no CSS: committing +/// the next source changes the sheet, and a batch serializes none. +pub struct Batch { + pub outputs: Vec>, + /// Whether the sources were extracted on worker threads. + pub parallel: bool, +} + +/// What a worker tells the calling thread. +enum Event { + /// Resolve an import and send the answer back. + Resolve { + specifier: String, + importer: String, + reply: SyncSender, + }, + /// A source is extracted, numbering only in its turn or not. + Extracted { + index: usize, + result: Result, + in_order: bool, + }, +} + +/// Ask the calling thread to resolve an import and wait for its answer. +fn ask_remote(events: &Sender, specifier: &str, importer: &str) -> HostAnswer { + let (reply, answer) = sync_channel(1); + let event = Event::Resolve { + specifier: specifier.to_string(), + importer: importer.to_string(), + reply, + }; + let dropped = || HostAnswer::Transport("module resolver request was dropped".to_string()); + events.send(event).map_or_else( + |_| dropped(), + |()| answer.recv().unwrap_or_else(|_| dropped()), + ) +} + +/// The host's answers in this batch, by import and importer. The resolver +/// answers alike while the batch runs, so workers ask for each import once. +type Answers = Mutex>; + +/// The host's answer for an import, asked of the calling thread only once. +fn ask_once( + answers: &Answers, + events: &Sender, + specifier: &str, + importer: &str, +) -> HostAnswer { + let key = (specifier.to_string(), importer.to_string()); + let known = answers + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(&key) + .cloned(); + known.unwrap_or_else(|| { + let answer = ask_remote(events, specifier, importer); + // A transport failure is no answer + if !matches!(answer, HostAnswer::Transport(_)) { + answers + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(key, answer.clone()); + } + answer + }) +} + +/// Resolve an import through `ask`, keeping the diagnostics a resolver failure +/// reports and the first transport failure, as a single extraction does. +fn resolve( + (diagnostics, transport): (&RefCell, &RefCell>), + ask: &Ask, + specifier: &str, + importer: &str, +) -> Option { + let request = diagnostics.borrow().request(specifier, importer)?; + let cause = match ask(specifier, importer) { + HostAnswer::Module { path, code } => match resolved_module(path, code) { + Ok(module) => { + diagnostics.borrow_mut().cache(&module, &request); + return Some(module); + } + Err(cause) => cause, + }, + HostAnswer::Failed(cause) => cause, + HostAnswer::Unresolved => return None, + HostAnswer::Transport(error) => { + transport.borrow_mut().get_or_insert(error); + return None; + } + }; + diagnostics.borrow_mut().record(&request, &cause); + None +} + +/// Extract one source, its imports resolved through `ask` when given. +fn extract_source( + source: &BatchSource, + options: &BatchOptions, + ask: Option<&Ask>, +) -> Result { + let option = ExtractOption { + css_dir: source.css_dir.clone(), + ..options.option.clone() + }; + let (filename, code) = (source.filename.as_str(), source.code.as_str()); + let source_map = matches!(options.source_map, SourceMapMode::Generate); + let Some(ask) = ask else { + let extracted = if source_map { + extract(filename, code, option) + } else { + extract_without_source_map(filename, code, option) + }; + return extracted.map_err(|error| error.to_string()); + }; + let diagnostics = Rc::new(RefCell::new(ResolverState::new(filename, code))); + let transport = Rc::new(RefCell::new(None)); + let resolver = { + let (diagnostics, transport, ask) = ( + Rc::clone(&diagnostics), + Rc::clone(&transport), + Rc::clone(ask), + ); + move |specifier: &str, importer: &str| { + resolve((&diagnostics, &transport), &ask, specifier, importer) + } + }; + let extracted = extract_with_modules(filename, code, option, source_map, &resolver); + if let Some(error) = transport.take() { + return Err(error); + } + diagnostics.borrow().check()?; + extracted.map_err(|error| error.to_string()) +} + +/// Whose turn it is to number: the first source that has not passed it on. +struct Turns { + passed: Mutex<(usize, Vec)>, + changed: Condvar, +} + +impl Turns { + fn new(sources: usize) -> Self { + Self { + passed: Mutex::new((0, vec![false; sources])), + changed: Condvar::new(), + } + } + + fn lock(&self) -> MutexGuard<'_, (usize, Vec)> { + self.passed.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Wait until every source before `index` passed its turn on. + fn wait(&self, index: usize) { + drop( + self.changed + .wait_while(self.lock(), |passed| passed.0 < index) + .unwrap_or_else(PoisonError::into_inner), + ); + } + + /// Pass the turn of `index` on. + fn pass(&self, index: usize) { + let mut passed = self.lock(); + passed.1[index] = true; + while passed.1.get(passed.0) == Some(&true) { + passed.0 += 1; + } + drop(passed); + self.changed.notify_all(); + } + + /// The turn of source `index`, for the thread that extracts it. + fn turn(self: &Arc, index: usize) -> Turn { + let (waiting, passing) = (Arc::clone(self), Arc::clone(self)); + Turn::begin(move || waiting.wait(index), move || passing.pass(index)) + } +} + +/// Extract the sources a worker takes, in order, until none are left. +fn work( + sources: &[BatchSource], + options: &BatchOptions, + (next, turns, answers): (&AtomicUsize, &Arc, &Arc), + (events, resolves): (Sender, bool), +) { + let ask = resolves.then(|| { + let (events, answers) = (events.clone(), Arc::clone(answers)); + Rc::new(move |specifier: &str, importer: &str| { + ask_once(&answers, &events, specifier, importer) + }) as Ask + }); + loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(source) = sources.get(index) else { + break; + }; + let turn = turns.turn(index); + let result = extract_source(source, options, ask.as_ref()); + let in_order = turn.finish(); + // The calling thread receives until every worker is done + let _ = events.send(Event::Extracted { + index, + result, + in_order, + }); + } +} + +/// Answer the workers' requests until every worker is done, returning what +/// they extracted in source order and whether all of it numbered in turn. +fn serve( + events: &Receiver, + ask: Option<&Ask>, + sources: usize, +) -> (Vec>>, bool) { + let mut extracted: Vec>> = + (0..sources).map(|_| None).collect(); + let mut in_order = true; + for event in events { + match event { + Event::Resolve { + specifier, + importer, + reply, + } => { + let answer = ask.map_or(HostAnswer::Unresolved, |ask| ask(&specifier, &importer)); + // A worker waits for every answer it asks for + let _ = reply.send(answer); + } + Event::Extracted { + index, + result, + in_order: ordered, + } => { + extracted[index] = Some(result); + in_order &= ordered; + } + } + } + (extracted, in_order) +} + +/// Start up to `threads` workers. +fn spawn<'scope>( + scope: &'scope Scope<'scope, '_>, + threads: usize, + events: &Sender, + run: &'scope (dyn Fn(Sender) + Sync), +) -> Vec> { + (0..threads) + .filter_map(|_| { + let events = events.clone(); + Builder::new() + .stack_size(STACK_SIZE) + .spawn_scoped(scope, move || run(events)) + .ok() + }) + .collect() +} + +/// Every source extracted on worker threads, or `None` when one numbered out +/// of its turn or no worker extracted it. +fn extract_parallel( + sources: &[BatchSource], + options: &BatchOptions, + ask: Option<&Ask>, +) -> Option>> { + let next = AtomicUsize::new(0); + let turns = Arc::new(Turns::new(sources.len())); + let answers = Arc::new(Answers::default()); + let resolves = ask.is_some(); + let run = |events: Sender| { + work( + sources, + options, + (&next, &turns, &answers), + (events, resolves), + ); + }; + let (sender, events) = channel(); + let (extracted, in_order) = std::thread::scope(|scope| { + let workers = spawn(scope, options.threads.min(sources.len()), &sender, &run); + drop(sender); + let served = serve(&events, ask, sources.len()); + for worker in workers { + // A worker that panicked left its source unextracted + let _ = worker.join(); + } + served + }); + in_order + .then(|| extracted.into_iter().collect::>>()) + .flatten() +} + +/// Extract the sources one after another on this thread. +fn extract_sequential( + sources: &[BatchSource], + options: &BatchOptions, + ask: Option<&Ask>, +) -> Vec> { + sources + .iter() + .map(|source| extract_source(source, options, ask)) + .collect() +} + +/// What the workers extracted, or when they could not, the numbering they +/// changed put back as `snapshot` holds it and every source extracted one by one. +fn or_one_by_one( + parallel: Option>, + snapshot: Snapshot, + one_by_one: impl FnOnce() -> Vec, +) -> Vec { + parallel.unwrap_or_else(|| { + snapshot.restore(); + one_by_one() + }) +} + +/// Extract `sources` as extracting them one by one in their order would, +/// resolving imports through `ask` on this thread. +pub fn extract_batch(sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>) -> Batch { + // Hoisted atoms are named from a plan the first extraction freezes + let parallel = options.threads > 1 && css::atom_hoist::atom_hoist_threshold().is_none(); + let extracted = if parallel { + let snapshot = Snapshot::take(); + or_one_by_one(extract_parallel(sources, options, ask), snapshot, || { + extract_sequential(sources, options, ask) + }) + } else { + extract_sequential(sources, options, ask) + }; + let css = CssOptions { + single_css: options.option.single_css, + import_main_css: options.import_main_css_in_css, + }; + let outputs = sources + .iter() + .zip(extracted) + .map(|(source, extracted)| { + extracted.map(|output| Output { + css: None, + ..Output::new(output, source.filename.clone(), css) + }) + }) + .collect(); + Batch { outputs, parallel } +} + +#[cfg(test)] +mod tests; diff --git a/libs/binding/src/batch/tests.rs b/libs/binding/src/batch/tests.rs new file mode 100644 index 000000000..2cb27726a --- /dev/null +++ b/libs/binding/src/batch/tests.rs @@ -0,0 +1,37 @@ +use serial_test::serial; + +use super::*; + +#[test] +#[serial] +fn workers_that_could_not_extract_leave_the_numbering_to_one_by_one() { + crate::reset_state_internal(|| {}); + let _ = css::keyframes_to_keyframes_name("first", None); + let snapshot = Snapshot::take(); + let numbered = css::class_map::get_class_map(); + let _ = css::keyframes_to_keyframes_name("second", None); + + let extracted = or_one_by_one(None, snapshot, || vec![css::class_map::get_class_map()]); + + assert_eq!(extracted, [numbered]); +} + +#[test] +#[serial] +fn what_workers_extracted_stands() { + crate::reset_state_internal(|| {}); + let snapshot = Snapshot::take(); + let _ = css::keyframes_to_keyframes_name("kept", None); + + let extracted = or_one_by_one(Some(vec![1]), snapshot, || vec![2]); + + assert_eq!(extracted, [1]); + assert_eq!(css::class_map::get_class_map()[""].len(), 1); +} + +#[test] +fn the_default_workers_are_the_cores_at_most_eight() { + let threads = default_threads(); + + assert!((1..=MAX_DEFAULT_THREADS).contains(&threads)); +} diff --git a/libs/binding/src/lib.rs b/libs/binding/src/lib.rs index d1bc2549a..3cc8e36a3 100644 --- a/libs/binding/src/lib.rs +++ b/libs/binding/src/lib.rs @@ -1,5 +1,6 @@ //! Host-neutral binding orchestration; JavaScript values belong to the host adapter. +mod batch; mod css_cache; mod lazy_css; mod native_theme; @@ -8,6 +9,9 @@ mod reservation; mod resolver_state; pub mod session; +pub use batch::{ + Ask, Batch, BatchOptions, BatchSource, HostAnswer, default_threads, extract_batch, +}; pub use css::debug::{is_debug, set_debug}; pub use css::license_banner::{is_license_banner, set_license_banner}; pub use css::slot_reservation::unreserved_slot_count as get_unreserved_class_slot_count; diff --git a/libs/binding/tests/batch.rs b/libs/binding/tests/batch.rs new file mode 100644 index 000000000..7802e35f3 --- /dev/null +++ b/libs/binding/tests/batch.rs @@ -0,0 +1,499 @@ +//! A batch extracts its sources as extracting them one by one in order does, +//! however many threads it runs on. + +use std::cell::RefCell; +use std::fmt::Write as _; +use std::rc::Rc; + +use devup_ui_binding_core::{ + Ask, BatchOptions, BatchSource, ExtractionMode, HostAnswer, Output, ResolverState, + SourceMapMode, code_extract, export_class_map_internal, export_file_map_internal, + export_sheet_internal, extract_batch, get_css, import_canonical_map_internal, + reset_state_internal, seed_file_map, set_atom_hoist, +}; +use extractor::ExtractOption; +use serial_test::serial; + +const COMPONENTS: usize = 48; +const ROUTES: usize = 6; +const BARREL: &str = "src/components/index.ts"; + +/// A large app: components behind one barrel, collapsed into its bucket, read +/// by routes, all reading shared tokens; and sources that fail, that import +/// nothing to extract, or that the file numbering does not know. +fn app() -> Vec<(String, String)> { + let mut files = vec![( + "src/tokens.ts".to_string(), + "export const tones = { a: '#123456', b: '#abcdef', c: 'red' } as const\nexport const space = { s: 4, m: 8 } as const\n".to_string(), + )]; + for index in 0..COMPONENTS { + files.push(( + format!("src/components/C{index:03}.tsx"), + format!( + "import {{ Box, css, Flex, keyframes, styled, Text }} from '@devup-ui/react' +import {{ space, tones }} from '../tokens' + +const Frame = styled('section', {{ borderRadius: {radius}, p: space.m }}) +const spin = keyframes({{ from: {{ opacity: 0 }}, to: {{ opacity: {opacity} }} }}) + +export function C{index:03}({{ active }}: {{ active?: boolean }}) {{ + return ( + + + + item {index} + + + + ) +}} +", + radius = 4 + index % 8, + gap = 2 + index % 12, + opacity = format!("0.{}", index % 9 + 1), + tone = ["a", "b", "c"][index % 3], + size = 12 + index % 10, + ), + )); + } + files.push(( + BARREL.to_string(), + (0..COMPONENTS).fold(String::new(), |mut barrel, index| { + let _ = writeln!(barrel, "export {{ C{index:03} }} from './C{index:03}'"); + barrel + }), + )); + for route in 0..ROUTES { + let names: Vec = (0..COMPONENTS / ROUTES) + .map(|offset| { + format!( + "C{:03}", + (route * COMPONENTS / ROUTES + offset) % COMPONENTS + ) + }) + .collect(); + files.push(( + format!("src/app/r{route}/page.tsx"), + format!( + "import {{ Box }} from '@devup-ui/react'\nimport {{ {} }} from '@/components'\n\nexport default function Page() {{\n return {}\n}}\n", + names.join(", "), + names.iter().fold(String::new(), |mut tags, name| { + let _ = write!(tags, "<{name} />"); + tags + }), + ), + )); + } + files.extend([ + ( + "src/app/broken.tsx".to_string(), + "import { Box } from '@devup-ui/react'\nexport const view = \n".to_string(), + ), + ( + "src/unnumbered.tsx".to_string(), + "import { Box } from '@devup-ui/react'\nexport const view = \n".to_string(), + ), + ]); + files +} + +/// Resolve an import of the app as the bundler does. +fn module(app: &[(String, String)], specifier: &str, importer: &str) -> Option<(String, String)> { + let base = if let Some(rest) = specifier.strip_prefix("@/") { + format!("src/{rest}") + } else if specifier.starts_with('.') { + let mut parts: Vec<&str> = importer.split('/').collect(); + parts.pop(); + for part in specifier.split('/') { + match part { + "." => {} + ".." => { + parts.pop(); + } + part => parts.push(part), + } + } + parts.join("/") + } else { + return None; + }; + ["", ".ts", ".tsx", "/index.ts"] + .iter() + .find_map(|extension| { + let path = format!("{base}{extension}"); + app.iter() + .find(|(filename, _)| *filename == path) + .map(|(filename, code)| (filename.clone(), code.clone())) + }) +} + +fn option() -> ExtractOption { + ExtractOption { + package: "@devup-ui/react".to_string(), + ..ExtractOption::default() + } +} + +fn css_dir(filename: &str) -> String { + format!("./{}df", "../".repeat(filename.matches('/').count())) +} + +/// The engine as the build sets it up: the components collapse into their +/// barrel's bucket, one shared file goes to the global sheet, and every file +/// but one is numbered in path order. +fn set_up(app: &[(String, String)]) { + reset_state_internal(|| {}); + import_canonical_map_internal( + app.iter() + .filter(|(filename, _)| filename.starts_with("src/components/C")) + .map(|(filename, _)| (filename.clone(), BARREL.to_string())) + .chain([( + "src/shared.tsx".to_string(), + css::file_map::GLOBAL_BUCKET.to_string(), + )]) + .collect(), + ); + let mut numbered: Vec = app + .iter() + .map(|(filename, _)| filename.clone()) + .filter(|filename| filename != "src/unnumbered.tsx") + .collect(); + numbered.sort(); + seed_file_map(&numbered); +} + +/// A source's code, map, CSS file, base-style flag and dependencies. +type Extracted = (String, Option, Option, bool, Vec); + +/// Everything a source's output and the engine state tell. +#[derive(Debug, PartialEq, Eq)] +struct Outcome { + outputs: Vec>, + sheet: String, + classes: String, + files: String, + css: Vec, +} + +fn outcome(outputs: Vec>) -> Outcome { + Outcome { + outputs: outputs + .into_iter() + .map(|output| { + output.map(|output| { + ( + output.code, + output.map, + output.css_file, + output.updated_base_style, + output.dependencies, + ) + }) + }) + .collect(), + sheet: export_sheet_internal().unwrap_or_default(), + classes: export_class_map_internal().unwrap_or_default(), + files: export_file_map_internal().unwrap_or_default(), + css: [None, Some(0), Some(1), Some(2)] + .into_iter() + .map(|file| get_css(file, false)) + .collect(), + } +} + +/// Extract the app one source after another, as a loader does. +fn one_by_one(app: &[(String, String)], source_map: bool) -> Outcome { + set_up(app); + let outputs = app + .iter() + .map(|(filename, code)| { + let diagnostics = Rc::new(RefCell::new(ResolverState::new(filename, code))); + let resolver = { + let (diagnostics, app) = (Rc::clone(&diagnostics), app.to_vec()); + move |specifier: &str, importer: &str| { + let request = diagnostics.borrow().request(specifier, importer)?; + let (path, code) = module(&app, specifier, importer)?; + let module = extractor::ResolvedModule { path, code }; + diagnostics.borrow_mut().cache(&module, &request); + Some(module) + } + }; + let check = || diagnostics.borrow().check(); + code_extract( + (filename, code), + ExtractOption { + css_dir: css_dir(filename), + ..option() + }, + ExtractionMode { + source_map: if source_map { + SourceMapMode::Generate + } else { + SourceMapMode::Skip + }, + resolver: Some(&resolver), + resolver_check: Some(&check), + import_main_css_in_css: true, + }, + ) + .map(|output| Output { + css: None, + ..output + }) + }) + .collect(); + outcome(outputs) +} + +fn sources(app: &[(String, String)]) -> Vec { + app.iter() + .map(|(filename, code)| BatchSource { + filename: filename.clone(), + code: code.clone(), + css_dir: css_dir(filename), + }) + .collect() +} + +fn resolver(app: &[(String, String)]) -> Ask { + let app = app.to_vec(); + Rc::new(move |specifier: &str, importer: &str| { + module(&app, specifier, importer).map_or(HostAnswer::Unresolved, |(path, code)| { + HostAnswer::Module { path, code } + }) + }) +} + +fn batch(app: &[(String, String)], threads: usize, source_map: bool) -> (Outcome, bool) { + set_up(app); + let batch = extract_batch( + &sources(app), + &BatchOptions { + option: option(), + source_map: if source_map { + SourceMapMode::Generate + } else { + SourceMapMode::Skip + }, + import_main_css_in_css: true, + threads, + }, + Some(&resolver(app)), + ); + (outcome(batch.outputs), batch.parallel) +} + +#[test] +#[serial] +fn a_batch_extracts_as_one_by_one_on_any_number_of_threads() { + let app = app(); + let expected = one_by_one(&app, false); + assert!( + expected.outputs.iter().any(Result::is_err), + "one source fails" + ); + assert!(expected.classes.contains(BARREL)); + + for threads in [1, 2, 3, 4, 8, 16, 64] { + for _ in 0..if threads == 8 { 8 } else { 2 } { + let (outcome, parallel) = batch(&app, threads, false); + assert_eq!(parallel, threads > 1); + assert_eq!(outcome, expected, "{threads} threads"); + } + } +} + +#[test] +#[serial] +fn a_batch_maps_sources_as_one_by_one() { + let app = app(); + let expected = one_by_one(&app, true); + assert!( + expected + .outputs + .iter() + .flatten() + .any(|output| output.1.is_some()) + ); + + let (outcome, _) = batch(&app, 4, true); + assert_eq!(outcome, expected); +} + +#[test] +#[serial] +fn a_batch_under_atom_hoisting_extracts_one_by_one() { + let app = app(); + set_up(&app); + set_atom_hoist(Some(2)); + let batch = extract_batch( + &sources(&app[..3]), + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: true, + threads: 4, + }, + None, + ); + set_atom_hoist(None); + + assert!(!batch.parallel); + assert_eq!(batch.outputs.len(), 3); +} + +#[test] +#[serial] +fn a_batch_without_a_resolver_extracts_as_one_by_one_without_one() { + let app = app(); + let sources = sources(&app); + let run = |threads| { + set_up(&app); + let batch = extract_batch( + &sources, + &BatchOptions { + option: option(), + source_map: SourceMapMode::Generate, + import_main_css_in_css: false, + threads, + }, + None, + ); + outcome(batch.outputs) + }; + + assert_eq!(run(4), run(1)); +} + +/// The output of a source reading `./tokens`, resolved through `answer`. +fn resolved_through(answer: HostAnswer, threads: usize) -> Result { + reset_state_internal(|| {}); + let answer = RefCell::new(Some(answer)); + let ask: Ask = Rc::new(move |_: &str, _: &str| { + answer.borrow_mut().take().unwrap_or(HostAnswer::Unresolved) + }); + let sources = [BatchSource { + filename: "src/view.tsx".to_string(), + code: "import { Box } from '@devup-ui/react'\nimport { tones } from './tokens'\nexport const view = \n".to_string(), + css_dir: "./df".to_string(), + }]; + extract_batch( + &sources, + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: false, + threads, + }, + Some(&ask), + ) + .outputs + .remove(0) +} + +#[test] +#[serial] +fn a_batch_reports_what_the_resolver_answers_as_one_by_one() { + for threads in [1, 2] { + let module = resolved_through( + HostAnswer::Module { + path: "src/tokens.ts".to_string(), + code: "export const tones = { a: '#123456' } as const\n".to_string(), + }, + threads, + ); + assert!(module.is_ok_and(|output| output.code.contains("className"))); + + let failed = resolved_through(HostAnswer::Failed("no tokens".to_string()), threads); + assert!(failed.is_err_and( + |error| error.contains("module resolver failed for `./tokens`") + && error.contains("no tokens") + )); + + let unnamed = resolved_through( + HostAnswer::Module { + path: String::new(), + code: String::new(), + }, + threads, + ); + assert!(unnamed.is_err_and(|error| error.contains("`path` must be a non-empty string"))); + + let transport = resolved_through(HostAnswer::Transport("gone".to_string()), threads); + assert_eq!(transport.err().as_deref(), Some("gone")); + + let unresolved = resolved_through(HostAnswer::Unresolved, threads); + assert!(unresolved.is_ok()); + } +} + +#[test] +#[serial] +fn an_empty_batch_extracts_nothing() { + reset_state_internal(|| {}); + let batch = extract_batch( + &[], + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: false, + threads: 4, + }, + None, + ); + assert!(batch.outputs.is_empty()); + assert!(batch.parallel); +} + +#[test] +#[serial] +fn workers_ask_the_resolver_once_for_each_import_of_each_source() { + let app = app(); + let run = |threads| { + set_up(&app); + let asked = Rc::new(RefCell::new(Vec::new())); + let ask: Ask = { + let (asked, resolve) = (Rc::clone(&asked), resolver(&app)); + Rc::new(move |specifier: &str, importer: &str| { + asked + .borrow_mut() + .push((specifier.to_string(), importer.to_string())); + resolve(specifier, importer) + }) + }; + let batch = extract_batch( + &sources(&app), + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: true, + threads, + }, + Some(&ask), + ); + let asked = asked.borrow().clone(); + (outcome(batch.outputs), asked) + }; + let (expected, one_by_one) = run(1); + let (outcome, parallel) = run(4); + + let mut unique = one_by_one.clone(); + unique.sort(); + unique.dedup(); + assert!( + unique.len() < one_by_one.len(), + "sources ask for an import again" + ); + let mut asked = parallel; + asked.sort(); + assert_eq!(asked, unique); + assert_eq!(outcome, expected); +} diff --git a/libs/css/src/file_map.rs b/libs/css/src/file_map.rs index 6f23fea77..41131bfdf 100644 --- a/libs/css/src/file_map.rs +++ b/libs/css/src/file_map.rs @@ -86,8 +86,10 @@ pub fn get_file_num_by_filename(filename: &str) -> usize { // RefCell::borrow_mut contention); only fall back to the write guard on a // genuine miss. if let Some(file_num) = with_file_map(|map| map.get_by_left(filename).copied()) { + crate::numbering_order::observe(); return file_num; } + crate::numbering_order::before_numbering(); with_file_map_mut(|map| { // Re-check under the write lock in case another registration slipped in // during the brief unlocked window between the two guards. diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index b19d8f27d..34324589a 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -12,6 +12,7 @@ pub mod file_routes; pub mod is_special_property; pub mod license_banner; mod num_to_nm_base; +pub mod numbering_order; pub mod optimize_multi_css_value; pub mod optimize_value; mod property_names; @@ -424,6 +425,7 @@ thread_local! { /// Single home for the class naming algorithm shared by keyframes, classname /// and variable-name generation. fn class_num_for_key(filename_key: &str, build_key: impl FnOnce(&mut String)) -> String { + numbering_order::before_numbering(); KEY_BUF.with(|buf| { let mut key = buf.borrow_mut(); key.clear(); diff --git a/libs/css/src/numbering_order.rs b/libs/css/src/numbering_order.rs new file mode 100644 index 000000000..0d9bddf7c --- /dev/null +++ b/libs/css/src/numbering_order.rs @@ -0,0 +1,183 @@ +//! Number classes and files in a fixed order of extractions running at once. +//! +//! Class and file numbers are handed out first come, first served, so the +//! order extractions number in decides them. Several threads can extract at +//! once and still number as extracting one after another would, when each +//! extraction numbers only in its turn: from its first number to the point +//! where its outermost extraction has handed out its last, no other numbers. +//! +//! A thread starts an extraction's turn with [`Turn::begin`]. Its first +//! number waits for the turn, and [`numbering_done`], which the extractor calls +//! once the outermost extraction can hand out no more, passes the turn on, as +//! ending the turn does. A number taken after that is out of order, and +//! [`Turn::finish`] reports it. + +use std::cell::{Cell, RefCell}; +use std::marker::PhantomData; +use std::rc::Rc; + +use crate::class_map::{ClassMap, get_class_map, set_class_map}; +use crate::file_map::{FileMap, get_file_map, set_file_map}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Phase { + /// Has not numbered yet + Before, + /// Numbers in its turn + Numbering, + /// Passed its turn on + Passed, + /// Numbered after passing its turn on + OutOfOrder, +} + +struct Ordered { + phase: Phase, + wait: Box, + pass: Box, +} + +impl Ordered { + fn pass_on(&mut self) { + if matches!(self.phase, Phase::Before | Phase::Numbering) { + (self.pass)(); + self.phase = Phase::Passed; + } + } +} + +thread_local! { + static ORDERED: RefCell> = const { RefCell::new(None) }; + /// How many extractions run inside one another on this thread + static DEPTH: Cell = const { Cell::new(0) }; +} + +/// One extraction's turn to number on this thread. +#[must_use] +pub struct Turn { + thread_bound: PhantomData>, +} + +impl Turn { + /// Start an extraction whose first number calls `wait`, which returns once + /// it is the extraction's turn, and which calls `pass` once to pass the + /// turn on, by the end at the latest. + pub fn begin(wait: impl Fn() + 'static, pass: impl Fn() + 'static) -> Self { + ORDERED.set(Some(Ordered { + phase: Phase::Before, + wait: Box::new(wait), + pass: Box::new(pass), + })); + Self { + thread_bound: PhantomData, + } + } + + /// End the turn, passing it on if it was not, and return whether the + /// extraction numbered only in its turn. + pub fn finish(self) -> bool { + ORDERED.with_borrow_mut(|ordered| { + ordered.as_mut().is_none_or(|ordered| { + ordered.pass_on(); + ordered.phase != Phase::OutOfOrder + }) + }) + } +} + +impl Drop for Turn { + fn drop(&mut self) { + if let Some(mut ordered) = ORDERED.take() { + ordered.pass_on(); + } + } +} + +/// Wait for this thread's turn before handing out a number. +pub(crate) fn before_numbering() { + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered { + match ordered.phase { + Phase::Before => { + (ordered.wait)(); + ordered.phase = Phase::Numbering; + } + Phase::Numbering | Phase::OutOfOrder => {} + Phase::Passed => ordered.phase = Phase::OutOfOrder, + } + } + }); +} + +/// Note that this thread read a number already handed out. +/// +/// Before the turn it was handed out by an extraction ordered earlier, as +/// only those number before this turn; after it, maybe by a later one. +pub(crate) fn observe() { + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered + && ordered.phase == Phase::Passed + { + ordered.phase = Phase::OutOfOrder; + } + }); +} + +/// The outermost extraction on this thread hands out no more numbers: pass +/// its turn on. +pub fn numbering_done() { + if DEPTH.get() == 1 { + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered { + ordered.pass_on(); + } + }); + } +} + +/// Marks an extraction running on this thread, inside any it runs within. +#[must_use] +pub struct Extracting { + thread_bound: PhantomData>, +} + +/// Enter an extraction; only the outermost one passes the turn on. +pub fn extracting() -> Extracting { + DEPTH.set(DEPTH.get() + 1); + Extracting { + thread_bound: PhantomData, + } +} + +impl Drop for Extracting { + fn drop(&mut self) { + DEPTH.set(DEPTH.get() - 1); + } +} + +/// The class and file numbering as it was, to number again from. +pub struct Snapshot { + classes: ClassMap, + files: FileMap, + reservation: crate::slot_reservation::State, +} + +impl Snapshot { + pub fn take() -> Self { + Self { + classes: get_class_map(), + files: get_file_map(), + reservation: crate::slot_reservation::current_state(), + } + } + + /// Make the numbering what it was when taken. + pub fn restore(self) { + set_class_map(self.classes); + set_file_map(self.files); + crate::slot_reservation::replace_state(self.reservation); + } +} + +#[cfg(test)] +mod tests; diff --git a/libs/css/src/numbering_order/tests.rs b/libs/css/src/numbering_order/tests.rs new file mode 100644 index 000000000..d6fd28887 --- /dev/null +++ b/libs/css/src/numbering_order/tests.rs @@ -0,0 +1,142 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use serial_test::serial; + +use super::*; +use crate::file_map::get_file_num_by_filename; +use crate::keyframes_to_keyframes_name; +use crate::test_state::TestStateGuard; + +/// A turn that records when it waits and passes. +fn recorded_turn() -> (Turn, Rc>>) { + let events = Rc::new(RefCell::new(Vec::new())); + let (waits, passes) = (Rc::clone(&events), Rc::clone(&events)); + let turn = Turn::begin( + move || waits.borrow_mut().push("wait"), + move || passes.borrow_mut().push("pass"), + ); + (turn, events) +} + +#[test] +#[serial] +fn the_first_number_waits_for_the_turn_and_the_outermost_extraction_passes_it() { + let _state = TestStateGuard::new(); + let (turn, events) = recorded_turn(); + let outer = extracting(); + assert!(events.borrow().is_empty()); + + let _ = keyframes_to_keyframes_name("x", None); + let _ = keyframes_to_keyframes_name("y", None); + assert_eq!(*events.borrow(), ["wait"]); + let inner = extracting(); + numbering_done(); + assert_eq!( + *events.borrow(), + ["wait"], + "a nested extraction keeps the turn" + ); + drop(inner); + numbering_done(); + assert_eq!(*events.borrow(), ["wait", "pass"]); + drop(outer); + + assert!(turn.finish()); + assert_eq!(*events.borrow(), ["wait", "pass"]); +} + +#[test] +#[serial] +fn a_file_number_handed_out_waits_for_the_turn_but_one_read_does_not() { + let _state = TestStateGuard::new(); + let _ = get_file_num_by_filename("a.tsx"); + let (turn, events) = recorded_turn(); + + assert_eq!(get_file_num_by_filename("a.tsx"), 0); + assert!(events.borrow().is_empty()); + assert_eq!(get_file_num_by_filename("b.tsx"), 1); + assert_eq!(*events.borrow(), ["wait"]); + + assert!(turn.finish()); + assert_eq!(*events.borrow(), ["wait", "pass"]); +} + +#[test] +#[serial] +fn numbering_after_passing_the_turn_is_out_of_order() { + let _state = TestStateGuard::new(); + let (turn, _) = recorded_turn(); + let _extracting = extracting(); + numbering_done(); + let _ = keyframes_to_keyframes_name("x", None); + let _ = keyframes_to_keyframes_name("y", None); + + assert!(!turn.finish()); +} + +#[test] +#[serial] +fn reading_a_file_number_after_passing_the_turn_is_out_of_order() { + let _state = TestStateGuard::new(); + let _ = get_file_num_by_filename("a.tsx"); + let (turn, events) = recorded_turn(); + let _extracting = extracting(); + numbering_done(); + let _ = get_file_num_by_filename("a.tsx"); + + assert!(!turn.finish()); + assert_eq!(*events.borrow(), ["pass"]); +} + +#[test] +#[serial] +fn a_turn_that_never_numbers_passes_once_it_ends() { + let _state = TestStateGuard::new(); + let (turn, events) = recorded_turn(); + drop(turn); + + assert_eq!(*events.borrow(), ["pass"]); + let _ = keyframes_to_keyframes_name("x", None); + assert_eq!( + *events.borrow(), + ["pass"], + "numbers outside a turn wait for none" + ); +} + +#[test] +#[serial] +fn a_turn_ended_by_a_later_one_numbered_in_order() { + let _state = TestStateGuard::new(); + let (outer, _) = recorded_turn(); + let (inner, events) = recorded_turn(); + drop(inner); + + assert!(outer.finish()); + assert_eq!(*events.borrow(), ["pass"]); +} + +#[test] +#[serial] +fn a_snapshot_restores_the_numbering_it_was_taken_of() { + let _state = TestStateGuard::new(); + crate::slot_reservation::ScratchSlots::default().commit(); + let _ = get_file_num_by_filename("a.tsx"); + let _ = keyframes_to_keyframes_name("x", None); + let snapshot = Snapshot::take(); + let (classes, files, misses) = ( + get_class_map(), + get_file_map(), + crate::slot_reservation::unreserved_slot_count(), + ); + + let _ = get_file_num_by_filename("b.tsx"); + let _ = keyframes_to_keyframes_name("y", None); + assert_ne!(crate::slot_reservation::unreserved_slot_count(), misses); + snapshot.restore(); + + assert_eq!(get_class_map(), classes); + assert_eq!(get_file_map(), files); + assert_eq!(crate::slot_reservation::unreserved_slot_count(), misses); +} diff --git a/libs/css/src/slot_reservation.rs b/libs/css/src/slot_reservation.rs index 6fbce61b2..fbdd8d6db 100644 --- a/libs/css/src/slot_reservation.rs +++ b/libs/css/src/slot_reservation.rs @@ -45,6 +45,10 @@ pub fn reset() { with_state(|state| *state = State::default()); } +pub(crate) fn current_state() -> State { + with_state(|state| *state) +} + pub(crate) fn replace_state(replacement: State) -> State { with_state(|state| std::mem::replace(state, replacement)) } diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 94c8658e7..dabe20d72 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -488,6 +488,7 @@ fn extract_with_source_map( if let ExtractTarget::Native(target) = option.target { return native::extract(filename, code, &option.package, target, source_map); } + let _extracting = css::numbering_order::extracting(); extract_source(filename, code, None, None, option, source_map, resolver) } @@ -1092,6 +1093,8 @@ fn extract_source( message += &changed_notes(&message, filename, source, &edits, &inlined.changed); return Err(message.into()); } + // Generating the code names nothing more + css::numbering_order::numbering_done(); let codegen_options = if source_map { CodegenOptions { source_map_path: Some(PathBuf::from(filename)), From 3465b7496f710e5ff054ce61859c697f5fe342a9 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 5 Dec 2026 16:47:55 +0900 Subject: [PATCH 2/6] fix(css): release the prefix lock before naming a class with_prefix held the global prefix mutex while its closure named classes. In a batch, a worker naming its file's first class waits there for an earlier file's turn; with the lock held, the earlier file could not name its own classes, and the batch deadlocked (seen on apps/landing under a Next production build). The prefix is now an Arc copied out under the lock, so no lock is held while a name waits for its turn. Co-Authored-By: Claude Opus 5.5 --- libs/css/src/lib.rs | 47 +++++++++++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index 34324589a..17a904eff 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -66,27 +66,29 @@ mod prefix_state { #[cfg(not(target_arch = "wasm32"))] mod prefix_state { - use std::sync::LazyLock; - use std::sync::Mutex; - static GLOBAL_PREFIX: LazyLock>> = LazyLock::new(|| Mutex::new(None)); + use std::sync::{Arc, LazyLock, Mutex}; + static GLOBAL_PREFIX: LazyLock>>> = LazyLock::new(|| Mutex::new(None)); + fn current() -> Option> { + GLOBAL_PREFIX + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } pub fn set_prefix(prefix: Option) { *GLOBAL_PREFIX .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = prefix; + .unwrap_or_else(std::sync::PoisonError::into_inner) = prefix.map(Arc::from); } pub fn get_prefix() -> Option { - GLOBAL_PREFIX - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() + current().as_deref().map(str::to_string) } - /// Run `f` with the current prefix as `&str` (empty when unset) without cloning. + /// Run `f` with the current prefix as `&str` (empty when unset) without cloning it. + /// + /// The lock is released before `f` runs: `f` names classes, which can wait + /// for an earlier file's turn, and that file names classes with the prefix too. pub(crate) fn with_prefix(f: impl FnOnce(&str) -> R) -> R { - f(GLOBAL_PREFIX - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .as_deref() - .unwrap_or_default()) + let prefix = current(); + f(prefix.as_deref().unwrap_or_default()) } } @@ -781,6 +783,23 @@ mod tests { set_prefix(None); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[serial] + fn test_with_prefix_holds_no_lock_while_naming() { + // Given: a naming step that reads the prefix again (as a worker + // waiting for its turn lets an earlier file do) + let _state = test_state::TestStateGuard::new(); + set_prefix(Some("host-".to_string())); + + // When + let prefixes = with_prefix(|outer| (outer.to_string(), get_prefix())); + + // Then: the inner read does not wait on the outer one + assert_eq!(prefixes, ("host-".to_string(), Some("host-".to_string()))); + set_prefix(None); + } + #[rstest] #[case("hover", "hover")] #[case("&:hover", "_a__c_hover")] From acb9501345dcc65fb4aa5ccc9546a61d9ee8b328 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 5 Dec 2026 17:05:18 +0900 Subject: [PATCH 3/6] fix(binding): commit each batch source to the stylesheet in its turn Committing an output to the stylesheet names classes too (a style's class in the global bucket is named when it is added). The batch committed every output only after all sources were extracted, so a later source's extraction could name a class before an earlier source's commit did; on apps/landing that moved classes in the global bucket. A worker now commits its source itself, after waiting for its turn, and the turn passes only once the commit is done, so numbering and the stylesheet change in source order exactly as one by one. Parsing and resolving imports before a source's first number still run at once. With the turn held to the end, nothing can number after its turn passed, so the out-of-order check, the snapshot fallback and the extractor's turn hooks go; a worker that panics fails the batch with its panic, as one by one would. Co-Authored-By: Claude Opus 5.5 --- libs/binding/src/batch.rs | 134 ++++++++++-------------- libs/binding/src/batch/tests.rs | 37 ------- libs/binding/tests/batch.rs | 5 + libs/css/src/file_map.rs | 1 - libs/css/src/numbering_order.rs | 144 +++----------------------- libs/css/src/numbering_order/tests.rs | 86 +++------------ libs/css/src/slot_reservation.rs | 4 - libs/extractor/src/lib.rs | 3 - 8 files changed, 88 insertions(+), 326 deletions(-) delete mode 100644 libs/binding/src/batch/tests.rs diff --git a/libs/binding/src/batch.rs b/libs/binding/src/batch.rs index 404a121da..0c7e8d51e 100644 --- a/libs/binding/src/batch.rs +++ b/libs/binding/src/batch.rs @@ -1,13 +1,13 @@ //! Extract many sources at once, as extracting them one by one in their order //! would, but on several threads. //! -//! Worker threads take the sources in order and extract them at once, each -//! numbering classes and files only in its turn (see -//! [`css::numbering_order`]), so every number comes out as one by one. The -//! calling thread, the only one that may run the host's module resolver, -//! answers the workers' resolver requests, then commits the outputs to the -//! stylesheet in source order. An extraction that numbered out of its turn -//! sends the whole batch back to extracting one by one. +//! Worker threads take the sources in order and extract them at once. Each +//! numbers classes and files and commits its styles to the stylesheet only in +//! its turn (see [`css::numbering_order`]): from its first number on, until +//! the commit, no other source numbers, so every number and the stylesheet +//! come out as one by one. Parsing and resolving imports before that run at +//! once. The calling thread, the only one that may run the host's module +//! resolver, answers the workers' resolver requests. use std::cell::RefCell; use std::collections::HashMap; @@ -17,7 +17,7 @@ use std::sync::mpsc::{Receiver, Sender, SyncSender, channel, sync_channel}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread::{Builder, Scope, ScopedJoinHandle}; -use css::numbering_order::{Snapshot, Turn}; +use css::numbering_order::Turn; use extractor::{ ExtractOption, ExtractOutput, ResolvedModule, extract, extract_with_modules, extract_without_source_map, @@ -90,11 +90,10 @@ enum Event { importer: String, reply: SyncSender, }, - /// A source is extracted, numbering only in its turn or not. + /// A source is extracted and committed. Extracted { index: usize, - result: Result, - in_order: bool, + result: Result, }, } @@ -256,6 +255,28 @@ impl Turns { } } +/// Extract one source and commit it to the stylesheet, as one by one would. +/// +/// Committing names classes too, so it runs in the source's turn: `wait` +/// returns once every earlier source has ended its own. +fn extract_and_commit( + source: &BatchSource, + options: &BatchOptions, + ask: Option<&Ask>, + wait: impl FnOnce(), +) -> Result { + let extracted = extract_source(source, options, ask); + wait(); + let css = CssOptions { + single_css: options.option.single_css, + import_main_css: options.import_main_css_in_css, + }; + extracted.map(|output| Output { + css: None, + ..Output::new(output, source.filename.clone(), css) + }) +} + /// Extract the sources a worker takes, in order, until none are left. fn work( sources: &[BatchSource], @@ -275,27 +296,21 @@ fn work( break; }; let turn = turns.turn(index); - let result = extract_source(source, options, ask.as_ref()); - let in_order = turn.finish(); + let result = extract_and_commit(source, options, ask.as_ref(), || turns.wait(index)); + drop(turn); // The calling thread receives until every worker is done - let _ = events.send(Event::Extracted { - index, - result, - in_order, - }); + let _ = events.send(Event::Extracted { index, result }); } } /// Answer the workers' requests until every worker is done, returning what -/// they extracted in source order and whether all of it numbered in turn. +/// they extracted in source order. fn serve( events: &Receiver, ask: Option<&Ask>, sources: usize, -) -> (Vec>>, bool) { - let mut extracted: Vec>> = - (0..sources).map(|_| None).collect(); - let mut in_order = true; +) -> Vec>> { + let mut extracted: Vec>> = (0..sources).map(|_| None).collect(); for event in events { match event { Event::Resolve { @@ -307,20 +322,13 @@ fn serve( // A worker waits for every answer it asks for let _ = reply.send(answer); } - Event::Extracted { - index, - result, - in_order: ordered, - } => { - extracted[index] = Some(result); - in_order &= ordered; - } + Event::Extracted { index, result } => extracted[index] = Some(result), } } - (extracted, in_order) + extracted } -/// Start up to `threads` workers. +/// Start `threads` workers running `run` with their own handle to `events`. fn spawn<'scope>( scope: &'scope Scope<'scope, '_>, threads: usize, @@ -338,13 +346,13 @@ fn spawn<'scope>( .collect() } -/// Every source extracted on worker threads, or `None` when one numbered out -/// of its turn or no worker extracted it. +/// Every source extracted on worker threads. A worker that panics fails +/// the batch with its panic, as extracting one by one would. fn extract_parallel( sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>, -) -> Option>> { +) -> Vec> { let next = AtomicUsize::new(0); let turns = Arc::new(Turns::new(sources.len())); let answers = Arc::new(Answers::default()); @@ -358,75 +366,41 @@ fn extract_parallel( ); }; let (sender, events) = channel(); - let (extracted, in_order) = std::thread::scope(|scope| { + let extracted = std::thread::scope(|scope| { let workers = spawn(scope, options.threads.min(sources.len()), &sender, &run); drop(sender); let served = serve(&events, ask, sources.len()); for worker in workers { - // A worker that panicked left its source unextracted - let _ = worker.join(); + if let Err(panic) = worker.join() { + std::panic::resume_unwind(panic); + } } served }); - in_order - .then(|| extracted.into_iter().collect::>>()) - .flatten() + extracted.into_iter().flatten().collect() } -/// Extract the sources one after another on this thread. +/// Every source extracted and committed one by one, in order. fn extract_sequential( sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>, -) -> Vec> { +) -> Vec> { sources .iter() - .map(|source| extract_source(source, options, ask)) + .map(|source| extract_and_commit(source, options, ask, || {})) .collect() } -/// What the workers extracted, or when they could not, the numbering they -/// changed put back as `snapshot` holds it and every source extracted one by one. -fn or_one_by_one( - parallel: Option>, - snapshot: Snapshot, - one_by_one: impl FnOnce() -> Vec, -) -> Vec { - parallel.unwrap_or_else(|| { - snapshot.restore(); - one_by_one() - }) -} - /// Extract `sources` as extracting them one by one in their order would, /// resolving imports through `ask` on this thread. pub fn extract_batch(sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>) -> Batch { // Hoisted atoms are named from a plan the first extraction freezes let parallel = options.threads > 1 && css::atom_hoist::atom_hoist_threshold().is_none(); - let extracted = if parallel { - let snapshot = Snapshot::take(); - or_one_by_one(extract_parallel(sources, options, ask), snapshot, || { - extract_sequential(sources, options, ask) - }) + let outputs = if parallel { + extract_parallel(sources, options, ask) } else { extract_sequential(sources, options, ask) }; - let css = CssOptions { - single_css: options.option.single_css, - import_main_css: options.import_main_css_in_css, - }; - let outputs = sources - .iter() - .zip(extracted) - .map(|(source, extracted)| { - extracted.map(|output| Output { - css: None, - ..Output::new(output, source.filename.clone(), css) - }) - }) - .collect(); Batch { outputs, parallel } } - -#[cfg(test)] -mod tests; diff --git a/libs/binding/src/batch/tests.rs b/libs/binding/src/batch/tests.rs deleted file mode 100644 index 2cb27726a..000000000 --- a/libs/binding/src/batch/tests.rs +++ /dev/null @@ -1,37 +0,0 @@ -use serial_test::serial; - -use super::*; - -#[test] -#[serial] -fn workers_that_could_not_extract_leave_the_numbering_to_one_by_one() { - crate::reset_state_internal(|| {}); - let _ = css::keyframes_to_keyframes_name("first", None); - let snapshot = Snapshot::take(); - let numbered = css::class_map::get_class_map(); - let _ = css::keyframes_to_keyframes_name("second", None); - - let extracted = or_one_by_one(None, snapshot, || vec![css::class_map::get_class_map()]); - - assert_eq!(extracted, [numbered]); -} - -#[test] -#[serial] -fn what_workers_extracted_stands() { - crate::reset_state_internal(|| {}); - let snapshot = Snapshot::take(); - let _ = css::keyframes_to_keyframes_name("kept", None); - - let extracted = or_one_by_one(Some(vec![1]), snapshot, || vec![2]); - - assert_eq!(extracted, [1]); - assert_eq!(css::class_map::get_class_map()[""].len(), 1); -} - -#[test] -fn the_default_workers_are_the_cores_at_most_eight() { - let threads = default_threads(); - - assert!((1..=MAX_DEFAULT_THREADS).contains(&threads)); -} diff --git a/libs/binding/tests/batch.rs b/libs/binding/tests/batch.rs index 7802e35f3..9e6f422fd 100644 --- a/libs/binding/tests/batch.rs +++ b/libs/binding/tests/batch.rs @@ -497,3 +497,8 @@ fn workers_ask_the_resolver_once_for_each_import_of_each_source() { assert_eq!(asked, unique); assert_eq!(outcome, expected); } + +#[test] +fn the_default_workers_are_the_cores_at_most_eight() { + assert!((1..=8).contains(&devup_ui_binding_core::default_threads())); +} diff --git a/libs/css/src/file_map.rs b/libs/css/src/file_map.rs index 41131bfdf..7ce783a07 100644 --- a/libs/css/src/file_map.rs +++ b/libs/css/src/file_map.rs @@ -86,7 +86,6 @@ pub fn get_file_num_by_filename(filename: &str) -> usize { // RefCell::borrow_mut contention); only fall back to the write guard on a // genuine miss. if let Some(file_num) = with_file_map(|map| map.get_by_left(filename).copied()) { - crate::numbering_order::observe(); return file_num; } crate::numbering_order::before_numbering(); diff --git a/libs/css/src/numbering_order.rs b/libs/css/src/numbering_order.rs index 0d9bddf7c..efedc3581 100644 --- a/libs/css/src/numbering_order.rs +++ b/libs/css/src/numbering_order.rs @@ -3,53 +3,27 @@ //! Class and file numbers are handed out first come, first served, so the //! order extractions number in decides them. Several threads can extract at //! once and still number as extracting one after another would, when each -//! extraction numbers only in its turn: from its first number to the point -//! where its outermost extraction has handed out its last, no other numbers. +//! extraction numbers only in its turn: from its first number until it ends, +//! no other extraction numbers. //! //! A thread starts an extraction's turn with [`Turn::begin`]. Its first -//! number waits for the turn, and [`numbering_done`], which the extractor calls -//! once the outermost extraction can hand out no more, passes the turn on, as -//! ending the turn does. A number taken after that is out of order, and -//! [`Turn::finish`] reports it. +//! number waits for the turn, and ending the turn passes it on. What runs +//! before the first number (parsing, resolving imports) runs at once with the +//! other threads. -use std::cell::{Cell, RefCell}; +use std::cell::RefCell; use std::marker::PhantomData; use std::rc::Rc; -use crate::class_map::{ClassMap, get_class_map, set_class_map}; -use crate::file_map::{FileMap, get_file_map, set_file_map}; - -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Phase { - /// Has not numbered yet - Before, - /// Numbers in its turn - Numbering, - /// Passed its turn on - Passed, - /// Numbered after passing its turn on - OutOfOrder, -} - struct Ordered { - phase: Phase, + /// Whether the extraction waited for its turn + numbering: bool, wait: Box, pass: Box, } -impl Ordered { - fn pass_on(&mut self) { - if matches!(self.phase, Phase::Before | Phase::Numbering) { - (self.pass)(); - self.phase = Phase::Passed; - } - } -} - thread_local! { static ORDERED: RefCell> = const { RefCell::new(None) }; - /// How many extractions run inside one another on this thread - static DEPTH: Cell = const { Cell::new(0) }; } /// One extraction's turn to number on this thread. @@ -60,11 +34,10 @@ pub struct Turn { impl Turn { /// Start an extraction whose first number calls `wait`, which returns once - /// it is the extraction's turn, and which calls `pass` once to pass the - /// turn on, by the end at the latest. + /// it is the extraction's turn; ending the turn calls `pass` to pass it on. pub fn begin(wait: impl Fn() + 'static, pass: impl Fn() + 'static) -> Self { ORDERED.set(Some(Ordered { - phase: Phase::Before, + numbering: false, wait: Box::new(wait), pass: Box::new(pass), })); @@ -72,112 +45,29 @@ impl Turn { thread_bound: PhantomData, } } - - /// End the turn, passing it on if it was not, and return whether the - /// extraction numbered only in its turn. - pub fn finish(self) -> bool { - ORDERED.with_borrow_mut(|ordered| { - ordered.as_mut().is_none_or(|ordered| { - ordered.pass_on(); - ordered.phase != Phase::OutOfOrder - }) - }) - } } impl Drop for Turn { fn drop(&mut self) { - if let Some(mut ordered) = ORDERED.take() { - ordered.pass_on(); + if let Some(ordered) = ORDERED.take() { + (ordered.pass)(); } } } /// Wait for this thread's turn before handing out a number. -pub(crate) fn before_numbering() { - ORDERED.with_borrow_mut(|ordered| { - if let Some(ordered) = ordered { - match ordered.phase { - Phase::Before => { - (ordered.wait)(); - ordered.phase = Phase::Numbering; - } - Phase::Numbering | Phase::OutOfOrder => {} - Phase::Passed => ordered.phase = Phase::OutOfOrder, - } - } - }); -} - -/// Note that this thread read a number already handed out. /// -/// Before the turn it was handed out by an extraction ordered earlier, as -/// only those number before this turn; after it, maybe by a later one. -pub(crate) fn observe() { +/// Callers hold no lock: an earlier extraction numbers until its turn ends. +pub(crate) fn before_numbering() { ORDERED.with_borrow_mut(|ordered| { if let Some(ordered) = ordered - && ordered.phase == Phase::Passed + && !ordered.numbering { - ordered.phase = Phase::OutOfOrder; + (ordered.wait)(); + ordered.numbering = true; } }); } -/// The outermost extraction on this thread hands out no more numbers: pass -/// its turn on. -pub fn numbering_done() { - if DEPTH.get() == 1 { - ORDERED.with_borrow_mut(|ordered| { - if let Some(ordered) = ordered { - ordered.pass_on(); - } - }); - } -} - -/// Marks an extraction running on this thread, inside any it runs within. -#[must_use] -pub struct Extracting { - thread_bound: PhantomData>, -} - -/// Enter an extraction; only the outermost one passes the turn on. -pub fn extracting() -> Extracting { - DEPTH.set(DEPTH.get() + 1); - Extracting { - thread_bound: PhantomData, - } -} - -impl Drop for Extracting { - fn drop(&mut self) { - DEPTH.set(DEPTH.get() - 1); - } -} - -/// The class and file numbering as it was, to number again from. -pub struct Snapshot { - classes: ClassMap, - files: FileMap, - reservation: crate::slot_reservation::State, -} - -impl Snapshot { - pub fn take() -> Self { - Self { - classes: get_class_map(), - files: get_file_map(), - reservation: crate::slot_reservation::current_state(), - } - } - - /// Make the numbering what it was when taken. - pub fn restore(self) { - set_class_map(self.classes); - set_file_map(self.files); - crate::slot_reservation::replace_state(self.reservation); - } -} - #[cfg(test)] mod tests; diff --git a/libs/css/src/numbering_order/tests.rs b/libs/css/src/numbering_order/tests.rs index d6fd28887..0e803c854 100644 --- a/libs/css/src/numbering_order/tests.rs +++ b/libs/css/src/numbering_order/tests.rs @@ -21,29 +21,23 @@ fn recorded_turn() -> (Turn, Rc>>) { #[test] #[serial] -fn the_first_number_waits_for_the_turn_and_the_outermost_extraction_passes_it() { +fn the_first_number_waits_for_the_turn_and_ending_it_passes_it() { let _state = TestStateGuard::new(); let (turn, events) = recorded_turn(); - let outer = extracting(); assert!(events.borrow().is_empty()); let _ = keyframes_to_keyframes_name("x", None); let _ = keyframes_to_keyframes_name("y", None); assert_eq!(*events.borrow(), ["wait"]); - let inner = extracting(); - numbering_done(); + + drop(turn); + assert_eq!(*events.borrow(), ["wait", "pass"]); + let _ = keyframes_to_keyframes_name("z", None); assert_eq!( *events.borrow(), - ["wait"], - "a nested extraction keeps the turn" + ["wait", "pass"], + "numbers outside a turn wait for none" ); - drop(inner); - numbering_done(); - assert_eq!(*events.borrow(), ["wait", "pass"]); - drop(outer); - - assert!(turn.finish()); - assert_eq!(*events.borrow(), ["wait", "pass"]); } #[test] @@ -58,37 +52,10 @@ fn a_file_number_handed_out_waits_for_the_turn_but_one_read_does_not() { assert_eq!(get_file_num_by_filename("b.tsx"), 1); assert_eq!(*events.borrow(), ["wait"]); - assert!(turn.finish()); + drop(turn); assert_eq!(*events.borrow(), ["wait", "pass"]); } -#[test] -#[serial] -fn numbering_after_passing_the_turn_is_out_of_order() { - let _state = TestStateGuard::new(); - let (turn, _) = recorded_turn(); - let _extracting = extracting(); - numbering_done(); - let _ = keyframes_to_keyframes_name("x", None); - let _ = keyframes_to_keyframes_name("y", None); - - assert!(!turn.finish()); -} - -#[test] -#[serial] -fn reading_a_file_number_after_passing_the_turn_is_out_of_order() { - let _state = TestStateGuard::new(); - let _ = get_file_num_by_filename("a.tsx"); - let (turn, events) = recorded_turn(); - let _extracting = extracting(); - numbering_done(); - let _ = get_file_num_by_filename("a.tsx"); - - assert!(!turn.finish()); - assert_eq!(*events.borrow(), ["pass"]); -} - #[test] #[serial] fn a_turn_that_never_numbers_passes_once_it_ends() { @@ -97,46 +64,17 @@ fn a_turn_that_never_numbers_passes_once_it_ends() { drop(turn); assert_eq!(*events.borrow(), ["pass"]); - let _ = keyframes_to_keyframes_name("x", None); - assert_eq!( - *events.borrow(), - ["pass"], - "numbers outside a turn wait for none" - ); } #[test] #[serial] -fn a_turn_ended_by_a_later_one_numbered_in_order() { +fn a_turn_ended_by_a_later_one_on_the_thread_passes_once() { let _state = TestStateGuard::new(); - let (outer, _) = recorded_turn(); + let (outer, outer_events) = recorded_turn(); let (inner, events) = recorded_turn(); drop(inner); + drop(outer); - assert!(outer.finish()); assert_eq!(*events.borrow(), ["pass"]); -} - -#[test] -#[serial] -fn a_snapshot_restores_the_numbering_it_was_taken_of() { - let _state = TestStateGuard::new(); - crate::slot_reservation::ScratchSlots::default().commit(); - let _ = get_file_num_by_filename("a.tsx"); - let _ = keyframes_to_keyframes_name("x", None); - let snapshot = Snapshot::take(); - let (classes, files, misses) = ( - get_class_map(), - get_file_map(), - crate::slot_reservation::unreserved_slot_count(), - ); - - let _ = get_file_num_by_filename("b.tsx"); - let _ = keyframes_to_keyframes_name("y", None); - assert_ne!(crate::slot_reservation::unreserved_slot_count(), misses); - snapshot.restore(); - - assert_eq!(get_class_map(), classes); - assert_eq!(get_file_map(), files); - assert_eq!(crate::slot_reservation::unreserved_slot_count(), misses); + assert!(outer_events.borrow().is_empty()); } diff --git a/libs/css/src/slot_reservation.rs b/libs/css/src/slot_reservation.rs index fbdd8d6db..6fbce61b2 100644 --- a/libs/css/src/slot_reservation.rs +++ b/libs/css/src/slot_reservation.rs @@ -45,10 +45,6 @@ pub fn reset() { with_state(|state| *state = State::default()); } -pub(crate) fn current_state() -> State { - with_state(|state| *state) -} - pub(crate) fn replace_state(replacement: State) -> State { with_state(|state| std::mem::replace(state, replacement)) } diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index dabe20d72..94c8658e7 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -488,7 +488,6 @@ fn extract_with_source_map( if let ExtractTarget::Native(target) = option.target { return native::extract(filename, code, &option.package, target, source_map); } - let _extracting = css::numbering_order::extracting(); extract_source(filename, code, None, None, option, source_map, resolver) } @@ -1093,8 +1092,6 @@ fn extract_source( message += &changed_notes(&message, filename, source, &edits, &inlined.changed); return Err(message.into()); } - // Generating the code names nothing more - css::numbering_order::numbering_done(); let codegen_options = if source_map { CodegenOptions { source_map_path: Some(PathBuf::from(filename)), From 147a4c6436fd6bb5516a9b5e4e8d3364c1415cdd Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 5 Dec 2026 17:14:07 +0900 Subject: [PATCH 4/6] test(binding): check a batch commits each source before a later one names A source that imports global styles names them when it is committed. The test fails on the batch that committed only after extracting every source. Co-Authored-By: Claude Opus 5.5 --- libs/binding/tests/batch.rs | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/libs/binding/tests/batch.rs b/libs/binding/tests/batch.rs index 9e6f422fd..6d6778c86 100644 --- a/libs/binding/tests/batch.rs +++ b/libs/binding/tests/batch.rs @@ -502,3 +502,46 @@ fn workers_ask_the_resolver_once_for_each_import_of_each_source() { fn the_default_workers_are_the_cores_at_most_eight() { assert!((1..=8).contains(&devup_ui_binding_core::default_threads())); } + +/// Global styles a source reaches through an import are named when the +/// source is committed, after the sources extracted before it. +#[test] +#[serial] +fn a_batch_commits_each_source_before_a_later_one_names() { + let file = |name: &str, code: &str| (name.to_string(), code.to_string()); + let mut app = vec![ + file( + "src/reset.ts", + "import { globalCss } from '@devup-ui/react' +export function reset() { + globalCss({ body: { margin: 0 }, h1: { fontSize: '2em' }, '*': { boxSizing: 'border-box' } }) +} +", + ), + file( + "src/layout.tsx", + "import { Box } from '@devup-ui/react' +import { reset } from './reset' +reset() +export const Layout = () => +", + ), + ]; + for index in 0..6 { + app.push(file( + &format!("src/page{index}.tsx"), + &format!( + "import {{ Grid, Flex }} from '@devup-ui/react' +export const Page = () => +" + ), + )); + } + let expected = one_by_one(&app, false); + + for threads in [2, 4, 8] { + for _ in 0..4 { + assert_eq!(batch(&app, threads, false).0, expected, "{threads} threads"); + } + } +} From 82ebc879f5fb5aff73ee9f429632019a6bcc7aa4 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 5 Dec 2026 17:22:08 +0900 Subject: [PATCH 5/6] perf(binding): name what a commit names in the turn, and pass it at codegen again Holding each source's turn until its output was committed (acb950134) was correct but serialized code generation and the stylesheet commit: the large app's prewarm only went from 289 ms to about 200-230 ms. The turn passes at code generation again, and the batch commits on the calling thread in source order. What the commit would name first (global-bucket names of styles a source reaches through an import, for instance) is now named before the turn passes: the extractor walks the styles in the commit's order and scope (`name_as_committed`), so the commit only looks names up. Outside a batch the hook does nothing. Co-Authored-By: Claude Opus 5.5 --- libs/binding/src/batch.rs | 134 +++++++++++++--------- libs/binding/src/batch/tests.rs | 37 ++++++ libs/binding/tests/batch.rs | 5 - libs/css/src/file_map.rs | 1 + libs/css/src/numbering_order.rs | 156 +++++++++++++++++++++++--- libs/css/src/numbering_order/tests.rs | 116 +++++++++++++++++-- libs/css/src/slot_reservation.rs | 4 + libs/extractor/src/lib.rs | 18 +++ libs/extractor/src/style_collector.rs | 5 + 9 files changed, 388 insertions(+), 88 deletions(-) create mode 100644 libs/binding/src/batch/tests.rs diff --git a/libs/binding/src/batch.rs b/libs/binding/src/batch.rs index 0c7e8d51e..404a121da 100644 --- a/libs/binding/src/batch.rs +++ b/libs/binding/src/batch.rs @@ -1,13 +1,13 @@ //! Extract many sources at once, as extracting them one by one in their order //! would, but on several threads. //! -//! Worker threads take the sources in order and extract them at once. Each -//! numbers classes and files and commits its styles to the stylesheet only in -//! its turn (see [`css::numbering_order`]): from its first number on, until -//! the commit, no other source numbers, so every number and the stylesheet -//! come out as one by one. Parsing and resolving imports before that run at -//! once. The calling thread, the only one that may run the host's module -//! resolver, answers the workers' resolver requests. +//! Worker threads take the sources in order and extract them at once, each +//! numbering classes and files only in its turn (see +//! [`css::numbering_order`]), so every number comes out as one by one. The +//! calling thread, the only one that may run the host's module resolver, +//! answers the workers' resolver requests, then commits the outputs to the +//! stylesheet in source order. An extraction that numbered out of its turn +//! sends the whole batch back to extracting one by one. use std::cell::RefCell; use std::collections::HashMap; @@ -17,7 +17,7 @@ use std::sync::mpsc::{Receiver, Sender, SyncSender, channel, sync_channel}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread::{Builder, Scope, ScopedJoinHandle}; -use css::numbering_order::Turn; +use css::numbering_order::{Snapshot, Turn}; use extractor::{ ExtractOption, ExtractOutput, ResolvedModule, extract, extract_with_modules, extract_without_source_map, @@ -90,10 +90,11 @@ enum Event { importer: String, reply: SyncSender, }, - /// A source is extracted and committed. + /// A source is extracted, numbering only in its turn or not. Extracted { index: usize, - result: Result, + result: Result, + in_order: bool, }, } @@ -255,28 +256,6 @@ impl Turns { } } -/// Extract one source and commit it to the stylesheet, as one by one would. -/// -/// Committing names classes too, so it runs in the source's turn: `wait` -/// returns once every earlier source has ended its own. -fn extract_and_commit( - source: &BatchSource, - options: &BatchOptions, - ask: Option<&Ask>, - wait: impl FnOnce(), -) -> Result { - let extracted = extract_source(source, options, ask); - wait(); - let css = CssOptions { - single_css: options.option.single_css, - import_main_css: options.import_main_css_in_css, - }; - extracted.map(|output| Output { - css: None, - ..Output::new(output, source.filename.clone(), css) - }) -} - /// Extract the sources a worker takes, in order, until none are left. fn work( sources: &[BatchSource], @@ -296,21 +275,27 @@ fn work( break; }; let turn = turns.turn(index); - let result = extract_and_commit(source, options, ask.as_ref(), || turns.wait(index)); - drop(turn); + let result = extract_source(source, options, ask.as_ref()); + let in_order = turn.finish(); // The calling thread receives until every worker is done - let _ = events.send(Event::Extracted { index, result }); + let _ = events.send(Event::Extracted { + index, + result, + in_order, + }); } } /// Answer the workers' requests until every worker is done, returning what -/// they extracted in source order. +/// they extracted in source order and whether all of it numbered in turn. fn serve( events: &Receiver, ask: Option<&Ask>, sources: usize, -) -> Vec>> { - let mut extracted: Vec>> = (0..sources).map(|_| None).collect(); +) -> (Vec>>, bool) { + let mut extracted: Vec>> = + (0..sources).map(|_| None).collect(); + let mut in_order = true; for event in events { match event { Event::Resolve { @@ -322,13 +307,20 @@ fn serve( // A worker waits for every answer it asks for let _ = reply.send(answer); } - Event::Extracted { index, result } => extracted[index] = Some(result), + Event::Extracted { + index, + result, + in_order: ordered, + } => { + extracted[index] = Some(result); + in_order &= ordered; + } } } - extracted + (extracted, in_order) } -/// Start `threads` workers running `run` with their own handle to `events`. +/// Start up to `threads` workers. fn spawn<'scope>( scope: &'scope Scope<'scope, '_>, threads: usize, @@ -346,13 +338,13 @@ fn spawn<'scope>( .collect() } -/// Every source extracted on worker threads. A worker that panics fails -/// the batch with its panic, as extracting one by one would. +/// Every source extracted on worker threads, or `None` when one numbered out +/// of its turn or no worker extracted it. fn extract_parallel( sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>, -) -> Vec> { +) -> Option>> { let next = AtomicUsize::new(0); let turns = Arc::new(Turns::new(sources.len())); let answers = Arc::new(Answers::default()); @@ -366,41 +358,75 @@ fn extract_parallel( ); }; let (sender, events) = channel(); - let extracted = std::thread::scope(|scope| { + let (extracted, in_order) = std::thread::scope(|scope| { let workers = spawn(scope, options.threads.min(sources.len()), &sender, &run); drop(sender); let served = serve(&events, ask, sources.len()); for worker in workers { - if let Err(panic) = worker.join() { - std::panic::resume_unwind(panic); - } + // A worker that panicked left its source unextracted + let _ = worker.join(); } served }); - extracted.into_iter().flatten().collect() + in_order + .then(|| extracted.into_iter().collect::>>()) + .flatten() } -/// Every source extracted and committed one by one, in order. +/// Extract the sources one after another on this thread. fn extract_sequential( sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>, -) -> Vec> { +) -> Vec> { sources .iter() - .map(|source| extract_and_commit(source, options, ask, || {})) + .map(|source| extract_source(source, options, ask)) .collect() } +/// What the workers extracted, or when they could not, the numbering they +/// changed put back as `snapshot` holds it and every source extracted one by one. +fn or_one_by_one( + parallel: Option>, + snapshot: Snapshot, + one_by_one: impl FnOnce() -> Vec, +) -> Vec { + parallel.unwrap_or_else(|| { + snapshot.restore(); + one_by_one() + }) +} + /// Extract `sources` as extracting them one by one in their order would, /// resolving imports through `ask` on this thread. pub fn extract_batch(sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>) -> Batch { // Hoisted atoms are named from a plan the first extraction freezes let parallel = options.threads > 1 && css::atom_hoist::atom_hoist_threshold().is_none(); - let outputs = if parallel { - extract_parallel(sources, options, ask) + let extracted = if parallel { + let snapshot = Snapshot::take(); + or_one_by_one(extract_parallel(sources, options, ask), snapshot, || { + extract_sequential(sources, options, ask) + }) } else { extract_sequential(sources, options, ask) }; + let css = CssOptions { + single_css: options.option.single_css, + import_main_css: options.import_main_css_in_css, + }; + let outputs = sources + .iter() + .zip(extracted) + .map(|(source, extracted)| { + extracted.map(|output| Output { + css: None, + ..Output::new(output, source.filename.clone(), css) + }) + }) + .collect(); Batch { outputs, parallel } } + +#[cfg(test)] +mod tests; diff --git a/libs/binding/src/batch/tests.rs b/libs/binding/src/batch/tests.rs new file mode 100644 index 000000000..2cb27726a --- /dev/null +++ b/libs/binding/src/batch/tests.rs @@ -0,0 +1,37 @@ +use serial_test::serial; + +use super::*; + +#[test] +#[serial] +fn workers_that_could_not_extract_leave_the_numbering_to_one_by_one() { + crate::reset_state_internal(|| {}); + let _ = css::keyframes_to_keyframes_name("first", None); + let snapshot = Snapshot::take(); + let numbered = css::class_map::get_class_map(); + let _ = css::keyframes_to_keyframes_name("second", None); + + let extracted = or_one_by_one(None, snapshot, || vec![css::class_map::get_class_map()]); + + assert_eq!(extracted, [numbered]); +} + +#[test] +#[serial] +fn what_workers_extracted_stands() { + crate::reset_state_internal(|| {}); + let snapshot = Snapshot::take(); + let _ = css::keyframes_to_keyframes_name("kept", None); + + let extracted = or_one_by_one(Some(vec![1]), snapshot, || vec![2]); + + assert_eq!(extracted, [1]); + assert_eq!(css::class_map::get_class_map()[""].len(), 1); +} + +#[test] +fn the_default_workers_are_the_cores_at_most_eight() { + let threads = default_threads(); + + assert!((1..=MAX_DEFAULT_THREADS).contains(&threads)); +} diff --git a/libs/binding/tests/batch.rs b/libs/binding/tests/batch.rs index 6d6778c86..9b2fe8f5f 100644 --- a/libs/binding/tests/batch.rs +++ b/libs/binding/tests/batch.rs @@ -498,11 +498,6 @@ fn workers_ask_the_resolver_once_for_each_import_of_each_source() { assert_eq!(outcome, expected); } -#[test] -fn the_default_workers_are_the_cores_at_most_eight() { - assert!((1..=8).contains(&devup_ui_binding_core::default_threads())); -} - /// Global styles a source reaches through an import are named when the /// source is committed, after the sources extracted before it. #[test] diff --git a/libs/css/src/file_map.rs b/libs/css/src/file_map.rs index 7ce783a07..41131bfdf 100644 --- a/libs/css/src/file_map.rs +++ b/libs/css/src/file_map.rs @@ -86,6 +86,7 @@ pub fn get_file_num_by_filename(filename: &str) -> usize { // RefCell::borrow_mut contention); only fall back to the write guard on a // genuine miss. if let Some(file_num) = with_file_map(|map| map.get_by_left(filename).copied()) { + crate::numbering_order::observe(); return file_num; } crate::numbering_order::before_numbering(); diff --git a/libs/css/src/numbering_order.rs b/libs/css/src/numbering_order.rs index efedc3581..313cdd4a6 100644 --- a/libs/css/src/numbering_order.rs +++ b/libs/css/src/numbering_order.rs @@ -3,27 +3,54 @@ //! Class and file numbers are handed out first come, first served, so the //! order extractions number in decides them. Several threads can extract at //! once and still number as extracting one after another would, when each -//! extraction numbers only in its turn: from its first number until it ends, -//! no other extraction numbers. +//! extraction numbers only in its turn: from its first number to the point +//! where its outermost extraction has handed out its last, no other numbers. //! //! A thread starts an extraction's turn with [`Turn::begin`]. Its first -//! number waits for the turn, and ending the turn passes it on. What runs -//! before the first number (parsing, resolving imports) runs at once with the -//! other threads. +//! number waits for the turn, and [`numbering_done`], which the extractor calls +//! once the outermost extraction can hand out no more, names what committing +//! its styles to the stylesheet will and passes the turn on, as ending the +//! turn does. A number taken after that is out of order, and +//! [`Turn::finish`] reports it. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::marker::PhantomData; use std::rc::Rc; +use crate::class_map::{ClassMap, get_class_map, set_class_map}; +use crate::file_map::{FileMap, get_file_map, set_file_map}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Phase { + /// Has not numbered yet + Before, + /// Numbers in its turn + Numbering, + /// Passed its turn on + Passed, + /// Numbered after passing its turn on + OutOfOrder, +} + struct Ordered { - /// Whether the extraction waited for its turn - numbering: bool, + phase: Phase, wait: Box, pass: Box, } +impl Ordered { + fn pass_on(&mut self) { + if matches!(self.phase, Phase::Before | Phase::Numbering) { + (self.pass)(); + self.phase = Phase::Passed; + } + } +} + thread_local! { static ORDERED: RefCell> = const { RefCell::new(None) }; + /// How many extractions run inside one another on this thread + static DEPTH: Cell = const { Cell::new(0) }; } /// One extraction's turn to number on this thread. @@ -34,10 +61,11 @@ pub struct Turn { impl Turn { /// Start an extraction whose first number calls `wait`, which returns once - /// it is the extraction's turn; ending the turn calls `pass` to pass it on. + /// it is the extraction's turn, and which calls `pass` once to pass the + /// turn on, by the end at the latest. pub fn begin(wait: impl Fn() + 'static, pass: impl Fn() + 'static) -> Self { ORDERED.set(Some(Ordered { - numbering: false, + phase: Phase::Before, wait: Box::new(wait), pass: Box::new(pass), })); @@ -45,29 +73,123 @@ impl Turn { thread_bound: PhantomData, } } + + /// End the turn, passing it on if it was not, and return whether the + /// extraction numbered only in its turn. + pub fn finish(self) -> bool { + ORDERED.with_borrow_mut(|ordered| { + ordered.as_mut().is_none_or(|ordered| { + ordered.pass_on(); + ordered.phase != Phase::OutOfOrder + }) + }) + } } impl Drop for Turn { fn drop(&mut self) { - if let Some(ordered) = ORDERED.take() { - (ordered.pass)(); + if let Some(mut ordered) = ORDERED.take() { + ordered.pass_on(); } } } /// Wait for this thread's turn before handing out a number. -/// -/// Callers hold no lock: an earlier extraction numbers until its turn ends. pub(crate) fn before_numbering() { + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered { + match ordered.phase { + Phase::Before => { + (ordered.wait)(); + ordered.phase = Phase::Numbering; + } + Phase::Numbering | Phase::OutOfOrder => {} + Phase::Passed => ordered.phase = Phase::OutOfOrder, + } + } + }); +} + +/// Note that this thread read a number already handed out. +/// +/// Before the turn it was handed out by an extraction ordered earlier, as +/// only those number before this turn; after it, maybe by a later one. +pub(crate) fn observe() { ORDERED.with_borrow_mut(|ordered| { if let Some(ordered) = ordered - && !ordered.numbering + && ordered.phase == Phase::Passed { - (ordered.wait)(); - ordered.numbering = true; + ordered.phase = Phase::OutOfOrder; } }); } +/// The outermost extraction on this thread hands out no more numbers but +/// what `name_committed` names: in its turn, run it, then pass the turn on. +/// +/// Committing the extraction's styles names classes too; naming them in the +/// turn leaves the commit, which can come after later extractions, nothing +/// new to name. +pub fn numbering_done(name_committed: impl FnOnce()) { + let in_turn = DEPTH.get() == 1 + && ORDERED.with_borrow(|ordered| { + ordered + .as_ref() + .is_some_and(|ordered| matches!(ordered.phase, Phase::Before | Phase::Numbering)) + }); + if in_turn { + name_committed(); + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered { + ordered.pass_on(); + } + }); + } +} + +/// Marks an extraction running on this thread, inside any it runs within. +#[must_use] +pub struct Extracting { + thread_bound: PhantomData>, +} + +/// Enter an extraction; only the outermost one passes the turn on. +pub fn extracting() -> Extracting { + DEPTH.set(DEPTH.get() + 1); + Extracting { + thread_bound: PhantomData, + } +} + +impl Drop for Extracting { + fn drop(&mut self) { + DEPTH.set(DEPTH.get() - 1); + } +} + +/// The class and file numbering as it was, to number again from. +pub struct Snapshot { + classes: ClassMap, + files: FileMap, + reservation: crate::slot_reservation::State, +} + +impl Snapshot { + pub fn take() -> Self { + Self { + classes: get_class_map(), + files: get_file_map(), + reservation: crate::slot_reservation::current_state(), + } + } + + /// Make the numbering what it was when taken. + pub fn restore(self) { + set_class_map(self.classes); + set_file_map(self.files); + crate::slot_reservation::replace_state(self.reservation); + } +} + #[cfg(test)] mod tests; diff --git a/libs/css/src/numbering_order/tests.rs b/libs/css/src/numbering_order/tests.rs index 0e803c854..e0f1a0438 100644 --- a/libs/css/src/numbering_order/tests.rs +++ b/libs/css/src/numbering_order/tests.rs @@ -21,23 +21,29 @@ fn recorded_turn() -> (Turn, Rc>>) { #[test] #[serial] -fn the_first_number_waits_for_the_turn_and_ending_it_passes_it() { +fn the_first_number_waits_for_the_turn_and_the_outermost_extraction_passes_it() { let _state = TestStateGuard::new(); let (turn, events) = recorded_turn(); + let outer = extracting(); assert!(events.borrow().is_empty()); let _ = keyframes_to_keyframes_name("x", None); let _ = keyframes_to_keyframes_name("y", None); assert_eq!(*events.borrow(), ["wait"]); - - drop(turn); - assert_eq!(*events.borrow(), ["wait", "pass"]); - let _ = keyframes_to_keyframes_name("z", None); + let inner = extracting(); + numbering_done(|| {}); assert_eq!( *events.borrow(), - ["wait", "pass"], - "numbers outside a turn wait for none" + ["wait"], + "a nested extraction keeps the turn" ); + drop(inner); + numbering_done(|| {}); + assert_eq!(*events.borrow(), ["wait", "pass"]); + drop(outer); + + assert!(turn.finish()); + assert_eq!(*events.borrow(), ["wait", "pass"]); } #[test] @@ -52,10 +58,37 @@ fn a_file_number_handed_out_waits_for_the_turn_but_one_read_does_not() { assert_eq!(get_file_num_by_filename("b.tsx"), 1); assert_eq!(*events.borrow(), ["wait"]); - drop(turn); + assert!(turn.finish()); assert_eq!(*events.borrow(), ["wait", "pass"]); } +#[test] +#[serial] +fn numbering_after_passing_the_turn_is_out_of_order() { + let _state = TestStateGuard::new(); + let (turn, _) = recorded_turn(); + let _extracting = extracting(); + numbering_done(|| {}); + let _ = keyframes_to_keyframes_name("x", None); + let _ = keyframes_to_keyframes_name("y", None); + + assert!(!turn.finish()); +} + +#[test] +#[serial] +fn reading_a_file_number_after_passing_the_turn_is_out_of_order() { + let _state = TestStateGuard::new(); + let _ = get_file_num_by_filename("a.tsx"); + let (turn, events) = recorded_turn(); + let _extracting = extracting(); + numbering_done(|| {}); + let _ = get_file_num_by_filename("a.tsx"); + + assert!(!turn.finish()); + assert_eq!(*events.borrow(), ["pass"]); +} + #[test] #[serial] fn a_turn_that_never_numbers_passes_once_it_ends() { @@ -64,17 +97,76 @@ fn a_turn_that_never_numbers_passes_once_it_ends() { drop(turn); assert_eq!(*events.borrow(), ["pass"]); + let _ = keyframes_to_keyframes_name("x", None); + assert_eq!( + *events.borrow(), + ["pass"], + "numbers outside a turn wait for none" + ); } #[test] #[serial] -fn a_turn_ended_by_a_later_one_on_the_thread_passes_once() { +fn a_turn_ended_by_a_later_one_numbered_in_order() { let _state = TestStateGuard::new(); - let (outer, outer_events) = recorded_turn(); + let (outer, _) = recorded_turn(); let (inner, events) = recorded_turn(); drop(inner); - drop(outer); + assert!(outer.finish()); assert_eq!(*events.borrow(), ["pass"]); - assert!(outer_events.borrow().is_empty()); +} + +#[test] +#[serial] +fn a_snapshot_restores_the_numbering_it_was_taken_of() { + let _state = TestStateGuard::new(); + crate::slot_reservation::ScratchSlots::default().commit(); + let _ = get_file_num_by_filename("a.tsx"); + let _ = keyframes_to_keyframes_name("x", None); + let snapshot = Snapshot::take(); + let (classes, files, misses) = ( + get_class_map(), + get_file_map(), + crate::slot_reservation::unreserved_slot_count(), + ); + + let _ = get_file_num_by_filename("b.tsx"); + let _ = keyframes_to_keyframes_name("y", None); + assert_ne!(crate::slot_reservation::unreserved_slot_count(), misses); + snapshot.restore(); + + assert_eq!(get_class_map(), classes); + assert_eq!(get_file_map(), files); + assert_eq!(crate::slot_reservation::unreserved_slot_count(), misses); +} + +#[test] +#[serial] +fn the_outermost_extraction_names_what_it_commits_in_its_turn_only() { + let _state = TestStateGuard::new(); + let named = Rc::new(RefCell::new(0)); + let name = || { + let named = Rc::clone(&named); + move || *named.borrow_mut() += 1 + }; + numbering_done(name()); + assert_eq!(*named.borrow(), 0, "no turn"); + + let (turn, events) = recorded_turn(); + let outer = extracting(); + let inner = extracting(); + numbering_done(name()); + assert_eq!(*named.borrow(), 0, "a nested extraction"); + drop(inner); + numbering_done(|| { + *named.borrow_mut() += 1; + let _ = keyframes_to_keyframes_name("committed", None); + }); + assert_eq!(*named.borrow(), 1); + assert_eq!(*events.borrow(), ["wait", "pass"]); + numbering_done(name()); + assert_eq!(*named.borrow(), 1, "a turn passed on"); + drop(outer); + assert!(turn.finish()); } diff --git a/libs/css/src/slot_reservation.rs b/libs/css/src/slot_reservation.rs index 6fbce61b2..fbdd8d6db 100644 --- a/libs/css/src/slot_reservation.rs +++ b/libs/css/src/slot_reservation.rs @@ -45,6 +45,10 @@ pub fn reset() { with_state(|state| *state = State::default()); } +pub(crate) fn current_state() -> State { + with_state(|state| *state) +} + pub(crate) fn replace_state(replacement: State) -> State { with_state(|state| std::mem::replace(state, replacement)) } diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 94c8658e7..f386efb0e 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -488,6 +488,7 @@ fn extract_with_source_map( if let ExtractTarget::Native(target) = option.target { return native::extract(filename, code, &option.package, target, source_map); } + let _extracting = css::numbering_order::extracting(); extract_source(filename, code, None, None, option, source_map, resolver) } @@ -1092,6 +1093,10 @@ fn extract_source( message += &changed_notes(&message, filename, source, &edits, &inlined.changed); return Err(message.into()); } + // Generating the code names nothing more + css::numbering_order::numbering_done(|| { + name_as_committed(visitor.styles.styles(), filename, option.single_css); + }); let codegen_options = if source_map { CodegenOptions { source_map_path: Some(PathBuf::from(filename)), @@ -1142,6 +1147,19 @@ fn extract_source( }) } +/// Name the classes of `styles` as committing them to the stylesheet does: +/// in their order, in the global bucket for a single or global stylesheet and +/// in the file's bucket otherwise. +fn name_as_committed(styles: &FxHashSet, filename: &str, single_css: bool) { + let _atom_mode = css::atom_hoist::AtomModeGuard::new(single_css); + let scope = (!(single_css || is_global(filename))).then(|| canonical(filename)); + let mut ordered: Vec<&ExtractStyleValue> = styles.iter().collect(); + ordered.sort_unstable(); + for style in ordered { + let _ = style.extract(scope.as_deref()); + } +} + /// Build the shared `devup-ui.css` main-css path for a given css directory. /// /// Single source of truth for the `"{css_dir}/devup-ui.css"` literal, used both diff --git a/libs/extractor/src/style_collector.rs b/libs/extractor/src/style_collector.rs index d9dbe95c8..a602a7701 100644 --- a/libs/extractor/src/style_collector.rs +++ b/libs/extractor/src/style_collector.rs @@ -76,6 +76,11 @@ impl StyleCollector { /// The styles of `file`, with the order of its layers when it uses any #[must_use] + /// The styles collected so far. + pub const fn styles(&self) -> &FxHashSet { + &self.styles + } + pub fn into_styles(mut self, file: &str) -> FxHashSet { if !self.layers.is_empty() { self.styles From 55092947b6c69cf3e1ed0d525e7c361b14555673 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 5 Dec 2026 18:55:15 +0900 Subject: [PATCH 6/6] fix(binding): commit each source before the next when a batch runs one by one A batch on one thread, under atom hoisting, or after a source numbered out of turn extracted every source first and committed them all afterwards. Committing a source can hand out the first number of a style, such as a global style a layout reaches through an import, so later sources took those numbers first and class names differed from extracting one by one. The one-by-one path now commits each source right after extracting it. `Batch::parallel` now tells whether the outputs come from worker threads, so a batch that fell back no longer reports itself parallel. The workers' channel is created inside the thread scope, so a resolver that panics on the calling thread fails the batch instead of leaving workers waiting for an answer. The doc and `#[must_use]` of `StyleCollector::into_styles` are back on it. Co-Authored-By: Claude Opus 5.5 --- libs/binding/src/batch.rs | 84 +++++++++++++++++---------- libs/binding/src/batch/tests.rs | 4 +- libs/binding/tests/batch.rs | 28 ++++++++- libs/extractor/src/style_collector.rs | 5 +- 4 files changed, 84 insertions(+), 37 deletions(-) diff --git a/libs/binding/src/batch.rs b/libs/binding/src/batch.rs index 404a121da..4549cbb80 100644 --- a/libs/binding/src/batch.rs +++ b/libs/binding/src/batch.rs @@ -78,7 +78,8 @@ pub type Ask = Rc HostAnswer>; /// the next source changes the sheet, and a batch serializes none. pub struct Batch { pub outputs: Vec>, - /// Whether the sources were extracted on worker threads. + /// Whether the outputs come from worker threads: not when the batch ran + /// one by one from the start, or again after a source numbered out of turn. pub parallel: bool, } @@ -357,8 +358,9 @@ fn extract_parallel( (events, resolves), ); }; - let (sender, events) = channel(); let (extracted, in_order) = std::thread::scope(|scope| { + // Dropped here should serving unwind, so no worker waits for an answer + let (sender, events) = channel(); let workers = spawn(scope, options.threads.min(sources.len()), &sender, &run); drop(sender); let served = serve(&events, ask, sources.len()); @@ -373,58 +375,76 @@ fn extract_parallel( .flatten() } -/// Extract the sources one after another on this thread. +/// Commit an extracted source to the stylesheet, keeping no CSS. +fn commit( + source: &BatchSource, + extracted: Result, + css: CssOptions, +) -> Result { + extracted.map(|output| Output { + css: None, + ..Output::new(output, source.filename.clone(), css) + }) +} + +/// Extract the sources one after another on this thread, committing each +/// before extracting the next: committing a source can name classes too. fn extract_sequential( sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>, -) -> Vec> { + css: CssOptions, +) -> Vec> { sources .iter() - .map(|source| extract_source(source, options, ask)) + .map(|source| commit(source, extract_source(source, options, ask), css)) .collect() } -/// What the workers extracted, or when they could not, the numbering they -/// changed put back as `snapshot` holds it and every source extracted one by one. +/// What the workers extracted and that they did, or when they could not, the +/// numbering they changed put back as `snapshot` holds it and every source +/// extracted one by one. fn or_one_by_one( parallel: Option>, snapshot: Snapshot, one_by_one: impl FnOnce() -> Vec, -) -> Vec { - parallel.unwrap_or_else(|| { - snapshot.restore(); - one_by_one() - }) +) -> (Vec, bool) { + parallel.map_or_else( + || { + snapshot.restore(); + (one_by_one(), false) + }, + |parallel| (parallel, true), + ) } /// Extract `sources` as extracting them one by one in their order would, /// resolving imports through `ask` on this thread. pub fn extract_batch(sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>) -> Batch { - // Hoisted atoms are named from a plan the first extraction freezes - let parallel = options.threads > 1 && css::atom_hoist::atom_hoist_threshold().is_none(); - let extracted = if parallel { - let snapshot = Snapshot::take(); - or_one_by_one(extract_parallel(sources, options, ask), snapshot, || { - extract_sequential(sources, options, ask) - }) - } else { - extract_sequential(sources, options, ask) - }; let css = CssOptions { single_css: options.option.single_css, import_main_css: options.import_main_css_in_css, }; - let outputs = sources - .iter() - .zip(extracted) - .map(|(source, extracted)| { - extracted.map(|output| Output { - css: None, - ..Output::new(output, source.filename.clone(), css) - }) - }) - .collect(); + // Hoisted atoms are named from a plan the first extraction freezes + if options.threads < 2 || css::atom_hoist::atom_hoist_threshold().is_some() { + return Batch { + outputs: extract_sequential(sources, options, ask, css), + parallel: false, + }; + } + let snapshot = Snapshot::take(); + // Each worker named what committing its source names in its turn, so the + // sources are committed in order once all are extracted + let parallel = extract_parallel(sources, options, ask).map(|extracted| { + sources + .iter() + .zip(extracted) + .map(|(source, extracted)| commit(source, extracted, css)) + .collect() + }); + let (outputs, parallel) = or_one_by_one(parallel, snapshot, || { + extract_sequential(sources, options, ask, css) + }); Batch { outputs, parallel } } diff --git a/libs/binding/src/batch/tests.rs b/libs/binding/src/batch/tests.rs index 2cb27726a..b152b054c 100644 --- a/libs/binding/src/batch/tests.rs +++ b/libs/binding/src/batch/tests.rs @@ -13,7 +13,7 @@ fn workers_that_could_not_extract_leave_the_numbering_to_one_by_one() { let extracted = or_one_by_one(None, snapshot, || vec![css::class_map::get_class_map()]); - assert_eq!(extracted, [numbered]); + assert_eq!(extracted, (vec![numbered], false)); } #[test] @@ -25,7 +25,7 @@ fn what_workers_extracted_stands() { let extracted = or_one_by_one(Some(vec![1]), snapshot, || vec![2]); - assert_eq!(extracted, [1]); + assert_eq!(extracted, (vec![1], true)); assert_eq!(css::class_map::get_class_map()[""].len(), 1); } diff --git a/libs/binding/tests/batch.rs b/libs/binding/tests/batch.rs index 9b2fe8f5f..48b0ba3cd 100644 --- a/libs/binding/tests/batch.rs +++ b/libs/binding/tests/batch.rs @@ -534,9 +534,35 @@ export const Page = () => } let expected = one_by_one(&app, false); - for threads in [2, 4, 8] { + for threads in [1, 2, 4, 8] { for _ in 0..4 { assert_eq!(batch(&app, threads, false).0, expected, "{threads} threads"); } } } + +/// A resolver that panics on the calling thread fails the batch: no worker +/// waits for an answer it can no longer get. +#[test] +#[serial] +fn a_resolver_that_panics_fails_the_batch_without_hanging() { + let app = app(); + set_up(&app); + let ask: Ask = Rc::new(|_: &str, _: &str| panic!("resolver panicked")); + let sources = sources(&app); + + let batch = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + extract_batch( + &sources, + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: true, + threads: 8, + }, + Some(&ask), + ) + })); + + assert!(batch.is_err()); +} diff --git a/libs/extractor/src/style_collector.rs b/libs/extractor/src/style_collector.rs index a602a7701..5cdca75a8 100644 --- a/libs/extractor/src/style_collector.rs +++ b/libs/extractor/src/style_collector.rs @@ -74,13 +74,14 @@ impl StyleCollector { self.styles.is_empty() && self.layers.is_empty() } - /// The styles of `file`, with the order of its layers when it uses any - #[must_use] /// The styles collected so far. + #[must_use] pub const fn styles(&self) -> &FxHashSet { &self.styles } + /// The styles of `file`, with the order of its layers when it uses any + #[must_use] pub fn into_styles(mut self, file: &str) -> FxHashSet { if !self.layers.is_empty() { self.styles