Commit 9ee76fd5 authored by Luke Sandberg's avatar Luke Sandberg

Revert style_production.rs to simple emit-on-first-encounter

The contiguity check in compute_style_batches guarantees that no two
distinct batches can interleave in any route's ordering. This means the
original simple approach — emit each batch/item on first encounter in DFS
order — produces correct CSS cascade ordering without needing the
topological sort over emission units.

This removes ~170 lines of complexity (EmissionUnit enum, Kahn's algorithm,
module_dependents propagation to StyleGroups) that is no longer needed.
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 7a211f2d
use std::{cmp::Reverse, collections::BinaryHeap};
use anyhow::Result; use anyhow::Result;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::FxHashSet;
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::rcstr; use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use crate::{ use crate::{
chunk::{ chunk::{
ChunkItemBatchGroup, ChunkItemBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkItemBatchGroup, ChunkItemWithAsyncModuleInfo, ChunkingConfig, ChunkingContext,
ChunkableModule, ChunkingConfig, ChunkingContext,
chunking::{ChunkItemOrBatchWithInfo, SplitContext, make_chunk}, chunking::{ChunkItemOrBatchWithInfo, SplitContext, make_chunk},
}, },
module_graph::{ModuleGraph, style_groups::StyleGroupsConfig}, module_graph::{ModuleGraph, style_groups::StyleGroupsConfig},
}; };
/// An emission unit is either a shared style batch or a single non-shared chunk item.
/// The topological sort in `make_style_production_chunks` operates over these units.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum EmissionUnit {
Batch(ResolvedVc<ChunkItemBatchWithAsyncModuleInfo>),
Item(ChunkItemWithAsyncModuleInfo),
}
pub async fn make_style_production_chunks( pub async fn make_style_production_chunks(
chunk_items: Vec<&ChunkItemOrBatchWithInfo>, chunk_items: Vec<&ChunkItemOrBatchWithInfo>,
_batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>, _batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>,
...@@ -44,168 +33,44 @@ pub async fn make_style_production_chunks( ...@@ -44,168 +33,44 @@ pub async fn make_style_production_chunks(
}, },
) )
.await?; .await?;
let mut handled = FxHashSet::default();
// `style_groups` has computed shared batches from the CSS chunk items across all let mut handle_chunk_item = async |chunk_item: &ChunkItemWithAsyncModuleInfo| {
// endpoints. We need to emit chunks for this endpoint in an order that respects the if let Some(&batch) = style_groups.shared_chunk_items.get(chunk_item) {
// CSS cascade: if module X must precede module Y, then X's emission unit (batch or if handled.insert(batch) {
// individual chunk) must be emitted before Y's.
//
// We cannot simply follow the DFS post-order of `chunk_items`, because a shared batch
// groups members whose DFS positions may interleave with non-shared items. For example,
// if DFS order is [A, B, C], {A, C} form a shared batch, and B is non-shared, emitting
// at the last member gives [B, {A,C}] — wrong, because A must precede B.
//
// Instead, we:
// 1. Build a module → EmissionUnit map for all CSS items in this endpoint.
// 2. Translate the module-level dependency edges from `style_groups.module_dependents` into
// emission-unit edges.
// 3. Topologically sort the emission units (Kahn's algorithm, DFS post-order as tiebreaker
// for determinism).
// 4. Emit chunks in the sorted order.
// --- Step 1: collect all ChunkItemWithAsyncModuleInfo for this endpoint ---
// We also record each item's DFS position (index) so we can use it as a tiebreaker.
let mut all_items: Vec<ChunkItemWithAsyncModuleInfo> = Vec::new();
for chunk_item in &chunk_items {
match chunk_item {
ChunkItemOrBatchWithInfo::ChunkItem { chunk_item, .. } => {
all_items.push(chunk_item.clone());
}
ChunkItemOrBatchWithInfo::Batch { batch, .. } => {
for item in &batch.await?.chunk_items {
all_items.push(item.clone());
}
}
}
}
// --- Step 2: build module → EmissionUnit and module → DFS position maps ---
// The DFS position is the index in `all_items` (already in DFS post-order).
let mut module_to_unit: FxHashMap<ResolvedVc<Box<dyn ChunkableModule>>, EmissionUnit> =
FxHashMap::default();
// Track the earliest DFS position for each emission unit (for tiebreaking).
let mut unit_min_pos: FxHashMap<EmissionUnit, usize> = FxHashMap::default();
for (pos, item) in all_items.iter().enumerate() {
let Some(module) = item.module else { continue };
let unit = if let Some(&batch) = style_groups.shared_chunk_items.get(item) {
EmissionUnit::Batch(batch)
} else {
EmissionUnit::Item(item.clone())
};
module_to_unit.insert(module, unit.clone());
unit_min_pos
.entry(unit)
.and_modify(|p| *p = (*p).min(pos))
.or_insert(pos);
}
// Collect the full set of emission units in this endpoint (in stable order for indexing).
let units: Vec<EmissionUnit> = {
let mut seen = FxHashSet::default();
let mut ordered = Vec::new();
for item in &all_items {
let Some(module) = item.module else { continue };
if let Some(unit) = module_to_unit.get(&module)
&& seen.insert(unit.clone())
{
ordered.push(unit.clone());
}
}
ordered
};
let unit_index: FxHashMap<EmissionUnit, usize> = units
.iter()
.enumerate()
.map(|(i, u)| (u.clone(), i))
.collect::<FxHashMap<_, _>>();
let n = units.len();
// --- Step 3: build the emission-unit dependency graph ---
// edge: src → dst means src must be emitted before dst.
let mut adj: Vec<FxHashSet<usize>> = vec![FxHashSet::default(); n];
let mut in_degree: Vec<usize> = vec![0; n];
for (module, dependents) in &style_groups.module_dependents {
let Some(src_unit) = module_to_unit.get(module) else {
continue;
};
let src_idx = unit_index[src_unit];
for dep_module in dependents {
let Some(dst_unit) = module_to_unit.get(dep_module) else {
continue;
};
if src_unit == dst_unit {
continue; // same unit, no edge needed
}
let dst_idx = unit_index[dst_unit];
if adj[src_idx].insert(dst_idx) {
in_degree[dst_idx] += 1;
}
}
}
// --- Step 4: Kahn's algorithm, using a min-heap on `unit_min_pos` as tiebreaker ---
// The heap stores (min_pos, unit_index) so that among units with in-degree 0,
// we always pick the one that appeared earliest in the DFS post-order.
let mut heap: BinaryHeap<Reverse<(usize, usize)>> = BinaryHeap::new();
for (i, unit) in units.iter().enumerate() {
if in_degree[i] == 0 {
let pos = unit_min_pos.get(unit).copied().unwrap_or(usize::MAX);
heap.push(Reverse((pos, i)));
}
}
let mut sorted: Vec<usize> = Vec::with_capacity(n);
while let Some(Reverse((_, idx))) = heap.pop() {
sorted.push(idx);
for &neighbor in &adj[idx] {
in_degree[neighbor] -= 1;
if in_degree[neighbor] == 0 {
let pos = unit_min_pos
.get(&units[neighbor])
.copied()
.unwrap_or(usize::MAX);
heap.push(Reverse((pos, neighbor)));
}
}
}
debug_assert_eq!(
sorted.len(),
n,
"Topological sort did not visit all emission units; cycle in CSS dependency graph?"
);
// --- Step 5: emit chunks in topological order ---
for idx in sorted {
match &units[idx] {
EmissionUnit::Batch(batch) => {
make_chunk( make_chunk(
vec![&ChunkItemOrBatchWithInfo::Batch { vec![&ChunkItemOrBatchWithInfo::Batch { batch, size: 0 }],
batch: *batch,
size: 0,
}],
vec![],
&mut String::new(),
&mut split_context,
)
.await?;
}
EmissionUnit::Item(chunk_item) => {
make_chunk(
vec![&ChunkItemOrBatchWithInfo::ChunkItem {
chunk_item: chunk_item.clone(),
size: 0,
asset_ident: rcstr!(""),
}],
vec![], vec![],
&mut String::new(), &mut String::new(),
&mut split_context, &mut split_context,
) )
.await?; .await?;
} }
} else {
make_chunk(
vec![&ChunkItemOrBatchWithInfo::ChunkItem {
chunk_item: chunk_item.clone(),
size: 0,
asset_ident: rcstr!(""),
}],
vec![],
&mut String::new(),
&mut split_context,
)
.await?;
} }
anyhow::Ok(())
};
for chunk_item in chunk_items {
match chunk_item {
ChunkItemOrBatchWithInfo::ChunkItem { chunk_item, .. } => {
handle_chunk_item(chunk_item).await?;
}
ChunkItemOrBatchWithInfo::Batch { batch, .. } => {
for chunk_item in &batch.await?.chunk_items {
handle_chunk_item(chunk_item).await?;
}
}
};
} }
Ok(()) Ok(())
......
...@@ -22,12 +22,6 @@ use crate::{ ...@@ -22,12 +22,6 @@ use crate::{
}, },
}; };
/// Maps each CSS module to the set of CSS modules that must be emitted after it.
pub type ModuleDependents = FxHashMap<
ResolvedVc<Box<dyn ChunkableModule>>,
FxHashSet<ResolvedVc<Box<dyn ChunkableModule>>>,
>;
#[derive( #[derive(
TaskInput, Debug, Clone, PartialEq, Eq, Hash, NonLocalValue, TraceRawVcs, Encode, Decode, TaskInput, Debug, Clone, PartialEq, Eq, Hash, NonLocalValue, TraceRawVcs, Encode, Decode,
)] )]
...@@ -46,13 +40,6 @@ pub struct StyleGroups { ...@@ -46,13 +40,6 @@ pub struct StyleGroups {
#[bincode(with = "turbo_bincode::indexmap")] #[bincode(with = "turbo_bincode::indexmap")]
pub shared_chunk_items: pub shared_chunk_items:
FxIndexMap<ChunkItemWithAsyncModuleInfo, ResolvedVc<ChunkItemBatchWithAsyncModuleInfo>>, FxIndexMap<ChunkItemWithAsyncModuleInfo, ResolvedVc<ChunkItemBatchWithAsyncModuleInfo>>,
/// For each CSS module, the set of CSS modules that must be emitted after it (its dependents
/// in cascade order). A module X maps to {Y, Z, ...} meaning X must be loaded before Y and Z.
///
/// This is used by `style_production.rs` to topologically sort emission units (shared batches
/// and non-shared items) into a correct CSS cascade order, taking into account that a shared
/// batch may group items whose DFS post-order positions interleave with non-shared items.
pub module_dependents: ModuleDependents,
} }
/// Information about a CSS module and its presence across chunk groups. /// Information about a CSS module and its presence across chunk groups.
...@@ -130,7 +117,6 @@ pub(crate) struct BatchingModuleInfo { ...@@ -130,7 +117,6 @@ pub(crate) struct BatchingModuleInfo {
/// share a single CSS chunk. Only multi-module batches are included. /// share a single CSS chunk. Only multi-module batches are included.
pub(crate) struct BatchingResult { pub(crate) struct BatchingResult {
pub batches: Vec<Vec<usize>>, pub batches: Vec<Vec<usize>>,
pub module_dependents: FxHashMap<usize, FxHashSet<usize>>,
} }
/// Pure algorithmic core of the style-groups batching algorithm. /// Pure algorithmic core of the style-groups batching algorithm.
...@@ -355,10 +341,7 @@ pub(crate) fn compute_style_batches( ...@@ -355,10 +341,7 @@ pub(crate) fn compute_style_batches(
} }
} }
BatchingResult { BatchingResult { batches }
batches,
module_dependents,
}
} }
pub async fn compute_style_groups( pub async fn compute_style_groups(
...@@ -561,23 +544,7 @@ pub async fn compute_style_groups( ...@@ -561,23 +544,7 @@ pub async fn compute_style_groups(
} }
} }
// Convert module_dependents back to ResolvedVc keys Ok(StyleGroups { shared_chunk_items }.cell())
let module_dependents: ModuleDependents = result
.module_dependents
.into_iter()
.map(|(k, deps)| {
(
idx_to_vc[k],
deps.into_iter().map(|d| idx_to_vc[d]).collect(),
)
})
.collect();
Ok(StyleGroups {
shared_chunk_items,
module_dependents,
}
.cell())
} }
#[cfg(test)] #[cfg(test)]
...@@ -852,73 +819,7 @@ mod tests { ...@@ -852,73 +819,7 @@ mod tests {
); );
} }
// ---- Test 5a: Dependents computation — universal predecessor ---- // ---- Test 5: Contiguity allows absorbing all intervening modules ----
#[test]
fn test_dependents_universal_predecessor() {
// Route 0: [A(0), B(1), C(2)]
// Route 1: [A(0), B(1)]
//
// A appears before B in all routes B is in → A is a dependency of B.
// A appears before C in all routes C is in (only route 0) → A is a dep of C.
// B appears before C in all routes C is in (only route 0) → B is a dep of C.
let iso = StyleType::IsolatedStyle;
let (info, styles) = make_inputs(
&[(iso, 100), (iso, 100), (iso, 100)],
&[&[0, 1, 2], &[0, 1]],
);
let result = compute_style_batches(&info, &styles, 1_000_000);
let deps_a = result
.module_dependents
.get(&0)
.cloned()
.unwrap_or_default();
assert!(deps_a.contains(&1), "A should have B as dependent");
assert!(deps_a.contains(&2), "A should have C as dependent");
let deps_b = result
.module_dependents
.get(&1)
.cloned()
.unwrap_or_default();
assert!(deps_b.contains(&2), "B should have C as dependent");
let deps_c = result
.module_dependents
.get(&2)
.cloned()
.unwrap_or_default();
assert!(deps_c.is_empty(), "C should have no dependents");
}
// ---- Test 5b: Non-universal appearance blocks dependent relationship ----
#[test]
fn test_dependents_non_universal_blocks() {
// Route 0: [A(0), B(1)]
// Route 1: [B(1)]
//
// A is only in route 0. B is in routes 0 and 1.
// A is NOT a dependency of B because A doesn't appear in route 1 where B does.
// (info.chunk_group_indices.len() >= dep.chunk_group_indices.len() fails: 1 < 2)
let iso = StyleType::IsolatedStyle;
let (info, styles) = make_inputs(&[(iso, 100), (iso, 100)], &[&[0, 1], &[1]]);
let result = compute_style_batches(&info, &styles, 1_000_000);
let deps_a = result
.module_dependents
.get(&0)
.cloned()
.unwrap_or_default();
assert!(
!deps_a.contains(&1),
"A should NOT be a dependency of B (A missing from route 1), got A deps: {:?}",
deps_a
);
}
// ---- Test 6: Contiguity allows absorbing all intervening modules ----
#[test] #[test]
fn test_contiguity_absorbs_intervening_modules() { fn test_contiguity_absorbs_intervening_modules() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment