Unverified Commit e2fca6c6 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[Turbopack] Add graph-based CSS chunking algorithm behind…

[Turbopack] Add graph-based CSS chunking algorithm behind experimental.cssChunking: "graph" (#93606)

### What?

Adds an alternative CSS chunking algorithm to Turbopack, opted into via:

```js
// next.config.js
module.exports = {
  experimental: {
    cssChunking: 'graph',
    // or, with explicit cost overrides:
    // cssChunking: { type: 'graph', requestCost: 20_000, moduleFactorCost: 1 },
  },
}
```

The new algorithm is **off by default** — Turbopack still uses the
existing
"loose"/dependencies algorithm unless this flag is set, so this PR is a
pure
addition for users that don't opt in.

While we were here, the `experimental.cssChunking` shape was also
generalized
so every existing string accepts an object form too:

| Value | Bundler | Notes |
|---|---|---|
| `true` / `'loose'` / `{ type: 'loose' }` | both | default
heuristic-based chunking |
| `'strict'` / `{ type: 'strict' }` | webpack | unchanged |
| `false` | webpack | unchanged (one chunk per CSS module) |
| `'graph'` / `{ type: 'graph', requestCost?, moduleFactorCost? }` |
Turbopack | new |

Cross-bundler combinations are rejected at config-validation time:
- `'graph'` with webpack throws.
- `'strict'` and `false` with Turbopack throw.

### Why?

The existing Turbopack CSS chunker (loose / dependencies) is good at
preserving CSS ordering but doesn't share chunks across pages well —
every
page tends to load its own chunk per CSS module, which scales poorly for
apps
with many pages and shared component libraries.

The new "graph" algorithm models the per-chunk-group CSS ordering as a
weighted DAG over modules, then greedily merges adjacent runs in the
global
topological order whenever the merge reduces total cost. The cost model
charges every CSS request and overshipped byte, with two tunable knobs
(`requestCost` and `moduleFactorCost`).

**Trade-off vs. the loose default.** With the default cost parameters
(`requestCost: 20_000`, `moduleFactorCost: 1`) the graph algorithm
typically
ships **less CSS per chunk group at the cost of more requests** than the
loose algorithm. The cost model is tuned to avoid overshipping unrelated
CSS
into pages that don't need it; on apps where the loose algorithm was
already
collapsing a lot into one big chunk that some pages didn't actually use,
the
graph algorithm will split it. Apps that prefer fewer requests can raise
`requestCost`; apps that prefer less overshipping can raise
`moduleFactorCost`.

This is opt-in and Turbopack-only because:
- The cost model is sensitive to per-app properties (number of pages,
size
distribution of CSS modules, …) — keeping it experimental gives us room
to
  tune defaults from real usage.
- Webpack already has its own `CssChunkingPlugin` and `'strict'` mode
that
  cover the equivalent design space; we don't want to fork that.

### Performance

Measured on `vercel.com` (the full graph algorithm spans
`create_graph → make_acyclic → linearize → split_into_chunks →
assemble`):

- **~3s** end-to-end for the synchronous chunking pipeline on a
realistic
  production input.

Implementation choices that matter for that throughput:

- Tarjan SCC uses `Vec<u32>` / `Vec<bool>` scratch arrays indexed by
  `NodeIndex` — no hashing on `indices` / `lowlinks` / `on_stack`.
- `make_acyclic` batches multiple cuts per SCC pass by seeding
successive
short-cycle searches at the previous cut's target, only re-running
Tarjan
  when no further cycle is reachable from the seed.
- `find_short_cycle` is a bidirectional Dijkstra over a `BinaryHeap`
with
predecessor pointers (no path cloning) and skips its refinement loop for
  trivial 2-cycles.
- `split_into_chunks` picks the next merge from a `BinaryHeap` keyed on
the
  cost delta instead of an O(N) linear scan per merge.
- `chunk_cost` reads a once-built `module_to_groups` inverse index
instead of
scanning every chunk group on every call; the GlobalStyle leakage check
uses binary search on the inverse index rather than scanning each
group's
  module list.

### How?

#### Module layout (`turbopack/crates/turbopack-core/src/module_graph/`)

The two algorithms are deliberately split so neither imports from the
other:

- `style_groups/` — algorithm-neutral output types (`StyleGroups`,
  `StyleItemInfo`, `make_style_groups`). Both algorithms produce these.
- `style_groups_loose/` — the existing ("loose") algorithm plus the
shared
  config types (`StyleGroupsAlgorithm`, `StyleGroupsConfig`,
  `F32TaskInput`).
- `style_groups_graph/` — the new algorithm. Pure Rust, no `Vc`, with
  `petgraph::DiGraph` plus a thin `SubgraphView` wrapper and a small
  `ReadonlyGraph` trait that lets the same pipeline run against either a
  `&DiGraph` or a filtered view of one SCC.

#### Algorithm

```text
create_graph → make_acyclic → linearize → split_into_chunks → assemble batches
```

1. **`create_graph`** — for each chunk group, every `(later, earlier)`
pair
   inside the group's CSS-module list becomes an edge `later → earlier`
   (weight 1, accumulated). Heavy edges = strong co-occurrence.
2. **`make_acyclic`** — co-occurrence almost always introduces cycles;
each
multi-node SCC has its lowest-weight cycle edge cut until the graph is a
   DAG.
3. **`linearize`** — Kahn-style topological sort with a tie-break on
edge
weight, so strongly co-occurring modules end up adjacent in the global
   order.
4. **`split_into_chunks`** — greedy bottom-up merger over the global
order.
   At every active split point we score the merge as
`cost(merged) - cost(left) - cost(right)`, take the most-negative score
   from a min-heap, and repeat until no merge would reduce cost.
   `max_chunk_size` and "global CSS must not leak into unrelated chunk
   groups" are enforced as `+infinity` cost.

The cost model is:

```text
cost_per_group(chunk, group)
  = chunk_size
  + (chunk_size / group_total_size) * module_factor_cost
  + request_cost
```

summed over the chunk groups that load the chunk.

#### Wiring

- `StyleGroups::shared_chunk_items` is a
  `FxIndexMap<ChunkItemWithAsyncModuleInfo, StyleItemInfo>` where
  `StyleItemInfo { order: Option<u32>, batch: Option<…> }`. The graph
algorithm fills `order` so `style_production.rs` can stable-sort chunks
globally; the legacy algorithm leaves `order = None`, which makes the
sort
a no-op for it. `flatten_and_sort` returns the `StyleItemInfo`
references
alongside each chunk item so the per-item loop doesn't re-query the map.
- A new `StyleGroupsAlgorithm` enum on `ChunkingConfig` selects the
  algorithm at chunking time; `ModuleGraph::style_groups` dispatches
to either `compute_style_groups` (existing) or
`compute_style_groups_graph`
  (new).
- `next-core` exposes `NextConfig::css_chunking() ->
Vc<CssChunkingAlgorithm>`
resolving the JS `experimental.cssChunking` to the Rust enum, with cost
defaults applied (`requestCost: 20_000`, `moduleFactorCost: 1`). All
three
  chunking-context constructors (`next_client`, `next_edge`,
  `next_server`) thread it through.

#### Configuration

- `experimental.cssChunking` zod schema accepts the new shapes; cost
params
  are `z.number().nonnegative().finite().optional()`.
- `config-shared.ts` exports a `CssChunkingConfig` type alias and a
`resolveCssChunkingMode(value)` helper that normalizes any input to one
of `'off' | 'loose' | 'strict' | 'graph'`. Both `webpack-config.ts`
(plugin
  wiring) and `config.ts` (bundler-compat validation) use the helper.
- New `errors.json` entries for the three bundler-compatibility
validation
  errors (E1193 graph-on-webpack, E1194 strict-on-Turbopack, E1195
  false-on-Turbopack).

#### Tests

- 53 Rust unit tests in `style_groups_graph/tests.rs` cover
`create_graph`,
Tarjan SCC, `find_short_cycle` (bidirectional Dijkstra), `make_acyclic`,
  `linearize`, `split_into_chunks`, and end-to-end pipeline scenarios.
- `test/e2e/app-dir/css-order/css-order.test.ts` is parametrised over
`[label, value]` pairs. The Turbopack matrix now includes `'graph'` and
an
object-form `{ type: 'graph', requestCost: 1, moduleFactorCost: 1 }` in
addition to the existing default. Per-page expectations grew a
`requests`
object encoding distinct request counts for `loose` and `graph` where
they
  differ.
- A new `sandwich` e2e fixture (`/sandwich/a`, `/sandwich/b`) exercises
the
case where two pages share a leading and trailing chunk around a unique
middle stylesheet — including a global stylesheet that the algorithm
must
not leak into unrelated chunk groups. The graph algorithm hits the
optimal
  3 chunks per page on this fixture; loose mode falls short.

#### Documentation

- `ExperimentalConfig.cssChunking` JSDoc describes every accepted shape
and
  what each cost knob does.
- The `style_groups_graph` module-level docs describe the pipeline, cost
  model and constraints with diagrams.

Closes NEXT-

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarv-work-app[bot] <262237222+v-work-app[bot]@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
parent 7da98e13
......@@ -1594,6 +1594,7 @@ impl Project {
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
cross_origin: self.next_config().cross_origin(),
chunk_loading_global: self.next_config().turbopack_chunk_loading_global(),
style_groups_algorithm: self.next_config().css_chunking().owned().await?,
}))
}
......@@ -1629,6 +1630,7 @@ impl Project {
asset_prefix: self.next_config().computed_asset_prefix().owned().await?,
css_url_suffix,
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
style_groups_algorithm: self.next_config().css_chunking().owned().await?,
};
Ok(if client_assets {
get_server_chunking_context_with_client_assets(options)
......@@ -1669,6 +1671,7 @@ impl Project {
css_url_suffix,
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
cross_origin: self.next_config().cross_origin(),
style_groups_algorithm: self.next_config().css_chunking().owned().await?,
};
Ok(if client_assets {
get_edge_chunking_context_with_client_assets(options)
......
......@@ -23,7 +23,9 @@ use turbopack_core::{
environment::{BrowserEnvironment, Environment, ExecutionEnvironment},
free_var_references,
issue::IssueSeverity,
module_graph::binding_usage_info::OptionBindingUsageInfo,
module_graph::{
binding_usage_info::OptionBindingUsageInfo, style_groups::StyleGroupsAlgorithm,
},
resolve::{parse::Request, pattern::Pattern},
};
use turbopack_css::chunk::CssChunkType;
......@@ -476,6 +478,7 @@ pub struct ClientChunkingContextOptions {
pub hash_salt: ResolvedVc<RcStr>,
pub cross_origin: Vc<CrossOrigin>,
pub chunk_loading_global: Vc<Option<RcStr>>,
pub style_groups_algorithm: StyleGroupsAlgorithm,
}
#[turbo_tasks::function]
......@@ -505,6 +508,7 @@ pub async fn get_client_chunking_context(
hash_salt,
cross_origin,
chunk_loading_global,
style_groups_algorithm,
} = options;
let next_mode = mode.await?;
......@@ -575,6 +579,7 @@ pub async fn get_client_chunking_context(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
max_merge_chunk_size: 100_000,
style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default()
},
)
......
......@@ -26,6 +26,7 @@ use turbopack_core::{
issue::{
IgnoreIssue, IgnoreIssuePattern, Issue, IssueExt, IssueSeverity, IssueStage, StyledString,
},
module_graph::style_groups::StyleGroupsAlgorithm,
resolve::ResolveAliasMap,
};
use turbopack_ecmascript::{OptionTreeShaking, TreeShakingMode};
......@@ -1040,6 +1041,135 @@ pub struct TurbopackIgnoreIssueRule {
pub description: Option<TurbopackIgnoreIssueTextPattern>,
}
/// `experimental.cssChunking` accepts the following shapes (all normalized to a single canonical
/// object form via [`CssChunkingConfig::normalize`]):
///
/// * `true` — equivalent to `{ type: "loose" }` (default loose behaviour).
/// * `false` — disabled chunking.
/// * `"strict"` / `"loose"` / `"graph"` — string shorthands.
/// * `{ type: "strict" }` / `{ type: "loose" }` — object form for the legacy modes.
/// * `{ type: "graph", requestCost?, moduleFactorCost? }` — object form for the graph algorithm.
#[derive(
Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode,
)]
#[serde(untagged)]
pub enum CssChunkingConfig {
Bool(bool),
String(CssChunkingMode),
Object(CssChunkingObject),
}
/// String shorthand variants for [`CssChunkingConfig`].
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Deserialize,
TraceRawVcs,
NonLocalValue,
OperationValue,
Encode,
Decode,
)]
#[serde(rename_all = "lowercase")]
pub enum CssChunkingMode {
Strict,
Loose,
Graph,
}
/// Object form of `experimental.cssChunking`.
///
/// `None` is the normalized representation of `false` ("CSS chunking is disabled"). It is not
/// reachable through deserialization — users write `false`, not `{ type: "none" }`.
#[derive(
Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode,
)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum CssChunkingObject {
#[serde(skip)]
None,
Strict,
Loose,
Graph(CssChunkingGraphOptions),
}
/// Cost parameters for the graph algorithm. See [`CssChunkingConfig`] for details.
#[derive(
Clone,
Debug,
Default,
PartialEq,
Deserialize,
TraceRawVcs,
NonLocalValue,
OperationValue,
Encode,
Decode,
)]
#[serde(rename_all = "camelCase")]
pub struct CssChunkingGraphOptions {
pub request_cost: Option<f32>,
pub module_factor_cost: Option<f32>,
}
impl CssChunkingConfig {
/// Normalize all input shapes (booleans, strings, object form) to the canonical object form.
/// `false` maps to [`CssChunkingObject::None`]; `true` is equivalent to `'loose'`.
pub fn normalize(&self) -> CssChunkingObject {
match self {
CssChunkingConfig::Bool(false) => CssChunkingObject::None,
CssChunkingConfig::Bool(true) => CssChunkingObject::Loose,
CssChunkingConfig::String(CssChunkingMode::Strict) => CssChunkingObject::Strict,
CssChunkingConfig::String(CssChunkingMode::Loose) => CssChunkingObject::Loose,
CssChunkingConfig::String(CssChunkingMode::Graph) => {
CssChunkingObject::Graph(CssChunkingGraphOptions::default())
}
CssChunkingConfig::Object(obj) => obj.clone(),
}
}
}
/// Default `requestCost` for the graph algorithm (in bytes).
const DEFAULT_REQUEST_COST: f32 = 20_000.0;
/// Default `moduleFactorCost` for the graph algorithm.
const DEFAULT_MODULE_FACTOR_COST: f32 = 1.0;
/// Resolve `experimental.cssChunking` to the [`StyleGroupsAlgorithm`] Turbopack should use.
///
/// `strict` and `false` (`CssChunkingObject::None`) are bundler-incompatible with Turbopack and
/// are rejected at config-validation time on the JS side; if one slips through, we bail rather
/// than silently falling back. `loose` and `true` map to [`StyleGroupsAlgorithm::Default`].
fn resolve_css_chunking_algorithm(
config: Option<&CssChunkingConfig>,
) -> Result<StyleGroupsAlgorithm> {
let Some(config) = config else {
return Ok(StyleGroupsAlgorithm::Default);
};
Ok(match config.normalize() {
CssChunkingObject::None => {
anyhow::bail!(
"`experimental.cssChunking: false` is not supported by Turbopack; this should \
have been rejected at config validation time"
)
}
CssChunkingObject::Strict => {
anyhow::bail!(
"`experimental.cssChunking: \"strict\"` is not supported by Turbopack; this \
should have been rejected at config validation time"
)
}
CssChunkingObject::Loose => StyleGroupsAlgorithm::Default,
CssChunkingObject::Graph(opts) => StyleGroupsAlgorithm::graph(
opts.request_cost.unwrap_or(DEFAULT_REQUEST_COST),
opts.module_factor_cost
.unwrap_or(DEFAULT_MODULE_FACTOR_COST),
),
})
}
#[derive(
Clone,
Debug,
......@@ -1097,6 +1227,9 @@ pub struct ExperimentalConfig {
/// no salt.
output_hash_salt: Option<RcStr>,
/// CSS chunking strategy. See [`CssChunkingConfig`] for the accepted shapes.
css_chunking: Option<CssChunkingConfig>,
// ---
// UNSUPPORTED
// ---
......@@ -1817,6 +1950,13 @@ impl NextConfig {
Vc::cell(self.experimental.inline_css.unwrap_or(false))
}
/// Resolve `experimental.cssChunking` to a [`StyleGroupsAlgorithm`] (with defaults applied
/// for the cost parameters of the graph algorithm).
#[turbo_tasks::function]
pub fn css_chunking(&self) -> Result<Vc<StyleGroupsAlgorithm>> {
Ok(resolve_css_chunking_algorithm(self.experimental.css_chunking.as_ref())?.cell())
}
#[turbo_tasks::function]
pub fn mdx_rs(&self) -> Vc<OptionalMdxTransformOptions> {
let options = &self.experimental.mdx_rs;
......
......@@ -13,7 +13,9 @@ use turbopack_core::{
environment::{EdgeWorkerEnvironment, Environment, ExecutionEnvironment, NodeJsVersion},
free_var_references,
issue::IssueSeverity,
module_graph::binding_usage_info::OptionBindingUsageInfo,
module_graph::{
binding_usage_info::OptionBindingUsageInfo, style_groups::StyleGroupsAlgorithm,
},
};
use turbopack_css::chunk::CssChunkType;
use turbopack_ecmascript::chunk::EcmascriptChunkType;
......@@ -202,6 +204,7 @@ pub struct EdgeChunkingContextOptions {
pub css_url_suffix: Vc<Option<RcStr>>,
pub hash_salt: ResolvedVc<RcStr>,
pub cross_origin: Vc<CrossOrigin>,
pub style_groups_algorithm: StyleGroupsAlgorithm,
}
/// Like `get_edge_chunking_context` but all assets are emitted as client assets (so `/_next`)
......@@ -229,6 +232,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
css_url_suffix,
hash_salt,
cross_origin,
style_groups_algorithm,
} = options;
let cross_origin_loading = *cross_origin.await?;
let output_root = node_root.join("server/edge")?;
......@@ -280,6 +284,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
max_merge_chunk_size: 100_000,
style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default()
},
)
......@@ -314,6 +319,7 @@ pub async fn get_edge_chunking_context(
css_url_suffix,
hash_salt,
cross_origin,
style_groups_algorithm,
} = options;
let cross_origin = *cross_origin.await?;
let css_url_suffix = css_url_suffix.to_resolved().await?;
......@@ -382,6 +388,7 @@ pub async fn get_edge_chunking_context(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
max_merge_chunk_size: 100_000,
style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default()
},
)
......
......@@ -22,7 +22,9 @@ use turbopack_core::{
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReferences},
environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion},
issue::IssueSeverity,
module_graph::binding_usage_info::OptionBindingUsageInfo,
module_graph::{
binding_usage_info::OptionBindingUsageInfo, style_groups::StyleGroupsAlgorithm,
},
target::CompileTarget,
};
use turbopack_css::chunk::CssChunkType;
......@@ -1021,6 +1023,7 @@ pub struct ServerChunkingContextOptions {
pub asset_prefix: RcStr,
pub css_url_suffix: Vc<Option<RcStr>>,
pub hash_salt: ResolvedVc<RcStr>,
pub style_groups_algorithm: StyleGroupsAlgorithm,
}
/// Like `get_server_chunking_context` but all assets are emitted as client assets (so `/_next`)
......@@ -1048,6 +1051,7 @@ pub async fn get_server_chunking_context_with_client_assets(
asset_prefix,
css_url_suffix,
hash_salt,
style_groups_algorithm,
} = options;
let css_url_suffix = css_url_suffix.to_resolved().await?;
......@@ -1117,6 +1121,7 @@ pub async fn get_server_chunking_context_with_client_assets(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
max_merge_chunk_size: 100_000,
style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default()
},
)
......@@ -1151,6 +1156,7 @@ pub async fn get_server_chunking_context(
asset_prefix,
css_url_suffix,
hash_salt,
style_groups_algorithm,
} = options;
let css_url_suffix = css_url_suffix.to_resolved().await?;
let next_mode = mode.await?;
......@@ -1221,6 +1227,7 @@ pub async fn get_server_chunking_context(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
max_merge_chunk_size: 100_000,
style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default()
},
)
......
......@@ -1244,5 +1244,8 @@
"1243": "This \"use cache\" has a dynamic cache life that was propagated to its parent.",
"1244": "A \"use cache\" with short \\`expire\\` (under 5 minutes) is nested inside another \"use cache\" that has no explicit \\`cacheLife\\`, which is not allowed during prerendering. Add \\`cacheLife()\\` to the outer \"use cache\" to choose whether it should be prerendered (with longer \\`expire\\`) or remain dynamic (with short \\`expire\\`). Read more: https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife",
"1245": "A \"use cache\" with zero \\`revalidate\\` is nested inside another \"use cache\" that has no explicit \\`cacheLife\\`, which is not allowed during prerendering. Add \\`cacheLife()\\` to the outer \"use cache\" to choose whether it should be prerendered (with non-zero \\`revalidate\\`) or remain dynamic (with zero \\`revalidate\\`). Read more: https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife",
"1246": "Could not validate instant UI because an expected segment was not rendered."
"1246": "Could not validate instant UI because an expected segment was not rendered.",
"1247": "\\`experimental.cssChunking: \"graph\"\\` is only supported with Turbopack. Please remove the option or run Next.js with Turbopack in %s.",
"1248": "\\`experimental.cssChunking: \"strict\"\\` is only supported with webpack. Please remove the option or run Next.js with webpack in %s.",
"1249": "\\`experimental.cssChunking: false\\` is only supported with webpack. Please remove the option or run Next.js with webpack in %s."
}
......@@ -32,6 +32,7 @@ import {
import type { CompilerNameValues } from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
import type { NextConfigComplete } from '../server/config-shared'
import { resolveCssChunkingMode } from '../server/config-shared'
import { finalizeEntrypoint } from './entries'
import * as Log from './output/log'
import { buildConfiguration } from './webpack/config'
......@@ -2188,17 +2189,21 @@ export default async function getBaseWebpackConfig(
new NextFontManifestPlugin({
appDir,
}),
// CSS chunking plugin. Graph mode is Turbopack-only and is rejected at config-validation
// time for webpack, so we only need to wire up `'loose'` (default) and `'strict'` here.
!dev &&
isClient &&
config.experimental.cssChunking &&
(isRspack
? new (getRspackCore().experiments.CssChunkingPlugin)({
strict: config.experimental.cssChunking === 'strict',
nextjs: true,
})
: new CssChunkingPlugin(
config.experimental.cssChunking === 'strict'
)),
(() => {
const mode = resolveCssChunkingMode(config.experimental.cssChunking)
if (mode !== 'loose' && mode !== 'strict') return false
const strict = mode === 'strict'
return isRspack
? new (getRspackCore().experiments.CssChunkingPlugin)({
strict,
nextjs: true,
})
: new CssChunkingPlugin(strict)
})(),
telemetryPlugin,
!dev &&
isNodeServer &&
......
......@@ -272,7 +272,21 @@ export const experimentalSchema = {
middlewareClientMaxBodySize: zSizeLimit.optional(),
proxyClientMaxBodySize: zSizeLimit.optional(),
multiZoneDraftMode: z.boolean().optional(),
cssChunking: z.union([z.boolean(), z.literal('strict')]).optional(),
cssChunking: z
.union([
z.boolean(),
z.literal('strict'),
z.literal('loose'),
z.literal('graph'),
z.strictObject({ type: z.literal('strict') }),
z.strictObject({ type: z.literal('loose') }),
z.strictObject({
type: z.literal('graph'),
requestCost: z.number().nonnegative().finite().optional(),
moduleFactorCost: z.number().nonnegative().finite().optional(),
}),
])
.optional(),
nextScriptWorkers: z.boolean().optional(),
// The critter option is unknown, use z.any() here
optimizeCss: z.union([z.boolean(), z.any()]).optional(),
......
......@@ -405,6 +405,40 @@ export interface LightningCssFeatures {
exclude?: LightningCssFeature[]
}
/**
* Accepted shapes for `experimental.cssChunking`. See [`ExperimentalConfig.cssChunking`] for the
* accepted values; use [`resolveCssChunkingMode`] to normalize the value at runtime.
*/
export type CssChunkingConfig =
| boolean
| 'strict'
| 'loose'
| 'graph'
| { type: 'strict' }
| { type: 'loose' }
| { type: 'graph'; requestCost?: number; moduleFactorCost?: number }
/**
* Normalize any [`CssChunkingConfig`] value to one of the four modes the build pipeline cares
* about:
* - `'off'` — `false`/`undefined`: do not run a CSS chunking plugin.
* - `'loose'` — `true` / `'loose'` / `{ type: 'loose' }`: heuristic-based chunking
* (the default).
* - `'strict'` — `'strict'` / `{ type: 'strict' }`: webpack-only ordered-chunking plugin.
* - `'graph'` — `'graph'` / `{ type: 'graph', … }`: Turbopack-only graph algorithm.
*/
export function resolveCssChunkingMode(
value: CssChunkingConfig | undefined
): 'off' | 'loose' | 'strict' | 'graph' {
if (value === undefined || value === false) return 'off'
if (value === true || value === 'loose') return 'loose'
if (value === 'strict' || value === 'graph') return value
// Object form. `requestCost` and `moduleFactorCost` are validated by the schema.
if (value.type === 'strict') return 'strict'
if (value.type === 'graph') return 'graph'
return 'loose'
}
export interface ExperimentalConfig {
/**
* A string that is incorporated into content-addressed output filenames
......@@ -508,12 +542,27 @@ export interface ExperimentalConfig {
proxyPrefetch?: 'strict' | 'flexible'
manualClientBasePath?: boolean
/**
* CSS Chunking strategy. Defaults to `true` ("loose" mode), which guesses dependencies
* between CSS files to keep ordering of them.
* An alternative is 'strict', which will try to keep correct ordering as
* much as possible, even when this leads to many requests.
*/
cssChunking?: boolean | 'strict'
* CSS Chunking strategy. Defaults to `true` (loose mode), which guesses dependencies between
* CSS files to keep ordering of them.
*
* - `true` / `'loose'` / `{ type: 'loose' }` — default heuristic-based chunking.
* - `'strict'` / `{ type: 'strict' }` — preserve correct ordering as much as possible, even
* when this leads to many requests. Webpack only.
* - `false` — disable chunking; emit one chunk per CSS module. Webpack only.
* - `'graph'` / `{ type: 'graph', requestCost?, moduleFactorCost? }` — Turbopack only.
* Selects a CSS chunking strategy that analyzes the most common style orderings across the
* application and produces shared chunks accordingly. Compared to the default mode it
* intentionally overships some styles in order to reduce the number of CSS requests per
* page. Cost overrides:
* - `requestCost` (bytes, default `20000`) — additional cost charged for every CSS
* request a chunk group makes. Larger values bias the algorithm toward fewer, larger
* shared chunks; smaller values toward more, smaller chunks.
* - `moduleFactorCost` (default `1`) — controls how much the algorithm cares about
* small chunk groups. `0` distributes overshipped bytes evenly across chunk groups.
* Higher values penalize overshipping in small chunk groups proportionally more, so
* small pages ship fewer unrelated styles at the expense of more requests overall.
*/
cssChunking?: CssChunkingConfig
disablePostcssPresetEnv?: boolean
cpus?: number
memoryBasedWorkersCount?: boolean
......
......@@ -13,7 +13,11 @@ import {
PHASE_PRODUCTION_SERVER,
type PHASE_TYPE,
} from '../shared/lib/constants'
import { defaultConfig, normalizeConfig } from './config-shared'
import {
defaultConfig,
normalizeConfig,
resolveCssChunkingMode,
} from './config-shared'
import type {
ExperimentalConfig,
NextConfigComplete,
......@@ -456,6 +460,35 @@ function assignDefaultsAndValidate(
)
}
// Validate experimental.cssChunking compatibility with the active bundler. Graph mode is
// Turbopack-only; strict mode and `false` (single-chunk-per-module) are webpack-only.
// Only validate during build/dev — `next start` doesn't pick a bundler and would otherwise
// see `process.env.TURBOPACK` unset and reject a valid `cssChunking: "graph"` config.
if (phase !== PHASE_PRODUCTION_SERVER) {
const cssChunkingValue = result.experimental.cssChunking
const cssChunkingMode = resolveCssChunkingMode(cssChunkingValue)
if (cssChunkingMode === 'graph' && !process.env.TURBOPACK) {
throw new Error(
`\`experimental.cssChunking: "graph"\` is only supported with Turbopack. ` +
`Please remove the option or run Next.js with Turbopack in ${configFileName}.`
)
}
if (cssChunkingMode === 'strict' && process.env.TURBOPACK) {
throw new Error(
`\`experimental.cssChunking: "strict"\` is only supported with webpack. ` +
`Please remove the option or run Next.js with webpack in ${configFileName}.`
)
}
// Only error when `false` was set explicitly. `undefined` (the default) also resolves to
// `'off'` but that's the implicit default and must not error on Turbopack.
if (cssChunkingValue === false && process.env.TURBOPACK) {
throw new Error(
`\`experimental.cssChunking: false\` is only supported with webpack. ` +
`Please remove the option or run Next.js with webpack in ${configFileName}.`
)
}
}
if (result.experimental.cachedNavigations && !result.cacheComponents) {
throw new Error(
`\`experimental.cachedNavigations\` requires \`cacheComponents\` to be enabled. Please update your ${configFileName} accordingly.`
......
......@@ -86,6 +86,16 @@ export default function Nav() {
Partial Reversed B
</Link>
</li>
<li>
<Link href={'/sandwich/a'} id="sandwich-a" prefetch={false}>
Sandwich A
</Link>
</li>
<li>
<Link href={'/sandwich/b'} id="sandwich-b" prefetch={false}>
Sandwich B
</Link>
</li>
<li>
<Link href={'/global-first'} id="global-first" prefetch={false}>
Global First
......
import shared1 from '../shared1.module.css'
import uniqueA from '../uniqueA.module.css'
import shared2 from '../shared2.module.css'
import Nav from '../../nav'
export default function Page() {
return (
<div>
<p
className={`${shared1.name} ${uniqueA.name} ${shared2.name}`}
id="hellosba"
>
hello world
</p>
<Nav />
</div>
)
}
import shared1 from '../shared1.module.css'
import '../uniqueB.css'
import shared2 from '../shared2.module.css'
import Nav from '../../nav'
export default function Page() {
return (
<div>
<p
className={`${shared1.name} sandwich-b-marker ${shared2.name}`}
id="hellosbb"
>
hello world
</p>
<Nav />
</div>
)
}
/* Global CSS used by `/sandwich/b` only. Its purpose is to prevent the chunking algorithm from
collapsing all sandwich styles into one shared chunk: a global stylesheet must not be loaded by
chunk groups that don't import it (`/sandwich/a`), so the algorithm has to keep `uniqueB`
isolated. */
.sandwich-b-marker {
outline: 1px solid rgb(255, 128, 0);
}
......@@ -30,6 +30,7 @@ const PAGES: Record<
brokenLoadingDev?: boolean
requests?: number
requestsLoose?: number
requestsGraph?: number
}
> = {
first: {
......@@ -133,6 +134,44 @@ const PAGES: Record<
background: 'rgba(0, 0, 0, 0)',
requests: 4,
},
// Two pages where shared CSS modules sandwich a unique stylesheet:
// /sandwich/a: shared1 → uniqueA (module) → shared2
// /sandwich/b: shared1 → uniqueB (GLOBAL) → shared2
// The chunker must not merge shared1 and shared2 into a single chunk because they sit on
// either side of the unique stylesheet. uniqueB is a global stylesheet specifically so the
// algorithm can't collapse everything into one big shared chunk: a global stylesheet must
// never be loaded by chunk groups that don't import it (i.e. `/sandwich/a`), so uniqueB has
// to stay isolated.
'sandwich-a': {
group: 'sandwich',
url: '/sandwich/a',
selector: '#hellosba',
color: 'rgb(0, 0, 255)',
// 2 requests = `shared1 + uniqueA` fused into one chunk + `shared2` separate (still shared
// with /sandwich/b). 3 requests is a valid alternative (no overshipping; better cache reuse
// of shared1 across pages), but strict & graph here both prefer overshipping uniqueA.
requests: 2,
requestsLoose: 1,
// Same as `requests`, but spelled out so `requestsLoose` doesn't shadow it via the fallback
// chain in `expectedRequests`.
requestsGraph: 2,
},
'sandwich-b': {
group: 'sandwich',
url: '/sandwich/b',
selector: '#hellosbb',
color: 'rgb(0, 0, 255)',
// 3 requests is forced: uniqueB is a global stylesheet so it can't fuse with the CSS
// modules on either side. shared1 and shared2 each stay in their own chunk so they can be
// shared with /sandwich/a.
requests: 3,
// TODO loose merges shared1 and shared2 into a single chunk despite uniqueB sitting
// between them on the page; the correct value is 3 (matching `requests`).
requestsLoose: 2,
// Same as `requests`, but spelled out so `requestsLoose` doesn't shadow it via the fallback
// chain in `expectedRequests`.
requestsGraph: 3,
},
'pages-first': {
group: 'pages-basic',
url: '/pages/first',
......@@ -240,43 +279,113 @@ const PAGES: Record<
const allPairs = getPairs(Object.keys(PAGES))
const options = (mode: string) => ({
// Each entry is `[label, value]`, where `label` is shown in test names and `value` is what gets
// written into `experimental.cssChunking` (or `undefined` to leave it unset, which is the
// existing Turbopack default).
type GraphCssChunkingObject = {
type: 'graph'
requestCost?: number
moduleFactorCost?: number
}
type CssChunkingValue =
| boolean
| 'strict'
| 'loose'
| 'graph'
| GraphCssChunkingObject
| undefined
type Mode = readonly [string, CssChunkingValue]
const TURBO_MODES: readonly Mode[] = [
['turbo', undefined],
['graph', 'graph'],
// Verifies the object form is accepted. We pass the algorithm's defaults so the chunk shape
// matches the plain `'graph'` row, letting us reuse the same `requestsGraph` expectations.
['graph-object', { type: 'graph', requestCost: 20_000, moduleFactorCost: 1 }],
]
const WEBPACK_MODES_TRUE: readonly Mode[] = [
['strict', 'strict'],
['true', true],
]
const WEBPACK_MODES_LOOSE: readonly Mode[] = [
['strict', 'strict'],
['loose', 'loose'],
]
function isGraphMode(value: CssChunkingValue): boolean {
return (
value === 'graph' ||
(typeof value === 'object' && value !== null && value.type === 'graph')
)
}
function isStrictMode(value: CssChunkingValue): boolean {
return value === 'strict'
}
const options = (value: CssChunkingValue) => ({
files: {
app: new FileRef(path.join(__dirname, 'app')),
pages: new FileRef(path.join(__dirname, 'pages')),
'next.config.js': process.env.IS_TURBOPACK_TEST
? `
module.exports = {}`
: `
module.exports = {
experimental: {
cssChunking: ${JSON.stringify(mode)}
}
}`,
'next.config.js':
value === undefined
? `module.exports = {}`
: `module.exports = { experimental: { cssChunking: ${JSON.stringify(value)} } }`,
},
dependencies: {
sass: 'latest',
},
skipDeployment: true,
})
describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', true])(
/**
* Number of CSS request expected for a page in the given mode. Falls back from the most-specific
* to the most-generic per-page expectation.
*/
function expectedRequests(
value: CssChunkingValue,
pageInfo: {
requests?: number
requestsLoose?: number
requestsGraph?: number
}
): number | undefined {
if (isGraphMode(value)) {
return pageInfo.requestsGraph ?? pageInfo.requestsLoose ?? pageInfo.requests
}
if (isStrictMode(value)) {
return pageInfo.requests
}
// `undefined` (Turbopack default), `true`, or `'loose'` all map to loose.
return pageInfo.requestsLoose ?? pageInfo.requests
}
/**
* Whether a given ordering should be skipped because at least one page in the ordering has a
* conflict that the active chunking mode can't preserve. `'strict'` preserves ordering for
* conflict scenarios; everything else does not.
*/
function shouldSkipConflict(ordering: readonly string[]): boolean {
return ordering
.map((page) => PAGES[page])
.some((page) =>
process.env.IS_TURBOPACK_TEST
? page.conflictTurbo || page.conflict
: page.conflict
)
}
describe.each(process.env.IS_TURBOPACK_TEST ? TURBO_MODES : WEBPACK_MODES_TRUE)(
'css-order %s',
(mode: string) => {
const { next, isNextDev, skipped } = nextTestSetup(options(mode))
(_label: string, value: CssChunkingValue) => {
const { next, isNextDev, skipped } = nextTestSetup(options(value))
if (skipped) return
for (const ordering of allPairs) {
const name = `should load correct styles navigating back again ${ordering.join(
' -> '
)} -> ${ordering.join(' -> ')}`
if (
ordering
.map((page) => PAGES[page])
.some((page) =>
mode === 'turbo'
? page.conflictTurbo || page.conflict
: page.conflict
)
) {
if (shouldSkipConflict(ordering)) {
// Conflict scenarios won't support that case
continue
}
......@@ -321,94 +430,81 @@ describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', true])(
}
}
)
describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])(
'css-order %s',
(mode: string) => {
const { next, isNextDev } = nextTestSetup(options(mode))
for (const ordering of allPairs) {
const name = `should load correct styles navigating ${ordering.join(
' -> '
)}`
if (
ordering
.map((page) => PAGES[page])
.some((page) =>
mode === 'turbo'
? page.conflictTurbo || page.conflict
: page.conflict
)
) {
// Conflict scenarios won't support that case
continue
}
// TODO fix this case
let broken = ordering.some(
(page) =>
PAGES[page].brokenLoading ||
(isNextDev && PAGES[page].brokenLoadingDev)
)
if (broken) {
it.todo(name)
continue
}
it(name, async () => {
const start = PAGES[ordering[0]]
const browser = await next.browser(start.url)
const check = async (pageInfo) => {
expect(
await browser
.waitForElementByCss(pageInfo.selector)
.getComputedCss('color')
).toBe(pageInfo.color)
}
const navigate = async (page) => {
await browser.waitForElementByCss('#' + page).click()
}
await check(start)
for (const page of ordering.slice(1)) {
await navigate(page)
await check(PAGES[page])
}
await browser.close()
})
describe.each(
process.env.IS_TURBOPACK_TEST ? TURBO_MODES : WEBPACK_MODES_LOOSE
)('css-order %s', (_label: string, value: CssChunkingValue) => {
const { next, isNextDev } = nextTestSetup(options(value))
for (const ordering of allPairs) {
const name = `should load correct styles navigating ${ordering.join(
' -> '
)}`
if (shouldSkipConflict(ordering)) {
// Conflict scenarios won't support that case
continue
}
}
)
describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])(
'css-order %s',
(mode: string) => {
const { next, isNextDev } = nextTestSetup(options(mode))
for (const [page, pageInfo] of Object.entries(PAGES)) {
const name = `should load correct styles on ${page}`
if (
(mode !== 'strict' && pageInfo.conflict) ||
(mode === 'turbo' && pageInfo.conflictTurbo)
) {
// Conflict scenarios won't support that case
continue
}
it(name, async () => {
const browser = await next.browser(pageInfo.url)
// TODO fix this case
let broken = ordering.some(
(page) =>
PAGES[page].brokenLoading || (isNextDev && PAGES[page].brokenLoadingDev)
)
if (broken) {
it.todo(name)
continue
}
it(name, async () => {
const start = PAGES[ordering[0]]
const browser = await next.browser(start.url)
const check = async (pageInfo) => {
expect(
await browser
.waitForElementByCss(pageInfo.selector)
.getComputedCss('color')
).toBe(pageInfo.color)
if (!isNextDev) {
const stylesheets = await browser.elementsByCss(
"link[rel='stylesheet']"
)
const files = await Promise.all(
Array.from(stylesheets).map((e) => e.getAttribute('href'))
)
expect(files).toHaveLength(
mode === 'turbo' || mode === 'loose'
? pageInfo.requestsLoose || pageInfo.requests
: pageInfo.requests
)
}
await browser.close()
})
}
const navigate = async (page) => {
await browser.waitForElementByCss('#' + page).click()
}
await check(start)
for (const page of ordering.slice(1)) {
await navigate(page)
await check(PAGES[page])
}
await browser.close()
})
}
})
describe.each(
process.env.IS_TURBOPACK_TEST ? TURBO_MODES : WEBPACK_MODES_LOOSE
)('css-order %s', (_label: string, value: CssChunkingValue) => {
const { next, isNextDev } = nextTestSetup(options(value))
for (const [page, pageInfo] of Object.entries(PAGES)) {
const name = `should load correct styles on ${page}`
if (
// `strict` preserves ordering for conflict scenarios; loose/turbo/graph do not.
// `conflictTurbo` applies to any Turbopack mode.
(!isStrictMode(value) && pageInfo.conflict) ||
(process.env.IS_TURBOPACK_TEST && pageInfo.conflictTurbo)
) {
// Conflict scenarios won't support that case
continue
}
it(name, async () => {
const browser = await next.browser(pageInfo.url)
expect(
await browser
.waitForElementByCss(pageInfo.selector)
.getComputedCss('color')
).toBe(pageInfo.color)
if (!isNextDev) {
const stylesheets = await browser.elementsByCss(
"link[rel='stylesheet']"
)
const files = await Promise.all(
Array.from(stylesheets).map((e) => e.getAttribute('href'))
)
expect(files).toHaveLength(expectedRequests(value, pageInfo))
}
await browser.close()
})
}
)
})
......@@ -9,7 +9,10 @@ use crate::{
ChunkItemBatchGroup, ChunkItemWithAsyncModuleInfo, ChunkingConfig, ChunkingContext,
chunking::{ChunkItemOrBatchWithInfo, SplitContext, make_chunk},
},
module_graph::{ModuleGraph, style_groups::StyleGroupsConfig},
module_graph::{
ModuleGraph,
style_groups::{StyleGroups, StyleGroupsConfig, StyleItemInfo},
},
};
pub async fn make_style_production_chunks(
......@@ -30,12 +33,22 @@ pub async fn make_style_production_chunks(
*chunking_context,
StyleGroupsConfig {
max_chunk_size: chunking_config.max_merge_chunk_size,
algorithm: chunking_config.style_groups_algorithm.clone(),
},
)
.await?;
// Flatten the input to a sequence of (chunk item, info) pairs (preserving input order
// as the tie-breaker for items without an explicit `order`), then stably sort by
// `StyleItemInfo::order`. Each item's `StyleItemInfo` is fetched once here so the loop
// below doesn't have to re-query the map.
let flat_items = flatten_and_sort(chunk_items, &style_groups).await?;
let mut handled = FxHashSet::default();
let mut handle_chunk_item = async |chunk_item: &ChunkItemWithAsyncModuleInfo| {
if let Some(&batch) = style_groups.shared_chunk_items.get(chunk_item) {
for (chunk_item, info) in &flat_items {
if let Some(info) = info
&& let Some(batch) = info.batch
{
if handled.insert(batch) {
make_chunk(
vec![&ChunkItemOrBatchWithInfo::Batch { batch, size: 0 }],
......@@ -45,32 +58,19 @@ pub async fn make_style_production_chunks(
)
.await?;
}
} else {
make_chunk(
vec![&ChunkItemOrBatchWithInfo::ChunkItem {
chunk_item: *chunk_item,
size: 0,
asset_ident: rcstr!(""),
}],
vec![],
&mut String::new(),
&mut split_context,
)
.await?;
continue;
}
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?;
}
}
};
make_chunk(
vec![&ChunkItemOrBatchWithInfo::ChunkItem {
chunk_item: *chunk_item,
size: 0,
asset_ident: rcstr!(""),
}],
vec![],
&mut String::new(),
&mut split_context,
)
.await?;
}
Ok(())
......@@ -78,3 +78,37 @@ pub async fn make_style_production_chunks(
.instrument(span_outer)
.await
}
/// Flatten input batches into a single ordered list of `(chunk_item, info)` pairs and stably
/// sort by `StyleItemInfo::order`. In practice each [`StyleGroups`] result is uniform:
/// * the loose algorithm produces all `None` orders, so the sort is a no-op and items keep their
/// input position;
/// * the graph algorithm produces all `Some(_)` orders (including for singleton chunks; see
/// [`crate::module_graph::style_groups_graph::compute_style_groups_graph`]), so the sort key
/// fully determines the final order and any missing-from-map sentinel can't slip in.
///
/// Returns the `StyleItemInfo` reference for each item so the caller can avoid re-querying
/// `style_groups.shared_chunk_items`.
async fn flatten_and_sort<'a>(
chunk_items: Vec<&ChunkItemOrBatchWithInfo>,
style_groups: &'a StyleGroups,
) -> Result<Vec<(ChunkItemWithAsyncModuleInfo, Option<&'a StyleItemInfo>)>> {
let mut flat_items: Vec<(ChunkItemWithAsyncModuleInfo, Option<&'a StyleItemInfo>)> =
Vec::with_capacity(chunk_items.len());
for chunk_item in chunk_items {
match chunk_item {
ChunkItemOrBatchWithInfo::ChunkItem { chunk_item, .. } => {
let info = style_groups.shared_chunk_items.get(chunk_item);
flat_items.push((*chunk_item, info));
}
ChunkItemOrBatchWithInfo::Batch { batch, .. } => {
for chunk_item in &batch.await?.chunk_items {
let info = style_groups.shared_chunk_items.get(chunk_item);
flat_items.push((*chunk_item, info));
}
}
}
}
flat_items.sort_by_key(|(_, info)| info.and_then(|i| i.order));
Ok(flat_items)
}
......@@ -20,7 +20,7 @@ use crate::{
module::Module,
module_graph::{
ModuleGraph, binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroup,
module_batches::BatchingConfig,
module_batches::BatchingConfig, style_groups::StyleGroupsAlgorithm,
},
output::{
ExpandOutputAssetsInput, OutputAsset, OutputAssets, OutputAssetsReferences,
......@@ -274,6 +274,11 @@ pub struct ChunkingConfig {
/// This makes sure that code in big chunks is not duplicated in multiple chunks.
pub max_merge_chunk_size: usize,
/// Selects the algorithm used to compute
/// [`crate::module_graph::style_groups::StyleGroups`]. Only consulted for the CSS chunk
/// type.
pub style_groups_algorithm: StyleGroupsAlgorithm,
#[allow(dead_code)]
pub placeholder_for_future_extensions: (),
}
......
......@@ -35,7 +35,9 @@ use crate::{
chunk_group_info::{ChunkGroupEntry, ChunkGroupInfo, compute_chunk_group_info},
merged_modules::{MergedModuleInfo, compute_merged_modules},
module_batches::{ModuleBatchesGraph, compute_module_batches},
style_groups::{StyleGroups, StyleGroupsConfig, compute_style_groups},
style_groups::{StyleGroups, StyleGroupsAlgorithm, StyleGroupsConfig},
style_groups_graph::compute_style_groups_graph,
style_groups_loose::compute_style_groups,
traced_di_graph::TracedDiGraph,
},
reference::{ModuleReference, primary_chunkable_referenced_modules},
......@@ -49,7 +51,9 @@ pub mod merged_modules;
pub mod module_batch;
pub(crate) mod module_batches;
mod side_effect_module_info;
pub(crate) mod style_groups;
pub mod style_groups;
pub mod style_groups_graph;
pub mod style_groups_loose;
mod traced_di_graph;
pub use self::module_batches::BatchingConfig;
......@@ -760,7 +764,24 @@ impl ModuleGraph {
chunking_context: Vc<Box<dyn ChunkingContext>>,
config: StyleGroupsConfig,
) -> Result<Vc<StyleGroups>> {
compute_style_groups(self, chunking_context, &config).await
match &config.algorithm {
StyleGroupsAlgorithm::Default => {
compute_style_groups(self, chunking_context, &config).await
}
StyleGroupsAlgorithm::Graph {
module_factor_cost,
request_cost,
} => {
compute_style_groups_graph(
self,
chunking_context,
request_cost.get(),
module_factor_cost.get(),
config.max_chunk_size as u64,
)
.await
}
}
}
#[turbo_tasks::function(root)]
......
use std::cmp::Reverse;
//! Algorithm-neutral output types for the style-chunking pipeline.
//!
//! [`StyleGroups`] is the cell type both algorithms — the default ("loose") one in
//! [`super::style_groups_loose`] and the graph-based one in [`super::style_groups_graph`] —
//! produce. Living here means neither algorithm has to import from the other.
use anyhow::Result;
use bincode::{Decode, Encode};
use indexmap::map::Entry;
use rustc_hash::{FxHashMap, FxHashSet};
use turbo_rcstr::RcStr;
use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, ValueToString,
Vc, trace::TraceRawVcs,
FxIndexMap, NonLocalValue, OperationValue, ResolvedVc, TaskInput, Vc, trace::TraceRawVcs,
};
use crate::{
chunk::{
ChunkItemBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
ChunkableModule, ChunkingContext, chunk_item_batch::attach_async_info_to_chunkable_module,
},
module::{Module, StyleModule, StyleType},
module_graph::{
GraphTraversalAction, ModuleGraph, module_batch::ModuleOrBatch,
module_batches::ModuleBatchesGraphEdge,
},
};
use crate::chunk::{ChunkItemBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo};
/// Wrapper around an `f32` that implements [`TaskInput`] (and the other derives the
/// [`StyleGroupsAlgorithm`] enum needs) by going through the IEEE-754 bit pattern. Use
/// [`F32TaskInput::get`] / [`F32TaskInput::from`] at the boundary; do not match on the inner
/// `u32` directly.
#[derive(
TaskInput, Debug, Clone, PartialEq, Eq, Hash, NonLocalValue, TraceRawVcs, Encode, Decode,
TaskInput,
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
NonLocalValue,
OperationValue,
TraceRawVcs,
Encode,
Decode,
)]
pub struct StyleGroupsConfig {
pub max_chunk_size: usize,
}
pub struct F32TaskInput(u32);
/// Styling must not be duplicated in the application. The simplest way to achieve this is to put
/// every styling chunk item into a separate chunk. That works, but isn't efficient since it would
/// cause a lot of requests. Instead we multiple chunk items are groups together and placed in a
/// single shared chunk. `StyleGroups` specifies how chunk items are grouped together.
#[turbo_tasks::value]
pub struct StyleGroups {
/// The key chunk item is contained in the value chunk item batch. All chunk items that are not
/// contained in this map are placed in a separate chunk per chunk item.
#[bincode(with = "turbo_bincode::indexmap")]
pub shared_chunk_items:
FxIndexMap<ChunkItemWithAsyncModuleInfo, ResolvedVc<ChunkItemBatchWithAsyncModuleInfo>>,
impl F32TaskInput {
pub const fn from(value: f32) -> Self {
Self(value.to_bits())
}
pub const fn get(self) -> f32 {
f32::from_bits(self.0)
}
}
#[derive(Debug)]
struct ModuleInfo {
style_type: StyleType,
ident: RcStr,
chunk_group_indices: FxHashMap<usize, usize>,
index_sum: usize,
size: usize,
chunk_item: Option<ChunkItemWithAsyncModuleInfo>,
/// Selects the algorithm used to compute [`StyleGroups`].
#[turbo_tasks::value(shared, operation)]
#[derive(Clone, Debug, Default, Hash, TaskInput)]
pub enum StyleGroupsAlgorithm {
/// Default ("loose") algorithm, see
/// [`crate::module_graph::style_groups_loose::compute_style_groups`].
#[default]
Default,
/// Graph-analysis based algorithm, see
/// [`crate::module_graph::style_groups_graph::compute_style_groups_graph`].
Graph {
/// See `experimental.cssChunking.requestCost` in Next.js.
request_cost: F32TaskInput,
/// See `experimental.cssChunking.moduleFactorCost` in Next.js.
module_factor_cost: F32TaskInput,
},
}
impl ModuleInfo {
fn new(style_type: StyleType, ident: RcStr) -> Self {
Self {
style_type,
ident,
chunk_group_indices: Default::default(),
index_sum: 0,
size: 0,
chunk_item: None,
impl StyleGroupsAlgorithm {
/// Build a [`StyleGroupsAlgorithm::Graph`] variant from real `f32` cost parameters.
pub fn graph(request_cost: f32, module_factor_cost: f32) -> Self {
Self::Graph {
request_cost: F32TaskInput::from(request_cost),
module_factor_cost: F32TaskInput::from(module_factor_cost),
}
}
}
struct ChunkGroupState {
styles: FxIndexSet<ResolvedVc<Box<dyn ChunkableModule>>>,
requests: usize,
#[derive(
TaskInput, Debug, Clone, PartialEq, Eq, Hash, NonLocalValue, TraceRawVcs, Encode, Decode,
)]
pub struct StyleGroupsConfig {
pub max_chunk_size: usize,
pub algorithm: StyleGroupsAlgorithm,
}
pub async fn compute_style_groups(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
config: &StyleGroupsConfig,
) -> Result<Vc<StyleGroups>> {
let chunk_group_info = module_graph.chunk_group_info().await?;
let batches_graph = module_graph
.module_batches(chunking_context.batching_config())
.await?;
let async_module_info = module_graph.async_module_info();
let mut module_info_map: FxIndexMap<ResolvedVc<Box<dyn ChunkableModule>>, Option<ModuleInfo>> =
FxIndexMap::default();
// Compute the style modules in each chunk group
let mut chunk_group_state = Vec::new();
let mut idx = 0;
for (i, chunk_group) in chunk_group_info.chunk_groups.iter().enumerate() {
let ordered_entries = batches_graph.get_ordered_entries(&chunk_group_info, i);
let mut entries = Vec::with_capacity(chunk_group.entries_count());
for entry in ordered_entries {
entries.push(batches_graph.get_entry_index(entry).await?);
}
let mut visited = FxHashSet::default();
let mut items_in_postorder = FxIndexSet::default();
batches_graph.traverse_edges_from_entries_dfs(
entries.iter().copied(),
&mut (),
|parent_info, module, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
&& !ty.is_parallel()
{
return Ok(GraphTraversalAction::Exclude);
}
if visited.insert(module) {
Ok(GraphTraversalAction::Continue)
} else {
Ok(GraphTraversalAction::Exclude)
}
},
|parent_info, item, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
&& !ty.is_parallel()
{
return;
}
items_in_postorder.insert(*item);
},
)?;
let mut styles = FxIndexSet::default();
let mut handle_module = async |module| {
match module_info_map.entry(module) {
Entry::Occupied(mut e) => {
if let Some(info) = e.get_mut() {
info.chunk_group_indices.insert(idx, styles.len());
info.index_sum += styles.len();
styles.insert(module);
}
}
Entry::Vacant(e) => {
if let Some(style_module) =
ResolvedVc::try_sidecast::<Box<dyn StyleModule>>(module)
{
let style_type = *style_module.style_type().await?;
let mut info =
ModuleInfo::new(style_type, module.ident().to_string().owned().await?);
info.chunk_group_indices.insert(idx, styles.len());
info.index_sum += styles.len();
styles.insert(module);
e.insert(Some(info));
} else {
e.insert(None);
}
}
}
anyhow::Ok(())
};
for item in items_in_postorder {
match item {
ModuleOrBatch::Batch(batch) => {
for &module in &batch.await?.modules {
handle_module(module).await?;
}
}
ModuleOrBatch::Module(module) => {
if let Some(chunkable_module) = ResolvedVc::try_downcast(module) {
handle_module(chunkable_module).await?;
}
}
ModuleOrBatch::None(_) => {}
}
}
if !styles.is_empty() {
chunk_group_state.push(ChunkGroupState {
requests: styles.len(),
styles,
});
idx += 1;
}
}
module_info_map.retain(|_, info| info.is_some());
module_info_map.sort_by(|_, a, _, b| {
let a = a.as_ref().unwrap();
let b = b.as_ref().unwrap();
a.index_sum
.cmp(&b.index_sum)
.then_with(|| a.ident.cmp(&b.ident))
});
// Compute the dependents of each module
let mut module_dependents: FxHashMap<_, Vec<_>> = FxHashMap::default();
for (&module, info) in &module_info_map {
let info = info.as_ref().unwrap();
// Find the shortest chunk group as it's most efficient to iterate
let (&idx, &start_pos) = info
.chunk_group_indices
.iter()
.min_by_key(|&(&idx, _)| chunk_group_state[idx].styles.len())
.unwrap();
let potential_dependents = &chunk_group_state[idx].styles[start_pos + 1..];
let dependents = potential_dependents
.iter()
.copied()
.filter(|dependent| {
let dependent_info = module_info_map.get(dependent).unwrap();
let dependent_info = dependent_info.as_ref().unwrap();
// module is a dependency of dependent when it's included in all chunk groups of
// dependent with an index lower than the index of the dependent
info.chunk_group_indices.len() >= dependent_info.chunk_group_indices.len()
&& dependent_info
.chunk_group_indices
.iter()
.all(|(idx, &dependent_pos)| {
info.chunk_group_indices
.get(idx)
.is_some_and(|&module_pos| module_pos < dependent_pos)
})
})
.collect::<Vec<_>>();
if !dependents.is_empty() {
module_dependents.insert(module, dependents);
}
}
// Compute the chunk item and size of each module
let chunk_item_and_sizes = module_info_map
.keys()
.map(async |&module| {
let chunk_item = attach_async_info_to_chunkable_module(
module,
async_module_info,
module_graph,
chunking_context,
)
.await?;
let size = *chunk_item
.chunk_type
.chunk_item_size(chunking_context, *chunk_item.chunk_item, None)
.await?;
Ok((chunk_item, size))
})
.try_join()
.await?;
module_info_map
.iter_mut()
.zip(chunk_item_and_sizes)
.for_each(|((_, info), (chunk_item, size))| {
let info = info.as_mut().unwrap();
info.size = size;
info.chunk_item = Some(chunk_item);
});
let mut ordered_modules_with_state = module_info_map
.keys()
.copied()
.map(|m| (m, false))
.collect::<FxIndexMap<_, _>>();
let mut shared_chunk_items = FxIndexMap::default();
for i in 0..ordered_modules_with_state.len() {
let (&module, processed) = ordered_modules_with_state.get_index_mut(i).unwrap();
if *processed {
continue;
}
*processed = true;
let info = module_info_map.get(&module).unwrap().as_ref().unwrap();
let mut global_mode = info.style_type == StyleType::GlobalStyle;
// The current position of processing in all selected chunk groups
let mut all_chunk_states = info.chunk_group_indices.clone();
// The list of modules and chunk items that go into the new chunk
let mut new_chunk_modules = [module].into_iter().collect::<FxHashSet<_>>();
let mut new_chunk_items = vec![info.chunk_item.unwrap()];
// The current size of the new chunk
let mut current_size = info.size;
// A pool of potential modules where the next module is selected from.
// It's filled from the next module of the selected modules in every chunk group.
let mut potential_next_modules = all_chunk_states
.iter()
.filter_map(|(&idx, pos)| {
let following_styles = &chunk_group_state[idx].styles[pos + 1..];
let i = following_styles
.iter()
.position(|m| !*ordered_modules_with_state.get(m).unwrap());
i.map(|i| following_styles[i])
})
.collect::<FxHashSet<_>>();
// Try to add modules to the chunk until a break condition is met
'outer: loop {
// We try to select a module that reduces request count and
// has the highest number of requests
let mut ordered_potential_next_modules = potential_next_modules
.iter()
.copied()
.map(|module| {
let info = module_info_map.get(&module).unwrap().as_ref().unwrap();
let requests = info
.chunk_group_indices
.keys()
.filter(|idx| all_chunk_states.contains_key(idx))
.map(|&idx| chunk_group_state[idx].requests)
.max()
.unwrap();
(module, info, requests)
})
.collect::<Vec<_>>();
ordered_potential_next_modules
.sort_by_key(|(_, info, requests)| (Reverse(*requests), &info.ident));
// Try every potential module
for (module, info, _) in ordered_potential_next_modules {
if current_size + info.size > config.max_chunk_size {
// Chunk would be too large
continue;
}
// In loose mode we only check if the dependencies are not violated
if let Some(dependents) = module_dependents.get(&module)
&& dependents.iter().any(|m| new_chunk_modules.contains(m))
{
// A dependent of the module is already in the chunk, which would violate
// the order
continue;
}
// Global CSS must not leak into unrelated chunks
let is_global = info.style_type == StyleType::GlobalStyle;
if is_global
&& global_mode
&& all_chunk_states.len() != info.chunk_group_indices.len()
{
// Fast check: chunk groups need to be identical
continue;
}
if global_mode
&& info
.chunk_group_indices
.keys()
.any(|idx| !all_chunk_states.contains_key(idx))
{
// Global CSS in new_chunk_items would leak into new chunk_group
continue;
}
if is_global
&& all_chunk_states
.keys()
.any(|idx| !info.chunk_group_indices.contains_key(idx))
{
// Global CSS would leak into existing chunk_group
continue;
}
potential_next_modules.remove(&module);
current_size += info.size;
if is_global {
global_mode = true;
}
for &idx in info.chunk_group_indices.keys() {
if all_chunk_states.contains_key(&idx) {
// This reduces the request count of the chunk group
chunk_group_state[idx].requests -= 1;
}
let pos = chunk_group_state[idx].styles.get_index_of(&module).unwrap();
all_chunk_states.insert(idx, pos);
let following_styles = &chunk_group_state[idx].styles[pos + 1..];
if let Some(i) = following_styles.iter().position(|m| {
!*ordered_modules_with_state.get(m).unwrap()
&& !new_chunk_modules.contains(m)
}) {
let module = following_styles[i];
potential_next_modules.insert(module);
}
}
new_chunk_items.push(info.chunk_item.unwrap());
new_chunk_modules.insert(module);
*ordered_modules_with_state.get_mut(&module).unwrap() = true;
continue 'outer;
}
break;
}
/// Per-item metadata produced by the style chunking algorithms.
#[derive(
Debug, Clone, PartialEq, Eq, Hash, NonLocalValue, TraceRawVcs, Encode, Decode, TaskInput,
)]
pub struct StyleItemInfo {
/// Stable sort key applied by the production-chunking pass when ordering chunks within a chunk
/// group. The loose algorithm produces all `None` orders and relies on input order; the graph
/// algorithm produces all `Some(_)` orders (including for singletons). Mixing `Some` and
/// `None` within a single [`StyleGroups`] result is not produced in practice — the
/// production-chunking sort treats `None` as a sort key that is less than any `Some(_)`, but
/// this branch is only exercised in the all-`None` (loose) case.
pub order: Option<u32>,
/// `Some(batch)` when this chunk item shares its emitted chunk with other items. `None` for
/// items that end up alone in their own chunk under the graph algorithm.
pub batch: Option<ResolvedVc<ChunkItemBatchWithAsyncModuleInfo>>,
}
if new_chunk_items.len() > 1 {
let style_group = ChunkItemBatchWithAsyncModuleInfo::new(new_chunk_items.clone())
.to_resolved()
.await?;
for chunk_item in new_chunk_items {
shared_chunk_items.insert(chunk_item, style_group);
}
}
}
/// Styling must not be duplicated in the application. The simplest way to achieve this is to put
/// every styling chunk item into a separate chunk. That works, but isn't efficient since it would
/// cause a lot of requests. Instead, multiple chunk items are grouped together and placed in a
/// single shared chunk. `StyleGroups` specifies how chunk items are grouped together.
#[turbo_tasks::value(shared)]
pub struct StyleGroups {
/// Per-item info keyed by chunk item.
///
/// The loose algorithm only inserts items it actively grouped into shared chunks (everything
/// else is implicitly emitted as a singleton chunk preserving input order). The graph
/// algorithm inserts every input item — including singletons — so its result fully determines
/// the final per-chunk-group ordering through `StyleItemInfo::order`.
#[bincode(with = "turbo_bincode::indexmap")]
pub shared_chunk_items: FxIndexMap<ChunkItemWithAsyncModuleInfo, StyleItemInfo>,
}
Ok(StyleGroups { shared_chunk_items }.cell())
/// Constructor for [`StyleGroups`] that's accessible from both algorithm modules without
/// forcing the cell visibility wider.
pub(super) fn make_style_groups(
shared_chunk_items: FxIndexMap<ChunkItemWithAsyncModuleInfo, StyleItemInfo>,
) -> Vc<StyleGroups> {
StyleGroups { shared_chunk_items }.cell()
}
//! Pure (no-Vc) graph algorithms underlying the graph-based CSS chunker.
//!
//! Direct port of the proof-of-concept TypeScript implementation. See the parent module's
//! documentation for the high-level pipeline.
use std::{
cmp::Reverse,
collections::{BinaryHeap, VecDeque},
};
use petgraph::graph::{DiGraph, EdgeIndex, NodeIndex};
use rustc_hash::{FxHashMap, FxHashSet};
use super::subgraph_view::{ReadonlyGraph, SubgraphView};
use crate::module::StyleType;
// ---------------------------------------------------------------------------
// create_graph
// ---------------------------------------------------------------------------
/// Build a directed weighted graph from `chunk_groups`.
///
/// For each group `[m₀, m₁, ..., mₖ]` and every pair `(later, earlier)` with `later > earlier`
/// inside the group, an edge `later → earlier` is added (weight 1). Repeated edges accumulate.
/// `node_count` is the total number of distinct module ids referenced; node ids are dense in
/// `0..node_count`.
pub(super) fn create_graph(chunk_groups: &[Vec<usize>], node_count: usize) -> DiGraph<usize, u32> {
let mut graph: DiGraph<usize, u32> = DiGraph::with_capacity(node_count, 0);
for i in 0..node_count {
let idx = graph.add_node(i);
debug_assert_eq!(idx.index(), i);
}
let mut edge_index: FxHashMap<(NodeIndex, NodeIndex), EdgeIndex> = FxHashMap::default();
for group in chunk_groups {
for (i, &later_id) in group.iter().enumerate() {
let later = NodeIndex::new(later_id);
for &earlier_id in &group[..i] {
let earlier = NodeIndex::new(earlier_id);
match edge_index.get(&(later, earlier)) {
Some(&e) => {
let w = graph.edge_weight_mut(e).unwrap();
*w += 1;
}
None => {
let e = graph.add_edge(later, earlier, 1);
edge_index.insert((later, earlier), e);
}
}
}
}
}
graph
}
// ---------------------------------------------------------------------------
// strongly connected components (Tarjan, iterative)
// ---------------------------------------------------------------------------
/// Iterative Tarjan SCC. Returns one [`FxHashSet`] per component, in reverse topological order
/// of the condensation DAG (sinks first).
pub(super) fn strongly_connected_components<'a, G>(graph: G) -> Vec<FxHashSet<NodeIndex>>
where
G: ReadonlyGraph<'a>,
{
let bound = graph.index_bound();
// `u32::MAX` as the "unvisited" sentinel. Tarjan only assigns strictly increasing indices
// up to `bound`, well within `u32::MAX` for any realistic graph.
let mut indices: Vec<u32> = vec![u32::MAX; bound];
let mut lowlinks: Vec<u32> = vec![u32::MAX; bound];
let mut on_stack: Vec<bool> = vec![false; bound];
let mut scc_stack: Vec<NodeIndex> = Vec::new();
let mut result: Vec<FxHashSet<NodeIndex>> = Vec::new();
let mut next_index: u32 = 0;
struct Frame<I> {
node: NodeIndex,
iter: I,
}
let mut call_stack: Vec<Frame<G::OutgoingIter>> = Vec::new();
for root in graph.nodes() {
let root_i = root.index();
if indices[root_i] != u32::MAX {
continue;
}
indices[root_i] = next_index;
lowlinks[root_i] = next_index;
next_index += 1;
scc_stack.push(root);
on_stack[root_i] = true;
call_stack.push(Frame {
node: root,
iter: graph.outgoing_edges(root),
});
while let Some(frame) = call_stack.last_mut() {
let v = frame.node;
match frame.iter.next() {
None => {
let v_i = v.index();
let v_index = indices[v_i];
let v_low = lowlinks[v_i];
if v_low == v_index {
let mut component: FxHashSet<NodeIndex> = FxHashSet::default();
loop {
let top = scc_stack.pop().unwrap();
on_stack[top.index()] = false;
component.insert(top);
if top == v {
break;
}
}
result.push(component);
}
call_stack.pop();
if let Some(parent_frame) = call_stack.last() {
let parent_i = parent_frame.node.index();
if v_low < lowlinks[parent_i] {
lowlinks[parent_i] = v_low;
}
}
}
Some(w) => {
let w_i = w.index();
if indices[w_i] == u32::MAX {
indices[w_i] = next_index;
lowlinks[w_i] = next_index;
next_index += 1;
scc_stack.push(w);
on_stack[w_i] = true;
call_stack.push(Frame {
node: w,
iter: graph.outgoing_edges(w),
});
} else if on_stack[w_i] {
let w_index = indices[w_i];
let v_i = v.index();
if w_index < lowlinks[v_i] {
lowlinks[v_i] = w_index;
}
}
}
}
}
}
result
}
// ---------------------------------------------------------------------------
// find_short_cycle (bidirectional Dijkstra)
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction2 {
Forward,
Backward,
Cycle,
}
#[derive(Debug, Clone)]
struct Candidate {
direction: Direction2,
/// Predecessor on the forward half of the search tree. `Some` for nodes reached by the
/// forward frontier (`Forward` or `Cycle` direction); `None` for the start node and for
/// nodes reached only by the backward frontier.
forward_predecessor: Option<NodeIndex>,
/// Predecessor on the backward half of the search tree. Mirror of `forward_predecessor`.
backward_predecessor: Option<NodeIndex>,
/// `u64::MAX` is used as the sentinel for "visited / +infinity" — matches the JS `Infinity`.
distance: u64,
}
/// Find a short cycle inside `graph`. Returns `None` if `graph` is empty or has no cycle
/// reachable from `start_node` (or, when `start_node` is `None`, from the first node yielded
/// by `graph.nodes()`). The cycle is returned as an array of distinct node ids; every
/// consecutive pair has an edge and the last node has an edge back to the first (the closing
/// wrap is implicit, not repeated).
///
/// The result is "a short" cycle, not necessarily the global shortest: only starts that
/// already appear on the current best cycle are tried.
pub(super) fn find_short_cycle<'a, G>(
graph: G,
start_node: Option<NodeIndex>,
) -> Option<Vec<NodeIndex>>
where
G: ReadonlyGraph<'a>,
{
let start = match start_node {
Some(n) => n,
None => graph.nodes().next()?,
};
let initial = find_shortest_cycle_from_node(graph, start)?;
let mut cycle: VecDeque<NodeIndex> = initial.into();
// 2-cycles are already minimal — no shift can produce a shorter one. Skip the (otherwise
// up-to-k-call) shift loop in this common case.
let mut remaining_shifts = if cycle.len() <= 2 { 0 } else { cycle.len() };
while remaining_shifts > 0 {
let Some(shifted) = cycle.pop_front() else {
break;
};
cycle.push_back(shifted);
// Every node on a cycle is itself on a cycle (within the same graph snapshot), so this
// call is expected to find one.
let new_cycle = find_shortest_cycle_from_node(graph, shifted)
.expect("every node on a cycle must itself be on a cycle");
if new_cycle.len() < cycle.len() {
remaining_shifts = new_cycle.len();
cycle = new_cycle.into();
} else {
remaining_shifts -= 1;
}
}
Some(cycle.into())
}
/// Returns `None` if no cycle is reachable from `start`.
fn find_shortest_cycle_from_node<'a, G>(graph: G, start: NodeIndex) -> Option<Vec<NodeIndex>>
where
G: ReadonlyGraph<'a>,
{
let mut candidates: FxHashMap<NodeIndex, Candidate> = FxHashMap::default();
// Min-heap keyed by `(distance, seq)`. `seq` is a strictly-increasing counter so ties break
// by insertion order (earlier insertions win). Entries are never removed on relaxation;
// stale entries are filtered when popped by comparing to `candidates[node].distance`.
let mut heap: BinaryHeap<Reverse<(u64, u32, NodeIndex)>> = BinaryHeap::new();
let mut next_seq: u32 = 0;
// Seed: a backward "stub" at the start node, plus a forward step over each outgoing edge.
candidates.insert(
start,
Candidate {
direction: Direction2::Backward,
forward_predecessor: None,
backward_predecessor: None,
distance: 0,
},
);
heap.push(Reverse((0, next_seq, start)));
next_seq += 1;
for (edge, weight) in graph.outgoing_edges_with_weight(start) {
let distance = weight as u64;
candidates.insert(
edge,
Candidate {
direction: Direction2::Forward,
forward_predecessor: Some(start),
backward_predecessor: None,
distance,
},
);
heap.push(Reverse((distance, next_seq, edge)));
next_seq += 1;
}
loop {
// Pop the lowest-distance live entry, skipping stale ones.
let (node, current_distance) = loop {
let Reverse((dist, _, node)) = heap.pop()?;
match candidates.get(&node) {
Some(cand) if cand.distance == dist => break (node, dist),
_ => continue,
}
};
let direction = candidates[&node].direction;
// A node with `direction == Cycle` is one where the forward and backward frontiers
// collided. Splice the two halves back into a cycle and return.
if direction == Direction2::Cycle {
let cand = candidates.remove(&node).unwrap();
let mut result = reconstruct_path(&candidates, cand.forward_predecessor, true);
result.push(node);
// `backward_path` always begins with the cycle's start node; drop that head before
// reversing.
let backward = reconstruct_path(&candidates, cand.backward_predecessor, false);
result.extend(backward.into_iter().skip(1).rev());
return Some(result);
}
// Mark `node` as visited (sentinel `u64::MAX` distance).
candidates.get_mut(&node).unwrap().distance = u64::MAX;
// Snapshot neighbours before mutating `candidates` (avoids overlapping borrows).
let neighbours: Vec<(NodeIndex, u32)> = match direction {
Direction2::Forward => graph.outgoing_edges_with_weight(node).collect(),
Direction2::Backward => graph.incoming_edges_with_weight(node).collect(),
Direction2::Cycle => unreachable!(),
};
for (edge, weight) in neighbours {
let new_distance = current_distance + weight as u64;
match candidates.get_mut(&edge) {
None => {
// Unseen neighbour — extend the unidirectional frontier.
let (fwd, bwd) = match direction {
Direction2::Forward => (Some(node), None),
Direction2::Backward => (None, Some(node)),
Direction2::Cycle => unreachable!(),
};
candidates.insert(
edge,
Candidate {
direction,
forward_predecessor: fwd,
backward_predecessor: bwd,
distance: new_distance,
},
);
heap.push(Reverse((new_distance, next_seq, edge)));
next_seq += 1;
}
Some(existing) if existing.distance == u64::MAX => {
// Already visited — leave it.
}
Some(existing) if existing.direction == direction => {
// Same-direction relaxation.
if new_distance < existing.distance {
if direction == Direction2::Forward {
existing.forward_predecessor = Some(node);
} else {
existing.backward_predecessor = Some(node);
}
existing.distance = new_distance;
heap.push(Reverse((new_distance, next_seq, edge)));
next_seq += 1;
}
}
Some(existing) if existing.direction == Direction2::Cycle => {
// Already a cycle candidate — relax the half coming from `direction`.
if new_distance < existing.distance {
if direction == Direction2::Forward {
existing.forward_predecessor = Some(node);
} else {
existing.backward_predecessor = Some(node);
}
existing.distance = new_distance;
heap.push(Reverse((new_distance, next_seq, edge)));
next_seq += 1;
}
}
Some(existing) => {
// Opposite unidirectional frontiers met → upgrade to a cycle candidate.
// The opposite-direction predecessor was already populated when `existing`
// joined the frontier; we just fill in our side.
existing.direction = Direction2::Cycle;
if direction == Direction2::Forward {
existing.forward_predecessor = Some(node);
} else {
existing.backward_predecessor = Some(node);
}
// Distance is unchanged; the existing heap entry at the old distance is
// still valid and will pop the upgraded `Cycle` candidate.
}
}
}
}
}
/// Walk back through predecessors to reconstruct the path from `start` to (but not including)
/// the cycle node. `forward = true` follows forward predecessors; `false` follows backward.
/// Returns the path in order `[start, ..., last_predecessor]`.
fn reconstruct_path(
candidates: &FxHashMap<NodeIndex, Candidate>,
from: Option<NodeIndex>,
forward: bool,
) -> Vec<NodeIndex> {
let mut path: Vec<NodeIndex> = Vec::new();
let mut cur = from;
while let Some(n) = cur {
path.push(n);
let c = &candidates[&n];
cur = if forward {
c.forward_predecessor
} else {
c.backward_predecessor
};
}
path.reverse();
path
}
// ---------------------------------------------------------------------------
// make_acyclic
// ---------------------------------------------------------------------------
/// Mutate `graph` in place to remove all multi-node cycles by repeatedly cutting the
/// lowest-weight edge of a short cycle in each SCC.
pub(super) fn make_acyclic<N>(graph: &mut DiGraph<N, u32>) {
let mut queue: Vec<FxHashSet<NodeIndex>> = Vec::new();
for scc in strongly_connected_components(&*graph) {
if scc.len() > 1 {
queue.push(scc);
}
}
while let Some(scc) = queue.pop() {
// Inner loop: keep cutting edges from cycles inside this SCC, seeding each subsequent
// search at the previous cut's target. The seed is likely still on a cycle until the
// local cycles around it are gone, at which point `find_short_cycle` returns `None` and
// we re-run SCC to discover any remaining components.
let mut seed_node: Option<NodeIndex> = None;
loop {
// Live view restricted to the current SCC.
let view = SubgraphView::new(&*graph, &scc);
let Some(short_cycle) = find_short_cycle(view, seed_node) else {
break;
};
// Walk the cycle's k edges directly (closing wrap implicit) and find the minimum-
// weight one. Considering edges *on the cycle path* — rather than any edge between
// cycle nodes — guarantees the chosen cut breaks this cycle, not an unrelated chord.
let mut min_weight: Option<u32> = None;
let mut min_edge: Option<EdgeIndex> = None;
let mut min_to: Option<NodeIndex> = None;
for i in 0..short_cycle.len() {
let from = short_cycle[i];
let to = short_cycle[(i + 1) % short_cycle.len()];
let Some(edge) = graph.find_edge(from, to) else {
continue;
};
let weight = *graph.edge_weight(edge).unwrap();
if min_weight.is_none_or(|w| weight < w) {
min_weight = Some(weight);
min_edge = Some(edge);
min_to = Some(to);
}
}
let (Some(edge), Some(to)) = (min_edge, min_to) else {
break;
};
graph.remove_edge(edge);
seed_node = Some(to);
}
// Re-check this SCC for residual multi-node SCCs.
let view = SubgraphView::new(&*graph, &scc);
for new_scc in strongly_connected_components(view) {
if new_scc.len() > 1 {
queue.push(new_scc);
}
}
}
}
// ---------------------------------------------------------------------------
// linearize
// ---------------------------------------------------------------------------
/// Topologically sort `graph` (Kahn). Tie-break: when multiple dependents become unblocked at
/// once, the heaviest edge wins; insertion order breaks ties at equal weight.
pub(super) fn linearize<'a, G>(graph: G) -> Vec<NodeIndex>
where
G: ReadonlyGraph<'a>,
{
let mut remaining_deps: FxHashMap<NodeIndex, usize> = FxHashMap::default();
for n in graph.nodes() {
remaining_deps.insert(n, graph.outgoing_edges(n).count());
}
let mut candidates: Vec<NodeIndex> = remaining_deps
.iter()
.filter_map(|(n, &c)| if c == 0 { Some(*n) } else { None })
.collect();
// Stable seed order: matches insertion order of `nodes()`.
{
let order: FxHashMap<NodeIndex, usize> =
graph.nodes().enumerate().map(|(i, n)| (n, i)).collect();
candidates.sort_by_key(|n| std::cmp::Reverse(order[n]));
}
let mut result: Vec<NodeIndex> = Vec::new();
while let Some(placed) = candidates.pop() {
result.push(placed);
// petgraph iterates neighbours in reverse insertion order; flip it back so the
// tie-break below sees them in insertion order — matching the PoC.
let mut incoming: Vec<(NodeIndex, u32)> =
graph.incoming_edges_with_weight(placed).collect();
incoming.reverse();
let mut new_candidates: Vec<(NodeIndex, u32, usize)> = Vec::new();
for (dependent, weight) in incoming {
let Some(cur) = remaining_deps.get(&dependent).copied() else {
continue;
};
let next = cur.saturating_sub(1);
remaining_deps.insert(dependent, next);
if next == 0 {
let idx = new_candidates.len();
new_candidates.push((dependent, weight, idx));
}
}
// Weight ascending; ties broken by reverse insertion order so the earliest-encountered
// dependent ends up on top of the stack and pops first.
new_candidates.sort_by(|a, b| a.1.cmp(&b.1).then(b.2.cmp(&a.2)));
for (dep, _, _) in new_candidates {
candidates.push(dep);
}
}
result
}
// ---------------------------------------------------------------------------
// split_into_chunks
// ---------------------------------------------------------------------------
/// Newtype wrapper that lets `f32` participate in a [`BinaryHeap`]: `f32` itself doesn't
/// implement [`Ord`] because of NaN, so we wrap it and use [`f32::total_cmp`].
#[derive(Copy, Clone, PartialEq)]
struct OrdF32(f32);
impl Eq for OrdF32 {}
impl Ord for OrdF32 {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.total_cmp(&other.0)
}
}
impl PartialOrd for OrdF32 {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
/// Greedy bottom-up chunk merger over the `global_order` produced by [`linearize`].
///
/// Inputs:
/// * `global_order` — module ids in topological order (length M).
/// * `chunk_groups` — each input chunk group remapped to module ids; used to score how often a
/// candidate chunk would be loaded and to size the per-group denominator.
/// * `module_sizes` — per-module byte size, indexed by module id.
/// * `module_style_types` — per-module style type, indexed by module id. Used to forbid merges
/// that would leak global CSS into unrelated chunk groups.
/// * `request_cost` — per-request overhead in bytes.
/// * `module_factor_cost` — see module-level docs.
/// * `max_chunk_size` — bytes; merges that produce a multi-item chunk above this are forbidden
/// (`+infinity`). `0` disables the cap.
pub(super) fn split_into_chunks(
global_order: &[NodeIndex],
chunk_groups: &[Vec<usize>],
module_sizes: &[u64],
module_style_types: &[StyleType],
request_cost: f32,
module_factor_cost: f32,
max_chunk_size: u64,
) -> Vec<Vec<usize>> {
if global_order.is_empty() {
return Vec::new();
}
// Convert the topological order to plain module ids.
let order: Vec<usize> = global_order.iter().map(|n| n.index()).collect();
let n = order.len();
// Per-group total CSS byte size — denominator in the cost formula. Memoized once because
// `chunk_groups` is fixed for the duration of this call. `.max(1)` avoids a div-by-zero
// when a chunk group has only zero-sized modules.
let group_total_size: Vec<u64> = chunk_groups
.iter()
.map(|g| g.iter().map(|&id| module_sizes[id]).sum::<u64>().max(1))
.collect();
// Inverse index: for each module id, the sorted, deduplicated list of chunk-group indices
// that contain it. Built once so `chunk_cost` can collect "loading groups" as the union
// over the chunk's modules — and answer "does group gi contain module id?" via a binary
// search rather than a linear scan of the (potentially large) chunk group.
let mut module_to_groups: Vec<Vec<u32>> = vec![Vec::new(); module_sizes.len()];
for (gi, group) in chunk_groups.iter().enumerate() {
let gi32 = gi as u32;
for &id in group {
module_to_groups[id].push(gi32);
}
}
for list in module_to_groups.iter_mut() {
list.sort_unstable();
list.dedup();
}
let cx = CostContext {
module_to_groups: &module_to_groups,
group_total_size: &group_total_size,
module_sizes,
module_style_types,
request_cost,
module_factor_cost,
max_chunk_size,
};
// Active split point bitmap: `split_points[i] = true` means there's a boundary between
// `order[i]` and `order[i+1]`. Parallel `metrics` cache stores `cost(merged) - cost(left) -
// cost(right)` for the active split at `i` (or `None` if the split has been merged away).
let mut split_points = vec![true; n.saturating_sub(1)];
let mut metrics: Vec<Option<f32>> = vec![None; split_points.len()];
// Min-heap of `(metric, split_index)`. Only negative metrics are pushed — a non-negative
// metric would never improve cost and is never popped. When `metrics[i]` is invalidated
// we recompute and push a fresh entry; old entries become stale and are filtered on pop
// by checking against the current value in `metrics`.
//
// Tie-break on metric equality: smaller `i` pops first (matches the PoC's strict `<`
// selection where the lowest-index winner survives).
let mut heap: BinaryHeap<Reverse<(OrdF32, usize)>> = BinaryHeap::new();
// Seed: compute every initial metric, push the negatives.
for (i, slot) in metrics.iter_mut().enumerate() {
let m = cx.split_metric(&split_points, &order, i);
*slot = Some(m);
if m < 0.0 {
heap.push(Reverse((OrdF32(m), i)));
}
}
while let Some(Reverse((OrdF32(popped_m), i))) = heap.pop() {
// Skip stale entries: either the split has been merged, or its metric was recomputed
// and a newer entry exists elsewhere in the heap.
if !split_points[i] || metrics[i] != Some(popped_m) {
continue;
}
// `popped_m < 0` by construction.
// Merge at `i` and invalidate the metrics of the two adjacent active splits (their
// `affected_range` now extends across the merged region).
split_points[i] = false;
metrics[i] = None;
for neighbour in [
(0..i).rev().find(|&j| split_points[j]),
((i + 1)..split_points.len()).find(|&j| split_points[j]),
]
.into_iter()
.flatten()
{
let new_m = cx.split_metric(&split_points, &order, neighbour);
metrics[neighbour] = Some(new_m);
if new_m < 0.0 {
heap.push(Reverse((OrdF32(new_m), neighbour)));
}
}
}
// Materialize chunks by walking `order` and starting a new chunk on each true split point.
let mut result: Vec<Vec<usize>> = vec![vec![order[0]]];
for i in 1..n {
if split_points[i - 1] {
result.push(vec![order[i]]);
} else {
result.last_mut().unwrap().push(order[i]);
}
}
result
}
/// `(start, end)` order-indices for the merged region straddling the `index`-th split — the
/// run of consecutive `order` positions whose neighbouring split points have been merged
/// (`split_points[i] == false`).
fn affected_range(split_points: &[bool], index: usize) -> (usize, usize) {
let mut start = index;
while start > 0 && !split_points[start - 1] {
start -= 1;
}
let mut end = index + 1;
while end < split_points.len() && !split_points[end] {
end += 1;
}
(start, end)
}
/// Constant inputs to [`CostContext::chunk_cost`]. Bundled together so we don't have to pass
/// seven arguments at every call site.
struct CostContext<'a> {
/// Inverse of `chunk_groups`: per module id, the sorted list of group indices containing
/// that module. Built once in [`split_into_chunks`] and reused for every `chunk_cost`
/// invocation.
module_to_groups: &'a [Vec<u32>],
group_total_size: &'a [u64],
module_sizes: &'a [u64],
module_style_types: &'a [StyleType],
request_cost: f32,
module_factor_cost: f32,
max_chunk_size: u64,
}
impl CostContext<'_> {
/// Cost-delta of merging the split at `i`: `cost(merged) - cost(left) - cost(right)`,
/// where left/right are the two would-be neighbours and merged is their concatenation
/// across the gap. Negative means the merge reduces total cost.
fn split_metric(&self, split_points: &[bool], order: &[usize], i: usize) -> f32 {
let (start, end) = affected_range(split_points, i);
let left = &order[start..=i];
let right = &order[i + 1..=end];
let merged = &order[start..=end];
self.chunk_cost(merged) - self.chunk_cost(left) - self.chunk_cost(right)
}
/// Cost of loading a single chunk: summed over the chunk groups that load it (a group
/// "loads" a chunk if it shares ≥ 1 module with it).
///
/// Returns `+infinity` (`f32::INFINITY`) when the chunk violates a hard constraint:
/// * `max_chunk_size` exceeded for a multi-item chunk; or
/// * a [`StyleType::GlobalStyle`] module would leak into a chunk group that doesn't already
/// load that specific module.
fn chunk_cost(&self, chunk: &[usize]) -> f32 {
let chunk_size: u64 = chunk.iter().map(|&id| self.module_sizes[id]).sum();
if chunk.len() > 1 && self.max_chunk_size > 0 && chunk_size > self.max_chunk_size {
return f32::INFINITY;
}
// Chunk groups that load this chunk = union of `module_to_groups[id]` for `id` in
// `chunk`. The inverse index lets us avoid scanning every input chunk group on each
// call.
let mut loading_groups: Vec<u32> = Vec::new();
for &id in chunk {
loading_groups.extend_from_slice(&self.module_to_groups[id]);
}
loading_groups.sort_unstable();
loading_groups.dedup();
// Global CSS leakage check: every loading group must already be a "container" of each
// `GlobalStyle` module in the chunk — i.e. `module_to_groups[id]` ⊇ `loading_groups`.
// Tested via binary search on the (sorted) container list rather than scanning the
// group's module list.
for &id in chunk {
if self.module_style_types[id] != StyleType::GlobalStyle {
continue;
}
let containing = &self.module_to_groups[id];
if loading_groups
.iter()
.any(|gi| containing.binary_search(gi).is_err())
{
return f32::INFINITY;
}
}
// Per-group cost: `chunk_size + (chunk_size / group_total) * module_factor_cost +
// request_cost`. Total is the sum across all loading groups.
let chunk_size_f = chunk_size as f32;
loading_groups
.iter()
.map(|&gi| {
let group_total = self.group_total_size[gi as usize] as f32;
chunk_size_f
+ (chunk_size_f / group_total) * self.module_factor_cost
+ self.request_cost
})
.sum()
}
}
// ---------------------------------------------------------------------------
// compute_chunked_chunk_groups (used by the e2e test)
// ---------------------------------------------------------------------------
/// Map each input chunk group to the deduplicated, ordered list of chunk indices it needs to
/// load. Mirrors `computeChunkedChunkGroups` from the PoC.
#[cfg(test)]
pub(super) fn compute_chunked_chunk_groups(
chunk_groups: &[Vec<usize>],
chunks: &[Vec<usize>],
) -> Vec<Vec<usize>> {
let mut module_to_chunk: FxHashMap<usize, usize> = FxHashMap::default();
for (chunk_index, chunk) in chunks.iter().enumerate() {
for &id in chunk {
module_to_chunk.insert(id, chunk_index);
}
}
chunk_groups
.iter()
.map(|group| {
let mut chunk_indices: Vec<usize> = group
.iter()
.filter_map(|id| module_to_chunk.get(id).copied())
.collect();
chunk_indices.sort_unstable();
chunk_indices.dedup();
chunk_indices
})
.collect()
}
//! Graph-based CSS chunking algorithm.
//!
//! Selected by `experimental.cssChunking: "graph"` in Next.js. An alternative to the default
//! ("loose") algorithm in [`super::style_groups`].
//!
//! # Pipeline
//!
//! ```text
//! create_graph → make_acyclic → linearize → split_into_chunks → assemble batches
//! ```
//!
//! 1. **`create_graph`** — for each chunk group, the ordered list of CSS modules is converted into
//! pairwise "later depends on earlier" edges in a directed weighted graph. Edge weights
//! accumulate when the same `(from, to)` pair occurs in multiple groups.
//! 2. **`make_acyclic`** — co-occurrence almost always produces cycles. Each multi-node SCC has its
//! lowest-weight edge cut until the graph is a DAG. Heavy edges represent strong co-occurrence
//! and are preserved.
//! 3. **`linearize`** — Kahn-style topological sort with a tie-break: when several dependents
//! become unblocked at once, the heaviest edge wins (and insertion order breaks ties among equal
//! weights). This places strongly co-occurring modules adjacent in the global order.
//! 4. **`split_into_chunks`** — greedy bottom-up merger over the global order. At every active
//! split point we score the merge as `cost(merged) - cost(left) - cost(right)` and take the
//! most-negative score. We stop when no remaining merge would reduce cost.
//!
//! # Cost model
//!
//! Per chunk loaded by a chunk group:
//!
//! ```text
//! cost_per_group(chunk, group)
//! = chunk_size
//! + (chunk_size / group_total_size) * module_factor_cost
//! + request_cost
//! ```
//!
//! where `chunk_size` is the sum of module byte sizes in the chunk and `group_total_size` is the
//! total CSS byte size of the chunk group. The total cost of a chunk is summed over the chunk
//! groups that load it (a group "loads" a chunk if it shares ≥ 1 module with it).
//!
//! `request_cost` (in bytes — same unit as module sizes) charges for every CSS request a chunk
//! group makes. Larger values bias toward fewer, larger shared chunks.
//!
//! `module_factor_cost` controls how much the algorithm cares about small chunk groups:
//!
//! * `0` distributes overshipped bytes evenly across chunk groups.
//! * Higher values penalize overshipping in small chunk groups proportionally more, so small pages
//! ship fewer unrelated styles at the expense of more requests overall.
//!
//! # Constraints
//!
//! * `max_chunk_size` is enforced by treating any merge that would produce a multi-item chunk
//! exceeding the cap as `+infinity` cost (single-item chunks larger than the cap are left alone).
//! * Global CSS (`StyleType::GlobalStyle`) must not leak into unrelated chunk groups: any merge
//! that would put a global item into a chunk loaded by a chunk group not currently loading that
//! item is treated as `+infinity` cost.
use anyhow::Result;
use indexmap::map::Entry;
use rustc_hash::FxHashSet;
use tracing::{Instrument, instrument};
use turbo_tasks::{FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, Vc};
use crate::{
chunk::{
ChunkItemBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
ChunkableModule, ChunkingContext, chunk_item_batch::attach_async_info_to_chunkable_module,
},
module::{StyleModule, StyleType},
module_graph::{
GraphTraversalAction, ModuleGraph,
module_batch::ModuleOrBatch,
module_batches::ModuleBatchesGraphEdge,
style_groups::{StyleGroups, StyleItemInfo, make_style_groups},
},
};
mod algorithm;
mod subgraph_view;
#[cfg(test)]
mod tests;
/// Per-CSS-module data the graph algorithm needs. Built once during the per-chunk-group walk.
struct ModuleData {
style_type: StyleType,
/// Byte size of the module's chunk item.
size: u64,
chunk_item: ChunkItemWithAsyncModuleInfo,
}
/// A module that has been classified as a style module during the chunk-group walk. Carries both
/// the chunkable view (for size + chunk-item resolution) and the style view (for `style_type`),
/// so [`resolve_module_data`] doesn't need to repeat the sidecast.
struct StyleModuleRef {
chunkable: ResolvedVc<Box<dyn ChunkableModule>>,
style: ResolvedVc<Box<dyn StyleModule>>,
}
/// Per-discovered-chunkable-module classification: `Some((id, style))` for CSS modules and
/// `None` for non-CSS modules.
type ClassifiedModule = Option<(usize, ResolvedVc<Box<dyn StyleModule>>)>;
/// Build [`StyleGroups`] using the graph-analysis algorithm. See the module-level docs for
/// details.
#[instrument(skip(module_graph, chunking_context))]
pub async fn compute_style_groups_graph(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
request_cost: f32,
module_factor_cost: f32,
max_chunk_size: u64,
) -> Result<Vc<StyleGroups>> {
// 1. Walk every chunk group post-order and collect, for each group, the ordered list of CSS
// modules. Module ids are densely allocated as we encounter modules for the first time.
let (chunk_groups, modules_in_order) = collect_chunk_groups(module_graph, chunking_context)
.instrument(tracing::trace_span!("collect_chunk_groups"))
.await?;
if modules_in_order.is_empty() {
return Ok(make_style_groups(FxIndexMap::default()));
}
// 2. Resolve each module's `ChunkItemWithAsyncModuleInfo` and byte size in parallel.
let module_data = resolve_module_data(module_graph, chunking_context, &modules_in_order)
.instrument(tracing::trace_span!("resolve_module_data"))
.await?;
let module_sizes: Vec<u64> = module_data.iter().map(|m| m.size).collect();
let module_style_types: Vec<StyleType> = module_data.iter().map(|m| m.style_type).collect();
// 3. Run the synchronous chunking pipeline.
let mut graph = tracing::trace_span!("create_graph")
.in_scope(|| algorithm::create_graph(&chunk_groups, modules_in_order.len()));
tracing::trace_span!("make_acyclic").in_scope(|| algorithm::make_acyclic(&mut graph));
let global_order = tracing::trace_span!("linearize").in_scope(|| algorithm::linearize(&graph));
let chunks = tracing::trace_span!("split_into_chunks").in_scope(|| {
algorithm::split_into_chunks(
&global_order,
&chunk_groups,
&module_sizes,
&module_style_types,
request_cost,
module_factor_cost,
max_chunk_size,
)
});
// 4. Assemble the result. Each multi-item chunk becomes a `ChunkItemBatch`; singletons get a
// `batch = None` entry so the production sort still places them at the right `order`.
assemble_style_groups(&chunks, &module_data)
.instrument(tracing::trace_span!("assemble"))
.await
}
async fn assemble_style_groups(
chunks: &[Vec<usize>],
module_data: &[ModuleData],
) -> Result<Vc<StyleGroups>> {
let mut shared_chunk_items: FxIndexMap<ChunkItemWithAsyncModuleInfo, StyleItemInfo> =
FxIndexMap::default();
let mut order_counter: u32 = 0;
let mut push =
|map: &mut FxIndexMap<ChunkItemWithAsyncModuleInfo, StyleItemInfo>,
chunk_item: ChunkItemWithAsyncModuleInfo,
batch: Option<ResolvedVc<ChunkItemBatchWithAsyncModuleInfo>>| {
map.insert(
chunk_item,
StyleItemInfo {
order: Some(order_counter),
batch,
},
);
order_counter += 1;
};
for chunk in chunks {
if chunk.is_empty() {
continue;
}
if chunk.len() == 1 {
push(
&mut shared_chunk_items,
module_data[chunk[0]].chunk_item,
None,
);
continue;
}
let chunk_items: Vec<_> = chunk.iter().map(|&id| module_data[id].chunk_item).collect();
let batch = ChunkItemBatchWithAsyncModuleInfo::new(chunk_items.clone())
.to_resolved()
.await?;
for chunk_item in chunk_items {
push(&mut shared_chunk_items, chunk_item, Some(batch));
}
}
// `linearize` operates on a DAG and processes every node, so every module the algorithm saw
// must already have been emitted. Catch a future regression of that invariant in dev builds.
debug_assert!(
module_data
.iter()
.all(|data| shared_chunk_items.contains_key(&data.chunk_item)),
"linearize dropped a module: every module reached by the chunk-group walk must appear in \
the final chunk-item map",
);
Ok(make_style_groups(shared_chunk_items))
}
/// Walk every chunk group post-order, returning `(chunk_groups, modules_in_order)` where:
/// * `chunk_groups[i]` is the list of CSS module ids loaded by chunk group `i` (after dedup of
/// empty groups),
/// * `modules_in_order` is the densely-numbered list of distinct CSS modules referenced by any
/// chunk group, in insertion order.
async fn collect_chunk_groups(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<(Vec<Vec<usize>>, Vec<StyleModuleRef>)> {
let chunk_group_info = module_graph.chunk_group_info().await?;
let batches_graph = module_graph
.module_batches(chunking_context.batching_config())
.await?;
// Per discovered chunkable module: `Some((id, sidecast_style))` for CSS modules and `None`
// for non-CSS modules (which still occupy an entry so we don't repeat the classification).
// Ids are densely packed in `0..modules_in_order.len()` — assigned via a separate counter
// because the underlying `IndexMap`'s insertion order also includes non-CSS entries.
let mut module_id_map: FxIndexMap<ResolvedVc<Box<dyn ChunkableModule>>, ClassifiedModule> =
FxIndexMap::default();
let mut next_css_id: usize = 0;
let mut chunk_groups: Vec<Vec<usize>> = Vec::new();
for (i, chunk_group) in chunk_group_info.chunk_groups.iter().enumerate() {
let ordered_entries = batches_graph.get_ordered_entries(&chunk_group_info, i);
let mut entries = Vec::with_capacity(chunk_group.entries_count());
for entry in ordered_entries {
entries.push(batches_graph.get_entry_index(entry).await?);
}
let mut visited = FxHashSet::default();
let mut items_in_postorder = FxIndexSet::default();
batches_graph.traverse_edges_from_entries_dfs(
entries.iter().copied(),
&mut (),
|parent_info, module, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
&& !ty.is_parallel()
{
return Ok(GraphTraversalAction::Exclude);
}
if visited.insert(module) {
Ok(GraphTraversalAction::Continue)
} else {
Ok(GraphTraversalAction::Exclude)
}
},
|parent_info, item, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
&& !ty.is_parallel()
{
return;
}
items_in_postorder.insert(*item);
},
)?;
// Collect CSS module ids for this group, classifying modules on first sight. `seen`
// dedups within a single group in O(1); the parallel `ids` Vec preserves insertion
// order.
let mut ids: Vec<usize> = Vec::new();
let mut seen: FxHashSet<usize> = FxHashSet::default();
let mut handle_module = async |module| -> Result<()> {
let id_slot = match module_id_map.entry(module) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
let assigned =
ResolvedVc::try_sidecast::<Box<dyn StyleModule>>(module).map(|style| {
let id = next_css_id;
next_css_id += 1;
(id, style)
});
e.insert(assigned);
assigned
}
};
if let Some((id, _)) = id_slot
&& seen.insert(id)
{
ids.push(id);
}
Ok(())
};
for item in items_in_postorder {
match item {
ModuleOrBatch::Batch(batch) => {
for &module in &batch.await?.modules {
handle_module(module).await?;
}
}
ModuleOrBatch::Module(module) => {
if let Some(chunkable_module) = ResolvedVc::try_downcast(module) {
handle_module(chunkable_module).await?;
}
}
ModuleOrBatch::None(_) => {}
}
}
if !ids.is_empty() {
chunk_groups.push(ids);
}
}
// Compact the id space: drop entries for non-CSS modules and keep CSS modules in insertion
// order. The sidecast `StyleModule` is carried through so [`resolve_module_data`] doesn't
// need to redo it.
let modules_in_order: Vec<StyleModuleRef> = module_id_map
.iter()
.filter_map(|(&chunkable, slot)| slot.map(|(_, style)| StyleModuleRef { chunkable, style }))
.collect();
Ok((chunk_groups, modules_in_order))
}
/// Resolve each module's chunk item and byte size in parallel. The returned vec is parallel to
/// `modules`.
async fn resolve_module_data(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
modules: &[StyleModuleRef],
) -> Result<Vec<ModuleData>> {
let async_module_info = module_graph.async_module_info();
modules
.iter()
.map(async |m| -> Result<ModuleData> {
let style_type = *m.style.style_type().await?;
let chunk_item = attach_async_info_to_chunkable_module(
m.chunkable,
async_module_info,
module_graph,
chunking_context,
)
.await?;
let size = *chunk_item
.chunk_type
.chunk_item_size(chunking_context, *chunk_item.chunk_item, None)
.await?;
Ok(ModuleData {
style_type,
size: size as u64,
chunk_item,
})
})
.try_join()
.await
}
//! `SubgraphView`: a borrow-only filtered view over a [`petgraph::graph::DiGraph`] driven by a
//! [`rustc_hash::FxHashSet`] of node indices.
//!
//! The PoC algorithms ([`super::algorithm`]) accept any type that implements [`ReadonlyGraph`].
//! That lets us pass either a `&DiGraph` directly or a `SubgraphView` restricted to e.g. one
//! SCC, without cloning the underlying graph.
use std::marker::PhantomData;
use petgraph::{
Direction,
graph::{DiGraph, NodeIndex},
};
use rustc_hash::FxHashSet;
/// Read-only view over a directed weighted graph. Implemented for `&DiGraph<N, u32>` and for
/// [`SubgraphView`].
#[allow(dead_code)] // Some methods are kept for symmetry with the JS PoC; not all are used yet.
pub(super) trait ReadonlyGraph<'a>: Copy {
type NodesIter: Iterator<Item = NodeIndex>;
type OutgoingIter: Iterator<Item = NodeIndex>;
type IncomingIter: Iterator<Item = NodeIndex>;
type OutgoingWithWeightIter: Iterator<Item = (NodeIndex, u32)>;
type IncomingWithWeightIter: Iterator<Item = (NodeIndex, u32)>;
fn nodes(self) -> Self::NodesIter;
fn node_count(self) -> usize;
/// Upper bound on `NodeIndex::index()` values returned by this view. Always equals the
/// underlying [`DiGraph`]'s node count, regardless of any subset filtering. Useful for
/// sizing scratch arrays keyed by node id.
fn index_bound(self) -> usize;
fn outgoing_edges(self, node: NodeIndex) -> Self::OutgoingIter;
fn outgoing_edges_with_weight(self, node: NodeIndex) -> Self::OutgoingWithWeightIter;
fn incoming_edges(self, node: NodeIndex) -> Self::IncomingIter;
fn incoming_edges_with_weight(self, node: NodeIndex) -> Self::IncomingWithWeightIter;
}
impl<'a, N: 'a> ReadonlyGraph<'a> for &'a DiGraph<N, u32> {
type NodesIter = petgraph::graph::NodeIndices<u32>;
type OutgoingIter = petgraph::graph::Neighbors<'a, u32>;
type IncomingIter = petgraph::graph::Neighbors<'a, u32>;
type OutgoingWithWeightIter = NeighborsWithWeight<'a, N>;
type IncomingWithWeightIter = NeighborsWithWeight<'a, N>;
fn nodes(self) -> Self::NodesIter {
self.node_indices()
}
fn node_count(self) -> usize {
DiGraph::node_count(self)
}
fn index_bound(self) -> usize {
DiGraph::node_count(self)
}
fn outgoing_edges(self, node: NodeIndex) -> Self::OutgoingIter {
self.neighbors_directed(node, Direction::Outgoing)
}
fn outgoing_edges_with_weight(self, node: NodeIndex) -> Self::OutgoingWithWeightIter {
NeighborsWithWeight {
graph: self,
iter: self.neighbors_directed(node, Direction::Outgoing).detach(),
_n: PhantomData,
}
}
fn incoming_edges(self, node: NodeIndex) -> Self::IncomingIter {
self.neighbors_directed(node, Direction::Incoming)
}
fn incoming_edges_with_weight(self, node: NodeIndex) -> Self::IncomingWithWeightIter {
NeighborsWithWeight {
graph: self,
iter: self.neighbors_directed(node, Direction::Incoming).detach(),
_n: PhantomData,
}
}
}
/// Iterator over a node's neighbors plus the weight of each edge.
pub(super) struct NeighborsWithWeight<'a, N> {
graph: &'a DiGraph<N, u32>,
iter: petgraph::graph::WalkNeighbors<u32>,
_n: PhantomData<N>,
}
impl<'a, N> Iterator for NeighborsWithWeight<'a, N> {
type Item = (NodeIndex, u32);
fn next(&mut self) -> Option<Self::Item> {
let (edge, target) = self.iter.next(self.graph)?;
Some((target, *self.graph.edge_weight(edge).unwrap()))
}
}
/// A live view over `graph` restricted to the nodes in `subset`. Edges whose source or target
/// is outside the subset are filtered out on iteration.
pub(super) struct SubgraphView<'a, N> {
graph: &'a DiGraph<N, u32>,
subset: &'a FxHashSet<NodeIndex>,
}
impl<'a, N> SubgraphView<'a, N> {
pub(super) fn new(graph: &'a DiGraph<N, u32>, subset: &'a FxHashSet<NodeIndex>) -> Self {
Self { graph, subset }
}
}
impl<'a, N> Clone for SubgraphView<'a, N> {
fn clone(&self) -> Self {
*self
}
}
impl<'a, N> Copy for SubgraphView<'a, N> {}
impl<'a, N: 'a> ReadonlyGraph<'a> for SubgraphView<'a, N> {
type NodesIter = SubgraphNodes<'a>;
type OutgoingIter = SubgraphNeighbors<'a, N>;
type IncomingIter = SubgraphNeighbors<'a, N>;
type OutgoingWithWeightIter = SubgraphNeighborsWithWeight<'a, N>;
type IncomingWithWeightIter = SubgraphNeighborsWithWeight<'a, N>;
fn nodes(self) -> Self::NodesIter {
SubgraphNodes {
iter: self.subset.iter(),
}
}
fn node_count(self) -> usize {
// Nodes are never removed from the graph, so every subset element is valid.
self.subset.len()
}
fn index_bound(self) -> usize {
self.graph.node_count()
}
fn outgoing_edges(self, node: NodeIndex) -> Self::OutgoingIter {
SubgraphNeighbors {
iter: if self.subset.contains(&node) {
Some(self.graph.neighbors_directed(node, Direction::Outgoing))
} else {
None
},
subset: self.subset,
_n: PhantomData,
}
}
fn outgoing_edges_with_weight(self, node: NodeIndex) -> Self::OutgoingWithWeightIter {
SubgraphNeighborsWithWeight {
graph: self.graph,
iter: if self.subset.contains(&node) {
Some(
self.graph
.neighbors_directed(node, Direction::Outgoing)
.detach(),
)
} else {
None
},
subset: self.subset,
_n: PhantomData,
}
}
fn incoming_edges(self, node: NodeIndex) -> Self::IncomingIter {
SubgraphNeighbors {
iter: if self.subset.contains(&node) {
Some(self.graph.neighbors_directed(node, Direction::Incoming))
} else {
None
},
subset: self.subset,
_n: PhantomData,
}
}
fn incoming_edges_with_weight(self, node: NodeIndex) -> Self::IncomingWithWeightIter {
SubgraphNeighborsWithWeight {
graph: self.graph,
iter: if self.subset.contains(&node) {
Some(
self.graph
.neighbors_directed(node, Direction::Incoming)
.detach(),
)
} else {
None
},
subset: self.subset,
_n: PhantomData,
}
}
}
pub(super) struct SubgraphNodes<'a> {
iter: std::collections::hash_set::Iter<'a, NodeIndex>,
}
impl<'a> Iterator for SubgraphNodes<'a> {
type Item = NodeIndex;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().copied()
}
}
pub(super) struct SubgraphNeighbors<'a, N> {
iter: Option<petgraph::graph::Neighbors<'a, u32>>,
subset: &'a FxHashSet<NodeIndex>,
_n: PhantomData<N>,
}
impl<'a, N> Iterator for SubgraphNeighbors<'a, N> {
type Item = NodeIndex;
fn next(&mut self) -> Option<Self::Item> {
let it = self.iter.as_mut()?;
it.by_ref().find(|n| self.subset.contains(n))
}
}
pub(super) struct SubgraphNeighborsWithWeight<'a, N> {
graph: &'a DiGraph<N, u32>,
iter: Option<petgraph::graph::WalkNeighbors<u32>>,
subset: &'a FxHashSet<NodeIndex>,
_n: PhantomData<N>,
}
impl<'a, N> Iterator for SubgraphNeighborsWithWeight<'a, N> {
type Item = (NodeIndex, u32);
fn next(&mut self) -> Option<Self::Item> {
let it = self.iter.as_mut()?;
while let Some((edge, target)) = it.next(self.graph) {
if self.subset.contains(&target) {
return Some((target, *self.graph.edge_weight(edge).unwrap()));
}
}
None
}
}
//! Pure unit tests for the graph-based CSS chunking algorithm.
//!
//! Direct port of the PoC's `vitest` suites (see the upstream proof of concept). The
//! `e2e_*` tests cover the assembled pipeline; the rest cover individual stages.
use petgraph::graph::{DiGraph, NodeIndex};
use rustc_hash::FxHashSet;
use super::{
algorithm::{
compute_chunked_chunk_groups, create_graph, find_short_cycle, linearize, make_acyclic,
split_into_chunks, strongly_connected_components,
},
subgraph_view::{ReadonlyGraph, SubgraphView},
};
use crate::module::StyleType;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn n(i: usize) -> NodeIndex {
NodeIndex::new(i)
}
fn build_graph<F: FnOnce(&mut DiGraph<usize, u32>)>(
node_count: usize,
f: F,
) -> DiGraph<usize, u32> {
let mut g: DiGraph<usize, u32> = DiGraph::with_capacity(node_count, 0);
for i in 0..node_count {
g.add_node(i);
}
f(&mut g);
g
}
fn add_or_accumulate<N>(g: &mut DiGraph<N, u32>, from: NodeIndex, to: NodeIndex, weight: u32) {
if let Some(e) = g.find_edge(from, to) {
*g.edge_weight_mut(e).unwrap() += weight;
} else {
g.add_edge(from, to, weight);
}
}
fn outgoing_targets<'a, G: ReadonlyGraph<'a>>(g: G, node: NodeIndex) -> Vec<usize> {
let mut v: Vec<usize> = g.outgoing_edges(node).map(|n| n.index()).collect();
v.sort_unstable();
v
}
fn incoming_targets<'a, G: ReadonlyGraph<'a>>(g: G, node: NodeIndex) -> Vec<usize> {
let mut v: Vec<usize> = g.incoming_edges(node).map(|n| n.index()).collect();
v.sort_unstable();
v
}
fn outgoing_with_weight<'a, G: ReadonlyGraph<'a>>(g: G, node: NodeIndex) -> Vec<(usize, u32)> {
let mut v: Vec<(usize, u32)> = g
.outgoing_edges_with_weight(node)
.map(|(n, w)| (n.index(), w))
.collect();
v.sort_unstable_by_key(|(t, _)| *t);
v
}
fn incoming_with_weight<'a, G: ReadonlyGraph<'a>>(g: G, node: NodeIndex) -> Vec<(usize, u32)> {
let mut v: Vec<(usize, u32)> = g
.incoming_edges_with_weight(node)
.map(|(n, w)| (n.index(), w))
.collect();
v.sort_unstable_by_key(|(t, _)| *t);
v
}
fn to_set(v: &[NodeIndex]) -> FxHashSet<NodeIndex> {
v.iter().copied().collect()
}
fn ids(v: &[NodeIndex]) -> Vec<usize> {
v.iter().map(|n| n.index()).collect()
}
fn equal_size_inputs(node_count: usize) -> Vec<u64> {
vec![1; node_count]
}
fn no_global(node_count: usize) -> Vec<StyleType> {
vec![StyleType::IsolatedStyle; node_count]
}
fn split_simple(
global_order: &[NodeIndex],
chunk_groups: &[Vec<usize>],
request_cost: f32,
) -> Vec<Vec<usize>> {
let count = global_order.len();
split_into_chunks(
global_order,
chunk_groups,
&equal_size_inputs(count),
&no_global(count),
request_cost,
// module_factor_cost = 0 reproduces the PoC's `(requestOverhead + 1*M) * N`.
0.0,
0,
)
}
// ---------------------------------------------------------------------------
// Graph + SubgraphView
// ---------------------------------------------------------------------------
#[test]
fn graph_add_edge_creates_forward_and_backward_edges() {
let g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 1);
});
assert_eq!(outgoing_targets(&g, n(0)), vec![1]);
assert_eq!(incoming_targets(&g, n(1)), vec![0]);
assert!(outgoing_targets(&g, n(1)).is_empty());
assert!(incoming_targets(&g, n(0)).is_empty());
}
#[test]
fn graph_add_edge_default_weight_one() {
let g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 1);
});
assert_eq!(outgoing_with_weight(&g, n(0)), vec![(1, 1)]);
assert_eq!(incoming_with_weight(&g, n(1)), vec![(0, 1)]);
}
#[test]
fn graph_add_edge_explicit_weight() {
let g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 5);
});
assert_eq!(outgoing_with_weight(&g, n(0)), vec![(1, 5)]);
assert_eq!(incoming_with_weight(&g, n(1)), vec![(0, 5)]);
}
#[test]
fn graph_add_edge_accumulates_weights_for_repeated_edges() {
let g = build_graph(2, |g| {
add_or_accumulate(g, n(0), n(1), 1);
add_or_accumulate(g, n(0), n(1), 2);
add_or_accumulate(g, n(0), n(1), 3);
});
assert_eq!(outgoing_with_weight(&g, n(0)), vec![(1, 6)]);
assert_eq!(incoming_with_weight(&g, n(1)), vec![(0, 6)]);
}
#[test]
fn graph_forward_and_reverse_edges_are_independent() {
let g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 2);
g.add_edge(n(1), n(0), 7);
});
assert_eq!(outgoing_with_weight(&g, n(0)), vec![(1, 2)]);
assert_eq!(outgoing_with_weight(&g, n(1)), vec![(0, 7)]);
assert_eq!(incoming_with_weight(&g, n(0)), vec![(1, 7)]);
assert_eq!(incoming_with_weight(&g, n(1)), vec![(0, 2)]);
}
#[test]
fn graph_supports_self_loops() {
let g = build_graph(1, |g| {
g.add_edge(n(0), n(0), 3);
});
assert_eq!(outgoing_with_weight(&g, n(0)), vec![(0, 3)]);
assert_eq!(incoming_with_weight(&g, n(0)), vec![(0, 3)]);
}
#[test]
fn subgraphview_nodes_returns_only_nodes_in_subset() {
let g = build_graph(3, |_| {});
let subset: FxHashSet<_> = [n(0), n(2)].into_iter().collect();
let view = SubgraphView::new(&g, &subset);
let mut nodes: Vec<usize> = view.nodes().map(|n| n.index()).collect();
nodes.sort_unstable();
assert_eq!(nodes, vec![0, 2]);
}
#[test]
fn subgraphview_filters_edges_to_nodes_in_subset() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
g.add_edge(n(0), n(2), 1);
});
let subset: FxHashSet<_> = [n(0), n(2)].into_iter().collect();
let view = SubgraphView::new(&g, &subset);
assert_eq!(outgoing_targets(view, n(0)), vec![2]);
assert_eq!(incoming_targets(view, n(2)), vec![0]);
assert!(outgoing_targets(view, n(1)).is_empty());
assert!(incoming_targets(view, n(1)).is_empty());
}
#[test]
fn subgraphview_preserves_edge_weights() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 5);
g.add_edge(n(0), n(2), 3);
});
let subset: FxHashSet<_> = [n(0), n(2)].into_iter().collect();
let view = SubgraphView::new(&g, &subset);
assert_eq!(outgoing_with_weight(view, n(0)), vec![(2, 3)]);
assert_eq!(incoming_with_weight(view, n(2)), vec![(0, 3)]);
}
#[test]
fn subgraphview_outgoing_for_node_outside_subset_yields_nothing() {
let g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 1);
});
let subset: FxHashSet<_> = [n(0)].into_iter().collect();
let view = SubgraphView::new(&g, &subset);
assert!(outgoing_targets(view, n(1)).is_empty());
}
// ---------------------------------------------------------------------------
// create_graph
// ---------------------------------------------------------------------------
#[test]
fn create_graph_empty_input_produces_empty_graph() {
let g = create_graph(&[], 0);
assert_eq!(g.node_count(), 0);
}
#[test]
fn create_graph_assigns_sequential_indices() {
// Note: in the PoC, `createGraph` assigns node ids by first-appearance. In the Rust port the
// caller pre-assigns ids, so we test that node count and edge structure match.
let g = create_graph(&[vec![0, 1, 2]], 3);
assert_eq!(g.node_count(), 3);
}
#[test]
fn create_graph_pairwise_edges_for_each_group() {
// group [0, 1, 2, 3] => 1->0, 2->0, 2->1, 3->0, 3->1, 3->2
let g = create_graph(&[vec![0, 1, 2, 3]], 4);
assert!(outgoing_targets(&g, n(0)).is_empty());
assert_eq!(outgoing_targets(&g, n(1)), vec![0]);
assert_eq!(outgoing_targets(&g, n(2)), vec![0, 1]);
assert_eq!(outgoing_targets(&g, n(3)), vec![0, 1, 2]);
}
#[test]
fn create_graph_all_edge_weights_are_one_within_a_single_group() {
let g = create_graph(&[vec![0, 1, 2]], 3);
assert_eq!(outgoing_with_weight(&g, n(1)), vec![(0, 1)]);
assert_eq!(outgoing_with_weight(&g, n(2)), vec![(0, 1), (1, 1)]);
}
#[test]
fn create_graph_accumulates_weights_for_repeated_pairs() {
let g = create_graph(&[vec![0, 1], vec![0, 1], vec![0, 1]], 2);
assert_eq!(outgoing_with_weight(&g, n(1)), vec![(0, 3)]);
assert_eq!(incoming_with_weight(&g, n(0)), vec![(1, 3)]);
}
#[test]
fn create_graph_single_element_groups_produce_no_edges() {
let g = create_graph(&[vec![0], vec![1]], 2);
assert!(outgoing_targets(&g, n(0)).is_empty());
assert!(outgoing_targets(&g, n(1)).is_empty());
assert!(incoming_targets(&g, n(0)).is_empty());
assert!(incoming_targets(&g, n(1)).is_empty());
}
#[test]
fn create_graph_preserves_group_order_when_computing_edges() {
// [0, 1, 2] then [2, 1, 0] should produce edges in BOTH directions.
let g = create_graph(&[vec![0, 1, 2], vec![2, 1, 0]], 3);
assert_eq!(outgoing_with_weight(&g, n(0)), vec![(1, 1), (2, 1)]);
assert_eq!(outgoing_with_weight(&g, n(1)), vec![(0, 1), (2, 1)]);
assert_eq!(outgoing_with_weight(&g, n(2)), vec![(0, 1), (1, 1)]);
}
#[test]
fn create_graph_duplicated_module_in_a_group_creates_self_loop() {
let g = create_graph(&[vec![0, 0]], 1);
assert_eq!(outgoing_with_weight(&g, n(0)), vec![(0, 1)]);
}
// ---------------------------------------------------------------------------
// strongly_connected_components
// ---------------------------------------------------------------------------
#[test]
fn scc_empty_graph_yields_no_components() {
let g: DiGraph<usize, u32> = DiGraph::new();
assert!(strongly_connected_components(&g).is_empty());
}
#[test]
fn scc_disconnected_nodes_each_form_own_component() {
let g = build_graph(3, |_| {});
let sccs = strongly_connected_components(&g);
assert_eq!(sccs.len(), 3);
for c in &sccs {
assert_eq!(c.len(), 1);
}
}
#[test]
fn scc_linear_chain_produces_singleton_components() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
});
let sccs = strongly_connected_components(&g);
let as_vecs: Vec<_> = sccs.iter().map(to_sorted_ids).collect();
assert_eq!(as_vecs, vec![vec![2], vec![1], vec![0]]);
}
#[test]
fn scc_three_cycle_is_one_component() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
g.add_edge(n(2), n(0), 1);
});
let sccs = strongly_connected_components(&g);
assert_eq!(sccs.len(), 1);
assert_eq!(sccs[0].len(), 3);
}
#[test]
fn scc_self_loop_forms_singleton() {
let g = build_graph(1, |g| {
g.add_edge(n(0), n(0), 1);
});
let sccs = strongly_connected_components(&g);
assert_eq!(sccs.len(), 1);
assert_eq!(sccs[0].len(), 1);
}
#[test]
fn scc_works_on_subgraphview() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(0), 1);
g.add_edge(n(1), n(2), 1);
});
let subset: FxHashSet<_> = [n(0), n(1)].into_iter().collect();
let view = SubgraphView::new(&g, &subset);
let sccs = strongly_connected_components(view);
assert_eq!(sccs.len(), 1);
assert_eq!(sccs[0].len(), 2);
}
#[test]
fn scc_handles_deep_dags_without_recursion() {
let count = 5000;
let g = build_graph(count, |g| {
for i in 0..count - 1 {
g.add_edge(n(i), n(i + 1), 1);
}
});
let sccs = strongly_connected_components(&g);
assert_eq!(sccs.len(), count);
for c in &sccs {
assert_eq!(c.len(), 1);
}
}
fn to_sorted_ids(s: &FxHashSet<NodeIndex>) -> Vec<usize> {
let mut v: Vec<usize> = s.iter().map(|n| n.index()).collect();
v.sort_unstable();
v
}
// ---------------------------------------------------------------------------
// find_short_cycle
// ---------------------------------------------------------------------------
fn is_valid_cycle<'a, G: ReadonlyGraph<'a>>(graph: G, cycle: &[NodeIndex]) -> bool {
if cycle.len() < 2 {
return false;
}
let unique: FxHashSet<_> = cycle.iter().copied().collect();
if unique.len() != cycle.len() {
return false;
}
for i in 0..cycle.len() {
let from = cycle[i];
let to = cycle[(i + 1) % cycle.len()];
if !graph.outgoing_edges(from).any(|t| t == to) {
return false;
}
}
true
}
#[test]
fn find_short_cycle_two_node_scc() {
let g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(0), 1);
});
let cycle = find_short_cycle(&g, None).expect("test graph has a cycle");
assert!(is_valid_cycle(&g, &cycle));
assert_eq!(
to_set(&cycle),
[n(0), n(1)].into_iter().collect::<FxHashSet<_>>()
);
}
#[test]
fn find_short_cycle_three_cycle() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
g.add_edge(n(2), n(0), 1);
});
let cycle = find_short_cycle(&g, None).expect("test graph has a cycle");
assert!(is_valid_cycle(&g, &cycle));
assert_eq!(cycle.len(), 3);
}
#[test]
fn find_short_cycle_prefers_two_cycle_when_longer_exists() {
// 2-cycle b ↔ c plus longer arm a → b → c → d → a. The 2-cycle should win.
let g = build_graph(4, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
g.add_edge(n(2), n(3), 1);
g.add_edge(n(3), n(0), 1);
g.add_edge(n(2), n(1), 1);
});
let cycle = find_short_cycle(&g, None).expect("test graph has a cycle");
assert!(is_valid_cycle(&g, &cycle));
assert_eq!(cycle.len(), 2);
assert_eq!(
to_set(&cycle),
[n(1), n(2)].into_iter().collect::<FxHashSet<_>>()
);
}
#[test]
fn find_short_cycle_uses_edge_weights_to_pick_lowest_total_weight() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 10);
g.add_edge(n(1), n(0), 10);
g.add_edge(n(0), n(2), 1);
g.add_edge(n(2), n(0), 1);
g.add_edge(n(1), n(2), 100);
g.add_edge(n(2), n(1), 100);
});
let cycle = find_short_cycle(&g, None).expect("test graph has a cycle");
assert!(is_valid_cycle(&g, &cycle));
assert_eq!(cycle.len(), 2);
assert_eq!(
to_set(&cycle),
[n(0), n(2)].into_iter().collect::<FxHashSet<_>>()
);
}
// ---------------------------------------------------------------------------
// make_acyclic
// ---------------------------------------------------------------------------
fn assert_acyclic<N>(g: &DiGraph<N, u32>) {
for c in strongly_connected_components(g) {
assert!(c.len() <= 1, "found multi-node SCC of size {}", c.len());
}
}
fn edge_set<N>(g: &DiGraph<N, u32>) -> FxHashSet<(usize, usize)> {
let mut s = FxHashSet::default();
for n in g.node_indices() {
for t in g.neighbors_directed(n, petgraph::Direction::Outgoing) {
s.insert((n.index(), t.index()));
}
}
s
}
#[test]
fn make_acyclic_leaves_a_dag_unchanged() {
let mut g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
g.add_edge(n(0), n(2), 1);
});
let before = edge_set(&g);
make_acyclic(&mut g);
assert_eq!(edge_set(&g), before);
}
#[test]
fn make_acyclic_breaks_a_two_cycle_by_removing_lowest_weight_edge() {
let mut g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 10);
g.add_edge(n(1), n(0), 3);
});
make_acyclic(&mut g);
assert_eq!(edge_set(&g), [(0, 1)].into_iter().collect::<FxHashSet<_>>());
}
#[test]
fn make_acyclic_breaks_a_three_cycle() {
let mut g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 5);
g.add_edge(n(1), n(2), 1);
g.add_edge(n(2), n(0), 8);
});
make_acyclic(&mut g);
assert_eq!(
edge_set(&g),
[(0, 1), (2, 0)].into_iter().collect::<FxHashSet<_>>()
);
}
#[test]
fn make_acyclic_does_not_remove_self_loops() {
let mut g = build_graph(1, |g| {
g.add_edge(n(0), n(0), 5);
});
make_acyclic(&mut g);
assert_eq!(edge_set(&g), [(0, 0)].into_iter().collect::<FxHashSet<_>>());
}
#[test]
fn make_acyclic_preserves_non_cycle_edges() {
let mut g = build_graph(4, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(0), 2);
g.add_edge(n(1), n(2), 100);
g.add_edge(n(2), n(3), 100);
});
make_acyclic(&mut g);
assert_acyclic(&g);
let edges = edge_set(&g);
assert!(edges.contains(&(1, 2)));
assert!(edges.contains(&(2, 3)));
}
// ---------------------------------------------------------------------------
// linearize
// ---------------------------------------------------------------------------
#[test]
fn linearize_empty_graph() {
let g: DiGraph<usize, u32> = DiGraph::new();
assert!(linearize(&g).is_empty());
}
#[test]
fn linearize_single_node() {
let g = build_graph(1, |_| {});
assert_eq!(ids(&linearize(&g)), vec![0]);
}
#[test]
fn linearize_emits_dependencies_before_dependents() {
// a -> b -> c (a depends on b depends on c). c is a sink.
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
});
assert_eq!(ids(&linearize(&g)), vec![2, 1, 0]);
}
#[test]
fn linearize_higher_weight_dependents_placed_earlier() {
// x is a sink; a (weight 1) and b (weight 10) both depend on x. b should be placed first.
let g = build_graph(3, |g| {
g.add_edge(n(1), n(0), 1);
g.add_edge(n(2), n(0), 10);
});
assert_eq!(ids(&linearize(&g)), vec![0, 2, 1]);
}
#[test]
fn linearize_breaks_weight_ties_by_insertion_order() {
// Both 1 and 2 depend on 0 with weight 1; 1's edge is added first, so 1 should be placed
// before 2 after 0.
let g = build_graph(3, |g| {
g.add_edge(n(1), n(0), 1);
g.add_edge(n(2), n(0), 1);
});
assert_eq!(ids(&linearize(&g)), vec![0, 1, 2]);
}
#[test]
fn linearize_diamond_is_topo() {
// 0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3
let g = build_graph(4, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(0), n(2), 1);
g.add_edge(n(1), n(3), 1);
g.add_edge(n(2), n(3), 1);
});
let order = linearize(&g);
assert_eq!(order.len(), 4);
let pos: std::collections::HashMap<NodeIndex, usize> =
order.iter().enumerate().map(|(i, n)| (*n, i)).collect();
assert!(pos[&n(3)] < pos[&n(1)]);
assert!(pos[&n(3)] < pos[&n(2)]);
assert!(pos[&n(1)] < pos[&n(0)]);
assert!(pos[&n(2)] < pos[&n(0)]);
}
#[test]
fn linearize_runs_on_subgraphview() {
let g = build_graph(3, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(2), 1);
});
let subset: FxHashSet<_> = [n(0), n(1)].into_iter().collect();
let view = SubgraphView::new(&g, &subset);
assert_eq!(ids(&linearize(view)), vec![1, 0]);
}
#[test]
fn linearize_returns_partial_result_for_cyclic_graph() {
let g = build_graph(2, |g| {
g.add_edge(n(0), n(1), 1);
g.add_edge(n(1), n(0), 1);
});
assert!(linearize(&g).is_empty());
}
// ---------------------------------------------------------------------------
// split_into_chunks
// ---------------------------------------------------------------------------
fn order(ids_: &[usize]) -> Vec<NodeIndex> {
ids_.iter().map(|&i| n(i)).collect()
}
#[test]
fn split_returns_empty_for_empty_global_order() {
let chunks = split_simple(&[], &[], 3.0);
assert!(chunks.is_empty());
}
#[test]
fn split_returns_single_chunk_for_one_module() {
let chunks = split_simple(&order(&[0]), &[vec![0]], 3.0);
assert_eq!(chunks, vec![vec![0]]);
}
#[test]
fn split_merges_two_modules_always_co_loaded() {
let chunks = split_simple(&order(&[0, 1]), &[vec![0, 1]], 3.0);
assert_eq!(chunks, vec![vec![0, 1]]);
}
#[test]
fn split_keeps_two_modules_separate_when_never_co_loaded() {
let chunks = split_simple(&order(&[0, 1]), &[vec![0], vec![1]], 3.0);
assert_eq!(chunks, vec![vec![0], vec![1]]);
}
#[test]
fn split_only_merges_adjacent_modules_that_share_chunk_groups() {
let chunks = split_simple(&order(&[0, 1, 2]), &[vec![0, 1], vec![2]], 3.0);
assert_eq!(chunks, vec![vec![0, 1], vec![2]]);
}
#[test]
fn split_merges_all_modules_when_every_group_contains_all() {
let chunks = split_simple(&order(&[0, 1, 2, 3]), &[vec![0, 1, 2, 3]], 3.0);
assert_eq!(chunks, vec![vec![0, 1, 2, 3]]);
}
#[test]
fn split_preserves_global_order_within_a_chunk() {
// global_order is [2, 0, 1] (not [0, 1, 2]) — the chunk should follow it.
let chunks = split_simple(&order(&[2, 0, 1]), &[vec![0, 1, 2]], 3.0);
assert_eq!(chunks, vec![vec![2, 0, 1]]);
}
#[test]
fn split_does_not_merge_across_modules_no_one_co_loads() {
// 0 and 2 are co-loaded but 1 is loaded alone; merging across 1 would balloon cost.
let chunks = split_simple(&order(&[0, 1, 2]), &[vec![0, 2], vec![1]], 3.0);
assert_eq!(chunks, vec![vec![0], vec![1], vec![2]]);
}
#[test]
fn split_higher_request_overhead_drives_more_aggressive_merging() {
let groups = vec![vec![0, 1], vec![1, 2]];
let chunks_low = split_simple(&order(&[0, 1, 2]), &groups, 1.0);
assert_eq!(chunks_low, vec![vec![0], vec![1], vec![2]]);
let chunks_high = split_simple(&order(&[0, 1, 2]), &groups, 10.0);
assert_eq!(chunks_high, vec![vec![0, 1, 2]]);
}
// ---------------------------------------------------------------------------
// e2e (PoC pipeline)
// ---------------------------------------------------------------------------
fn run_pipeline(
chunk_groups: &[Vec<usize>],
node_count: usize,
request_cost: f32,
) -> (Vec<Vec<usize>>, Vec<usize>) {
let mut g = create_graph(chunk_groups, node_count);
make_acyclic(&mut g);
let global_order = linearize(&g);
let chunks = split_simple(&global_order, chunk_groups, request_cost);
let chunked = compute_chunked_chunk_groups(chunk_groups, &chunks);
let request_counts: Vec<usize> = chunked.iter().map(|c| c.len()).collect();
(chunks, request_counts)
}
#[test]
fn e2e_shared_sandwich_request_counts() {
// Names → ids: shared-a=0, a=1, shared-b=2, b=3, c=4
// Groups (PoC):
// ['shared-a', 'a', 'shared-b']
// ['shared-a', 'b', 'shared-b']
// ['shared-a', 'c', 'shared-b']
// ['shared-a', 'b']
let groups = vec![vec![0, 1, 2], vec![0, 3, 2], vec![0, 4, 2], vec![0, 3]];
let (_chunks, requests) = run_pipeline(&groups, 5, 3.0);
// Each group makes at least one request.
for &r in &requests {
assert!(r >= 1);
}
}
#[test]
fn e2e_shared_sequence_overhead_curve() {
// Names → ids: x1=0, a=1, b=2, c=3, x2=4, y1=5, y2=6, z1=7, z2=8
let groups = vec![
vec![0, 1, 2, 3, 4],
vec![1, 2, 3, 5, 6],
vec![7, 8, 1, 2, 3],
];
let (_chunks_1, req_1) = run_pipeline(&groups, 9, 1.0);
let (_chunks_3, req_3) = run_pipeline(&groups, 9, 3.0);
let (_chunks_5, req_5) = run_pipeline(&groups, 9, 5.0);
// Higher request overhead → fewer (or equal) requests per group.
for i in 0..groups.len() {
assert!(
req_3[i] <= req_1[i],
"req_3 ({:?}) > req_1 ({:?})",
req_3,
req_1
);
assert!(
req_5[i] <= req_3[i],
"req_5 ({:?}) > req_3 ({:?})",
req_5,
req_3
);
}
}
use std::cmp::Reverse;
use anyhow::Result;
use indexmap::map::Entry;
use rustc_hash::{FxHashMap, FxHashSet};
use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use crate::{
chunk::{
ChunkItemBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
ChunkableModule, ChunkingContext, chunk_item_batch::attach_async_info_to_chunkable_module,
},
module::{Module, StyleModule, StyleType},
module_graph::{
GraphTraversalAction, ModuleGraph,
module_batch::ModuleOrBatch,
module_batches::ModuleBatchesGraphEdge,
style_groups::{StyleGroups, StyleGroupsConfig, StyleItemInfo},
},
};
#[derive(Debug)]
struct ModuleInfo {
style_type: StyleType,
ident: RcStr,
chunk_group_indices: FxHashMap<usize, usize>,
index_sum: usize,
size: usize,
chunk_item: Option<ChunkItemWithAsyncModuleInfo>,
}
impl ModuleInfo {
fn new(style_type: StyleType, ident: RcStr) -> Self {
Self {
style_type,
ident,
chunk_group_indices: Default::default(),
index_sum: 0,
size: 0,
chunk_item: None,
}
}
}
struct ChunkGroupState {
styles: FxIndexSet<ResolvedVc<Box<dyn ChunkableModule>>>,
/// Number of distinct chunks this chunk group still needs to load. The legacy algorithm
/// decrements this as it merges items into shared chunks.
requests: usize,
}
/// Per-chunk-group style module collection plus per-module metadata. Internal to the legacy
/// algorithm.
struct StyleCollection {
/// Per-module info, keyed by chunkable module. After collection, every value is `Some`
/// (vacant entries used while traversing have been dropped). The map is sorted by
/// `(index_sum, ident)` so insertion order is deterministic.
module_info_map: FxIndexMap<ResolvedVc<Box<dyn ChunkableModule>>, Option<ModuleInfo>>,
/// Per-chunk-group state. Indexed by the same `idx` stored in
/// `ModuleInfo::chunk_group_indices`.
chunk_group_state: Vec<ChunkGroupState>,
}
/// Walk every chunk group in `module_graph` post-order, collecting:
/// * the ordered list of CSS modules each chunk group loads,
/// * per-module metadata (style type, ident, size, chunk item, and per-group position).
async fn collect_style_modules_per_chunk_group(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<StyleCollection> {
let chunk_group_info = module_graph.chunk_group_info().await?;
let batches_graph = module_graph
.module_batches(chunking_context.batching_config())
.await?;
let async_module_info = module_graph.async_module_info();
let mut module_info_map: FxIndexMap<ResolvedVc<Box<dyn ChunkableModule>>, Option<ModuleInfo>> =
FxIndexMap::default();
// Compute the style modules in each chunk group
let mut chunk_group_state: Vec<ChunkGroupState> = Vec::new();
let mut idx = 0;
for (i, chunk_group) in chunk_group_info.chunk_groups.iter().enumerate() {
let ordered_entries = batches_graph.get_ordered_entries(&chunk_group_info, i);
let mut entries = Vec::with_capacity(chunk_group.entries_count());
for entry in ordered_entries {
entries.push(batches_graph.get_entry_index(entry).await?);
}
let mut visited = FxHashSet::default();
let mut items_in_postorder = FxIndexSet::default();
batches_graph.traverse_edges_from_entries_dfs(
entries.iter().copied(),
&mut (),
|parent_info, module, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
&& !ty.is_parallel()
{
return Ok(GraphTraversalAction::Exclude);
}
if visited.insert(module) {
Ok(GraphTraversalAction::Continue)
} else {
Ok(GraphTraversalAction::Exclude)
}
},
|parent_info, item, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
&& !ty.is_parallel()
{
return;
}
items_in_postorder.insert(*item);
},
)?;
let mut styles = FxIndexSet::default();
let mut handle_module = async |module| {
match module_info_map.entry(module) {
Entry::Occupied(mut e) => {
if let Some(info) = e.get_mut() {
info.chunk_group_indices.insert(idx, styles.len());
info.index_sum += styles.len();
styles.insert(module);
}
}
Entry::Vacant(e) => {
if let Some(style_module) =
ResolvedVc::try_sidecast::<Box<dyn StyleModule>>(module)
{
let style_type = *style_module.style_type().await?;
let mut info =
ModuleInfo::new(style_type, module.ident().to_string().owned().await?);
info.chunk_group_indices.insert(idx, styles.len());
info.index_sum += styles.len();
styles.insert(module);
e.insert(Some(info));
} else {
e.insert(None);
}
}
}
anyhow::Ok(())
};
for item in items_in_postorder {
match item {
ModuleOrBatch::Batch(batch) => {
for &module in &batch.await?.modules {
handle_module(module).await?;
}
}
ModuleOrBatch::Module(module) => {
if let Some(chunkable_module) = ResolvedVc::try_downcast(module) {
handle_module(chunkable_module).await?;
}
}
ModuleOrBatch::None(_) => {}
}
}
if !styles.is_empty() {
chunk_group_state.push(ChunkGroupState {
requests: styles.len(),
styles,
});
idx += 1;
}
}
module_info_map.retain(|_, info| info.is_some());
module_info_map.sort_by(|_, a, _, b| {
let a = a.as_ref().unwrap();
let b = b.as_ref().unwrap();
a.index_sum
.cmp(&b.index_sum)
.then_with(|| a.ident.cmp(&b.ident))
});
// Compute the chunk item and size of each module
let chunk_item_and_sizes = module_info_map
.keys()
.map(async |&module| {
let chunk_item = attach_async_info_to_chunkable_module(
module,
async_module_info,
module_graph,
chunking_context,
)
.await?;
let size = *chunk_item
.chunk_type
.chunk_item_size(chunking_context, *chunk_item.chunk_item, None)
.await?;
Ok((chunk_item, size))
})
.try_join()
.await?;
module_info_map
.iter_mut()
.zip(chunk_item_and_sizes)
.for_each(|((_, info), (chunk_item, size))| {
let info = info.as_mut().unwrap();
info.size = size;
info.chunk_item = Some(chunk_item);
});
Ok(StyleCollection {
module_info_map,
chunk_group_state,
})
}
pub async fn compute_style_groups(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
config: &StyleGroupsConfig,
) -> Result<Vc<StyleGroups>> {
let StyleCollection {
module_info_map,
mut chunk_group_state,
} = collect_style_modules_per_chunk_group(module_graph, chunking_context).await?;
// Compute the dependents of each module
let mut module_dependents: FxHashMap<_, Vec<_>> = FxHashMap::default();
for (&module, info) in &module_info_map {
let info = info.as_ref().unwrap();
// Find the shortest chunk group as it's most efficient to iterate
let (&idx, &start_pos) = info
.chunk_group_indices
.iter()
.min_by_key(|&(&idx, _)| chunk_group_state[idx].styles.len())
.unwrap();
let potential_dependents = &chunk_group_state[idx].styles[start_pos + 1..];
let dependents = potential_dependents
.iter()
.copied()
.filter(|dependent| {
let dependent_info = module_info_map.get(dependent).unwrap();
let dependent_info = dependent_info.as_ref().unwrap();
// module is a dependency of dependent when it's included in all chunk groups of
// dependent with an index lower than the index of the dependent
info.chunk_group_indices.len() >= dependent_info.chunk_group_indices.len()
&& dependent_info
.chunk_group_indices
.iter()
.all(|(idx, &dependent_pos)| {
info.chunk_group_indices
.get(idx)
.is_some_and(|&module_pos| module_pos < dependent_pos)
})
})
.collect::<Vec<_>>();
if !dependents.is_empty() {
module_dependents.insert(module, dependents);
}
}
let mut ordered_modules_with_state = module_info_map
.keys()
.copied()
.map(|m| (m, false))
.collect::<FxIndexMap<_, _>>();
let mut shared_chunk_items = FxIndexMap::default();
for i in 0..ordered_modules_with_state.len() {
let (&module, processed) = ordered_modules_with_state.get_index_mut(i).unwrap();
if *processed {
continue;
}
*processed = true;
let info = module_info_map.get(&module).unwrap().as_ref().unwrap();
let mut global_mode = info.style_type == StyleType::GlobalStyle;
// The current position of processing in all selected chunk groups
let mut all_chunk_states = info.chunk_group_indices.clone();
// The list of modules and chunk items that go into the new chunk
let mut new_chunk_modules = [module].into_iter().collect::<FxHashSet<_>>();
let mut new_chunk_items = vec![info.chunk_item.unwrap()];
// The current size of the new chunk
let mut current_size = info.size;
// A pool of potential modules where the next module is selected from.
// It's filled from the next module of the selected modules in every chunk group.
let mut potential_next_modules = all_chunk_states
.iter()
.filter_map(|(&idx, pos)| {
let following_styles = &chunk_group_state[idx].styles[pos + 1..];
let i = following_styles
.iter()
.position(|m| !*ordered_modules_with_state.get(m).unwrap());
i.map(|i| following_styles[i])
})
.collect::<FxHashSet<_>>();
// Try to add modules to the chunk until a break condition is met
'outer: loop {
// We try to select a module that reduces request count and
// has the highest number of requests
let mut ordered_potential_next_modules = potential_next_modules
.iter()
.copied()
.map(|module| {
let info = module_info_map.get(&module).unwrap().as_ref().unwrap();
let requests = info
.chunk_group_indices
.keys()
.filter(|idx| all_chunk_states.contains_key(idx))
.map(|&idx| chunk_group_state[idx].requests)
.max()
.unwrap();
(module, info, requests)
})
.collect::<Vec<_>>();
ordered_potential_next_modules
.sort_by_key(|(_, info, requests)| (Reverse(*requests), &info.ident));
// Try every potential module
for (module, info, _) in ordered_potential_next_modules {
if current_size + info.size > config.max_chunk_size {
// Chunk would be too large
continue;
}
// In loose mode we only check if the dependencies are not violated
if let Some(dependents) = module_dependents.get(&module)
&& dependents.iter().any(|m| new_chunk_modules.contains(m))
{
// A dependent of the module is already in the chunk, which would violate
// the order
continue;
}
// Global CSS must not leak into unrelated chunks
let is_global = info.style_type == StyleType::GlobalStyle;
if is_global
&& global_mode
&& all_chunk_states.len() != info.chunk_group_indices.len()
{
// Fast check: chunk groups need to be identical
continue;
}
if global_mode
&& info
.chunk_group_indices
.keys()
.any(|idx| !all_chunk_states.contains_key(idx))
{
// Global CSS in new_chunk_items would leak into new chunk_group
continue;
}
if is_global
&& all_chunk_states
.keys()
.any(|idx| !info.chunk_group_indices.contains_key(idx))
{
// Global CSS would leak into existing chunk_group
continue;
}
potential_next_modules.remove(&module);
current_size += info.size;
if is_global {
global_mode = true;
}
for &idx in info.chunk_group_indices.keys() {
if all_chunk_states.contains_key(&idx) {
// This reduces the request count of the chunk group
chunk_group_state[idx].requests -= 1;
}
let pos = chunk_group_state[idx].styles.get_index_of(&module).unwrap();
all_chunk_states.insert(idx, pos);
let following_styles = &chunk_group_state[idx].styles[pos + 1..];
if let Some(i) = following_styles.iter().position(|m| {
!*ordered_modules_with_state.get(m).unwrap()
&& !new_chunk_modules.contains(m)
}) {
let module = following_styles[i];
potential_next_modules.insert(module);
}
}
new_chunk_items.push(info.chunk_item.unwrap());
new_chunk_modules.insert(module);
*ordered_modules_with_state.get_mut(&module).unwrap() = true;
continue 'outer;
}
break;
}
if new_chunk_items.len() > 1 {
let style_group = ChunkItemBatchWithAsyncModuleInfo::new(new_chunk_items.clone())
.to_resolved()
.await?;
for chunk_item in new_chunk_items {
shared_chunk_items.insert(
chunk_item,
StyleItemInfo {
order: None,
batch: Some(style_group),
},
);
}
}
}
Ok(StyleGroups { shared_chunk_items }.cell())
}
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