rspack_plugin_split_chunks 0.103.2

rspack split chunks plugin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
use std::{cmp::Ordering, fmt};

use derive_more::Debug;
use rspack_collections::{IdentifierMap, IdentifierSet};
use rspack_core::{ChunkUkey, ModuleIdentifier, SourceType};
use rustc_hash::FxHashSet;
use smallvec::SmallVec;

use crate::{
  CacheGroup,
  common::{ModuleChunkMap, ModuleSizes, SplitChunkSizes, chunk_mask},
};

pub(crate) struct IndexedCacheGroup<'a> {
  pub cache_group_index: u32,
  pub cache_group: &'a CacheGroup,
}

impl<'a> IndexedCacheGroup<'a> {
  pub fn compare_by_priority(&self, other: &Self) -> Ordering {
    self
      .cache_group
      .priority
      .partial_cmp(&other.cache_group.priority)
      .unwrap_or(Ordering::Equal)
  }

  pub fn compare_by_index(&self, other: &Self) -> Ordering {
    self.cache_group_index.cmp(&other.cache_group_index)
  }
}

#[derive(Debug)]
enum ModulesForCompare {
  Unsorted(Vec<ModuleIdentifier>),
  Sorted(Vec<ModuleIdentifier>),
}

impl Default for ModulesForCompare {
  fn default() -> Self {
    Self::Unsorted(Default::default())
  }
}

impl ModulesForCompare {
  fn as_slice(&self) -> &[ModuleIdentifier] {
    match self {
      Self::Unsorted(modules) | Self::Sorted(modules) => modules,
    }
  }

  fn prepare(&mut self, modules: Vec<ModuleIdentifier>) {
    if modules.is_empty() {
      return;
    }

    if matches!(self, Self::Unsorted(modules_for_compare) if modules_for_compare.is_empty()) {
      *self = Self::Unsorted(modules);
    }
  }

  fn sorted(&mut self) -> &[ModuleIdentifier] {
    if let Self::Unsorted(modules) = self {
      modules.sort_unstable_by_key(|module| module.precomputed_hash());
      *self = Self::Sorted(std::mem::take(modules));
    }

    let Self::Sorted(modules) = self else {
      unreachable!("modules for compare should be sorted");
    };
    modules
  }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) enum ModuleGroupKey {
  Named {
    cache_group_index: u32,
    chunk_name: String,
  },
  Anonymous {
    cache_group_index: u32,
    chunks_key: u64,
  },
}

impl fmt::Display for ModuleGroupKey {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Named {
        cache_group_index,
        chunk_name,
      } => write!(
        f,
        "named(cache_group_index={cache_group_index}, chunk_name={chunk_name})"
      ),
      Self::Anonymous {
        cache_group_index,
        chunks_key,
      } => write!(
        f,
        "anonymous(cache_group_index={cache_group_index}, chunks_key={chunks_key:x})"
      ),
    }
  }
}

/// `ModuleGroup` is a abstraction of middle step for splitting chunks.
///
/// `ModuleGroup` captures/contains a bunch of modules due to the `optimization.splitChunks` configuration.
///
/// `ModuleGroup` would be transform into `Chunk`s in the end.
///
///  A `ModuleGroup` would be transform into multiple `Chunk`s if the `name` dynamic computed
///
/// The original name of `ModuleGroup` is `ChunkInfoItem` borrowed from Webpack
#[derive(Debug)]
enum ModuleGroupChunks {
  /// Anonymous groups are keyed by their exact chunk combination. `None` means the selected chunks
  /// are still identical to `ModuleGroup::chunks`; a snapshot is created only if that union is
  /// later mutated while choosing a reused destination.
  Shared(Option<FxHashSet<ChunkUkey>>),
  /// A named group can merge modules selected from different chunk combinations.
  ByModule(IdentifierMap<FxHashSet<ChunkUkey>>),
}

pub(crate) enum CandidateUpdate {
  Unchanged,
  Updated,
  Discard,
}

#[derive(Debug)]
pub(crate) struct ModuleGroup {
  pub modules: IdentifierSet,
  /// Packed `selectable` / `placement_changed` / stale size reduction flags. A
  /// single byte keeps `ModuleGroup` within the padding next to the other small
  /// fields, so the struct (moved by sorts and `swap_remove`) does not grow.
  candidate_flags: u8,
  /// The chunks selected for each module. Anonymous groups structurally share their exact chunk
  /// combination instead of allocating one set per module.
  #[debug(skip)]
  module_chunks: ModuleGroupChunks,
  /// the real index used for mapping the ModuleGroup to corresponding CacheGroup
  pub cache_group_index: u32,
  pub cache_group_reuse_existing_chunk: bool,
  /// If the `ModuleGroup` is going to create a chunk, which will be named using `chunk_name`
  /// A module
  pub chunk_name: Option<String>,

  /// `Chunk`s which `Module`s in this ModuleGroup belong to
  #[debug(skip)]
  pub chunks: FxHashSet<ChunkUkey>,
  /// A conservative snapshot of the group's chunks before selection starts. Later operations only
  /// remove chunks, so retaining the original bits can add false positives but never false
  /// negatives to cleanup filtering.
  chunk_mask: u64,
  modules_for_compare: ModulesForCompare,
  pending_initial_sizes: bool,
  has_modules_without_source_types: bool,
  removed: Vec<ModuleIdentifier>,
  sizes: SplitChunkSizes,
  size_reduction: f64,
}

// Most consecutive module sizes have the same source type. Keep that running
// total in a local value instead of hashing the type for every module. Flush on
// type changes so insertion order and each floating-point operation stay intact.
struct SizeAccumulator<'a> {
  sizes: &'a mut SplitChunkSizes,
  cached: Option<(SourceType, f64)>,
}

impl SizeAccumulator<'_> {
  fn get(&mut self, ty: SourceType) -> &mut f64 {
    if self
      .cached
      .as_ref()
      .is_some_and(|(cached, _)| *cached != ty)
    {
      let (ty, size) = self.cached.take().expect("cached source type");
      self.sizes.insert(ty, size);
    }
    &mut self
      .cached
      .get_or_insert_with(|| (ty, *self.sizes.entry(ty).or_default()))
      .1
  }

  fn finish(self) {
    if let Some((ty, size)) = self.cached {
      self.sizes.insert(ty, size);
    }
  }
}

impl ModuleGroup {
  const SELECTABLE: u8 = 1 << 0;
  const PLACEMENT_CHANGED: u8 = 1 << 1;
  const SIZE_REDUCTION_STALE: u8 = 1 << 2;

  /// Only threshold-invalid candidates are skipped by selection. Cleanup can
  /// make them selectable again within this priority's existing queue.
  #[inline]
  pub fn selectable(&self) -> bool {
    self.candidate_flags & Self::SELECTABLE != 0
  }

  #[inline]
  pub fn set_selectable(&mut self, selectable: bool) {
    if selectable {
      self.candidate_flags |= Self::SELECTABLE;
    } else {
      self.candidate_flags &= !Self::SELECTABLE;
    }
  }

  #[inline]
  pub fn placement_changed(&self) -> bool {
    self.candidate_flags & Self::PLACEMENT_CHANGED != 0
  }

  #[inline]
  pub fn mark_placement_changed(&mut self) {
    self.candidate_flags |= Self::PLACEMENT_CHANGED;
  }

  #[inline]
  fn mark_size_reduction_stale(&mut self) {
    self.candidate_flags |= Self::SIZE_REDUCTION_STALE;
  }

  pub fn new(chunk_name: Option<String>, cache_group_index: u32, cache_group: &CacheGroup) -> Self {
    let module_chunks = if chunk_name.is_some() {
      ModuleGroupChunks::ByModule(Default::default())
    } else {
      ModuleGroupChunks::Shared(None)
    };
    Self {
      modules: Default::default(),
      candidate_flags: Self::SELECTABLE,
      module_chunks,
      cache_group_index,
      cache_group_reuse_existing_chunk: cache_group.reuse_existing_chunk,
      sizes: Default::default(),
      chunks: Default::default(),
      chunk_mask: 0,
      modules_for_compare: Default::default(),
      chunk_name,
      pending_initial_sizes: false,
      has_modules_without_source_types: false,
      removed: Default::default(),
      size_reduction: 0.0,
    }
  }

  pub fn get_source_types_modules(
    &self,
    ty: &[SourceType],
    module_sizes: &ModuleSizes,
  ) -> IdentifierSet {
    // Most candidates never violate a source-type threshold. Materialize this
    // filtered membership only when needed instead of duplicating every
    // candidate's module set while calculating its size.
    self
      .modules
      .iter()
      .filter_map(|module| {
        let sizes = module_sizes.get(module).expect("should have module size");
        if ty.iter().any(|ty| sizes.contains_key(ty)) {
          Some(*module)
        } else {
          None
        }
      })
      .collect()
  }

  pub fn has_only_source_types(&self, source_types: &[SourceType]) -> bool {
    debug_assert!(!self.pending_initial_sizes);
    // Size keys are never removed. They conservatively cover every remaining
    // module, including after partial removals, without rescanning the modules.
    !self.has_modules_without_source_types && self.sizes.keys().all(|ty| source_types.contains(ty))
  }

  pub fn add_module(
    &mut self,
    module: ModuleIdentifier,
    chunks: impl IntoIterator<Item = ChunkUkey>,
  ) {
    self.modules.insert(module);
    let ModuleGroupChunks::ByModule(module_chunks) = &mut self.module_chunks else {
      unreachable!("add_module should only be used for named module groups");
    };
    let module_chunks = module_chunks.entry(module).or_default();
    for chunk in chunks {
      module_chunks.insert(chunk);
      self.chunks.insert(chunk);
    }
    self.mark_size_reduction_stale();
  }

  pub fn add_module_with_shared_chunks(
    &mut self,
    module: ModuleIdentifier,
    chunks: impl IntoIterator<Item = ChunkUkey>,
  ) {
    self.modules.insert(module);
    let ModuleGroupChunks::Shared(shared_chunks) = &mut self.module_chunks else {
      unreachable!("shared chunks should only be used for anonymous module groups");
    };
    if self.chunks.is_empty() {
      debug_assert!(shared_chunks.is_none());
      self.chunks.extend(chunks);
    }
  }

  pub fn remove_group_chunk(&mut self, chunk: &ChunkUkey) {
    if let ModuleGroupChunks::Shared(shared_chunks) = &mut self.module_chunks
      && shared_chunks.is_none()
    {
      *shared_chunks = Some(self.chunks.clone());
    }
    self.chunks.remove(chunk);
  }

  pub fn get_module_chunks(&self, module: &ModuleIdentifier) -> Option<&FxHashSet<ChunkUkey>> {
    if !self.modules.contains(module) {
      return None;
    }
    match &self.module_chunks {
      ModuleGroupChunks::Shared(Some(chunks)) => Some(chunks),
      ModuleGroupChunks::Shared(None) => Some(&self.chunks),
      ModuleGroupChunks::ByModule(module_chunks) => module_chunks.get(module),
    }
  }

  pub fn uses_shared_module_chunks(&self) -> bool {
    matches!(self.module_chunks, ModuleGroupChunks::Shared(_))
  }

  pub fn shared_module_chunks(&self) -> Option<&FxHashSet<ChunkUkey>> {
    match &self.module_chunks {
      ModuleGroupChunks::Shared(Some(chunks)) => Some(chunks),
      ModuleGroupChunks::Shared(None) => Some(&self.chunks),
      ModuleGroupChunks::ByModule(_) => None,
    }
  }

  pub fn remove_module(&mut self, module: ModuleIdentifier) {
    self.remove_modules([module]);
  }

  pub fn remove_modules(&mut self, modules: impl IntoIterator<Item = ModuleIdentifier>) {
    match &mut self.module_chunks {
      ModuleGroupChunks::Shared(_) => {
        for module in modules {
          if self.modules.remove(&module) {
            self.removed.push(module);
          }
        }
      }
      ModuleGroupChunks::ByModule(module_chunks) => {
        for module in modules {
          if self.modules.remove(&module) {
            module_chunks.remove(&module);
            self.removed.push(module);
            self.candidate_flags |= Self::SIZE_REDUCTION_STALE;
          }
        }
      }
    }
  }

  pub fn remove_shared_modules(&mut self, modules: &IdentifierSet) {
    debug_assert!(self.uses_shared_module_chunks());
    if self.modules.len() > modules.len() {
      // The original intersection walks `modules` in this case. Remove while
      // walking the same set to avoid probing the group twice per match.
      self.remove_modules(modules.iter().copied());
    } else {
      // Preserve the smaller group's iteration order, erasing known buckets
      // directly instead of hashing each matching module a second time.
      self.modules.retain(|module| {
        if modules.contains(module) {
          self.removed.push(*module);
          false
        } else {
          true
        }
      });
    }
  }

  /// Shrinking can only reduce a source type's size/reduction. Keep mixed-type
  /// candidates only if removing another type could leave an eligible one.
  pub fn can_recover(&mut self, cache: &CacheGroup, sizes: &ModuleSizes, chunks: usize) -> bool {
    chunks >= (cache.min_chunks as usize).max(1)
      && Self::has_recoverable_size(self.get_sizes(sizes), cache, chunks)
  }

  fn has_recoverable_size(sizes: &SplitChunkSizes, cache: &CacheGroup, chunks: usize) -> bool {
    sizes.iter().any(|(ty, size)| {
      *size > 0.0
        && *size >= cache.min_size.get(ty).copied().unwrap_or_default()
        && *size * chunks as f64
          >= cache
            .min_size_reduction
            .get(ty)
            .copied()
            .unwrap_or_default()
    })
  }

  /// Choose which dimension to delete without materializing either alternative.
  /// The caller has found an overlap; preserve each source type's subtraction order.
  fn prefer_module_removal(
    &self,
    affected: impl Iterator<Item = ModuleIdentifier>,
    remaining_chunks: usize,
    cache: &CacheGroup,
    module_sizes: &ModuleSizes,
  ) -> bool {
    let mut remaining_sizes: SmallVec<[(SourceType, f64); 2]> =
      self.sizes.iter().map(|(ty, size)| (*ty, *size)).collect();
    for module in affected {
      let sizes = &module_sizes[&module];
      for (ty, remaining) in &mut remaining_sizes {
        *remaining = (*remaining - sizes.get(ty).copied().unwrap_or_default()).max(0.0);
      }
    }
    let reduction = |ty, size: f64, chunks: usize| {
      if size >= cache.min_size.get(ty).copied().unwrap_or_default()
        && size * chunks as f64
          >= cache
            .min_size_reduction
            .get(ty)
            .copied()
            .unwrap_or_default()
      {
        size * chunks.saturating_sub(1) as f64
      } else {
        0.0
      }
    };
    let mut keep_chunks = 0.0;
    let mut keep_modules = 0.0;
    for ((ty, size), (_, remaining)) in self.sizes.iter().zip(remaining_sizes) {
      keep_chunks += reduction(ty, remaining, self.chunks.len());
      keep_modules += reduction(ty, *size, remaining_chunks);
    }
    keep_chunks > keep_modules
  }

  /// Subtract committed placements from this candidate in the existing cleanup
  /// traversal. Keep one remaining rectangle; never fork or rebuild a candidate.
  pub fn update_candidate(
    &mut self,
    placed: &ModuleChunkMap,
    cache: &CacheGroup,
    module_sizes: &ModuleSizes,
    scratch: &mut Vec<ModuleIdentifier>,
  ) -> CandidateUpdate {
    let minimum = (cache.min_chunks as usize).max(1);
    if let ModuleGroupChunks::ByModule(sources) = &mut self.module_chunks {
      let mut changed = false;
      sources.retain(|module, chunks| {
        let Some(removed) = placed.get(module) else {
          return true;
        };
        let before = chunks.len();
        chunks.retain(|chunk| !removed.contains(chunk));
        changed |= chunks.len() != before;
        if chunks.len() < minimum {
          self.modules.remove(module);
          self.removed.push(*module);
          self.candidate_flags |= Self::SIZE_REDUCTION_STALE;
          false
        } else {
          true
        }
      });
      if !changed {
        return CandidateUpdate::Unchanged;
      }
      if self.modules.is_empty() {
        return CandidateUpdate::Discard;
      }
      // A changed named group must not introduce consumers of a module that
      // was already extracted elsewhere. Narrow its existing support in place.
      let before = self.chunks.len();
      self
        .chunks
        .retain(|chunk| sources.values().all(|chunks| chunks.contains(chunk)));
      for chunks in sources.values_mut() {
        chunks.retain(|chunk| self.chunks.contains(chunk));
      }
      self.mark_size_reduction_stale();
      self.mark_placement_changed();
      if self.chunks.len() != before {
        self.chunk_mask = chunk_mask(self.chunks.iter());
      }
      return CandidateUpdate::Updated;
    }
    let mut changed = false;
    let mut chunks_changed = false;
    match placed {
      ModuleChunkMap::Shared { modules, chunks } => {
        let shrink_chunks = if self.chunks.len() <= minimum {
          // Any overlap invalidates the chunk remainder. Keep the original
          // first-hit check and module-deletion path without counting chunks.
          if self.chunks.is_disjoint(chunks) {
            return CandidateUpdate::Unchanged;
          }
          if self.modules.is_subset(modules) {
            return CandidateUpdate::Discard;
          }
          false
        } else {
          // Finish deferred size bookkeeping before borrowing both iterators.
          self.get_sizes(module_sizes);
          let mut overlap = self.chunks.intersection(chunks);
          if overlap.next().is_none() {
            return CandidateUpdate::Unchanged;
          }
          let mut affected = self.modules.intersection(modules).copied();
          let Some(first) = affected.next() else {
            return CandidateUpdate::Unchanged;
          };
          // Count only candidates that share a module. Both first-hit checks
          // continue their existing iterators instead of starting another scan.
          let remaining = self.chunks.len() - 1 - overlap.count();
          if remaining >= minimum && Self::has_recoverable_size(&self.sizes, cache, remaining) {
            !self.prefer_module_removal(
              std::iter::once(first).chain(affected),
              remaining,
              cache,
              module_sizes,
            )
          } else {
            if self.modules.is_subset(modules) {
              return CandidateUpdate::Discard;
            }
            false
          }
        };
        if shrink_chunks {
          self.chunks.retain(|chunk| !chunks.contains(chunk));
          self.mark_placement_changed();
          changed = true;
          chunks_changed = true;
        } else {
          // The original module deletion is the viable or more beneficial update.
          let before = self.modules.len();
          self.remove_shared_modules(modules);
          changed = self.modules.len() != before;
        }
      }
      ModuleChunkMap::ByModule(placed) => {
        scratch.extend(
          placed
            .keys()
            .filter(|module| self.modules.contains(module))
            .copied(),
        );
        scratch.sort_unstable_by_key(|module| (module.precomputed_hash(), *module));
        for module in scratch.iter().copied() {
          let removed = &placed[&module];
          let overlap = self.chunks.intersection(removed).count();
          if overlap == 0 {
            continue;
          }
          changed = true;
          let remaining = self.chunks.len() - overlap;
          if self.can_recover(cache, module_sizes, remaining)
            && !self.prefer_module_removal(std::iter::once(module), remaining, cache, module_sizes)
          {
            self.chunks.retain(|chunk| !removed.contains(chunk));
            self.mark_placement_changed();
            chunks_changed = true;
          } else {
            self.remove_module(module);
          }
        }
      }
    }
    if changed {
      if self.modules.is_empty() {
        return CandidateUpdate::Discard;
      }
      // Pending candidates have not selected a reused destination, so their
      // shared per-module support is exactly the updated candidate support.
      self.module_chunks = ModuleGroupChunks::Shared(None);
      if chunks_changed {
        self.chunk_mask = chunk_mask(self.chunks.iter());
      }
      CandidateUpdate::Updated
    } else {
      CandidateUpdate::Unchanged
    }
  }

  pub fn rebuild_chunks(&mut self) {
    let ModuleGroupChunks::ByModule(module_chunks) = &self.module_chunks else {
      return;
    };
    self.chunks.clear();
    self
      .chunks
      .extend(module_chunks.values().flatten().copied());
  }

  pub fn prepare_modules_for_sizes_and_compare(&mut self) {
    self.chunk_mask = chunk_mask(self.chunks.iter());
    let modules = self.modules.iter().copied().collect::<Vec<_>>();
    self.pending_initial_sizes = !modules.is_empty();
    self.modules_for_compare.prepare(modules);
  }

  pub fn sorted_modules_for_compare(&mut self) -> &[ModuleIdentifier] {
    self.modules_for_compare.sorted()
  }

  pub fn may_have_chunks_in_mask(&self, mask: u64) -> bool {
    self.chunk_mask & mask != 0
  }

  pub fn get_cache_group<'a>(&self, cache_groups: &'a [CacheGroup]) -> &'a CacheGroup {
    &cache_groups[self.cache_group_index as usize]
  }

  pub fn get_size_reduction(&mut self, module_sizes: &ModuleSizes) -> f64 {
    let ModuleGroupChunks::ByModule(module_chunks) = &self.module_chunks else {
      if self.pending_initial_sizes || !self.removed.is_empty() {
        unreachable!("should update sizes before get size reduction");
      }
      return self.size_reduction * self.chunks.len().saturating_sub(1) as f64;
    };
    if self.candidate_flags & Self::SIZE_REDUCTION_STALE != 0 {
      self.size_reduction =
        get_named_group_size_reduction(&self.modules, module_chunks, module_sizes);
      self.candidate_flags &= !Self::SIZE_REDUCTION_STALE;
    } else {
      // Every mutation of a named group's modules or selected chunks must mark the cache stale.
      debug_assert_eq!(
        self.size_reduction,
        get_named_group_size_reduction(&self.modules, module_chunks, module_sizes),
        "named size reduction cache is stale; a mutation path forgot to invalidate it",
      );
    }
    self.size_reduction
  }

  pub fn get_sizes(&mut self, module_sizes: &ModuleSizes) -> &SplitChunkSizes {
    if !self.pending_initial_sizes && self.removed.is_empty() {
      return &self.sizes;
    }
    let mut sizes = SizeAccumulator {
      sizes: &mut self.sizes,
      cached: None,
    };
    let mut total_size = self.size_reduction;
    if self.pending_initial_sizes {
      // The comparison snapshot is captured before any module is removed and
      // before the first size comparison. It also supplies the initial size
      // accumulation in the original iteration order without a second copy.
      for module in self.modules_for_compare.as_slice() {
        let module_sizes = module_sizes.get(module).expect("should have module size");
        self.has_modules_without_source_types |= module_sizes.is_empty();
        for (ty, s) in module_sizes.iter() {
          let size = sizes.get(*ty);
          *size += s;
          total_size += s;
        }
      }
      self.pending_initial_sizes = false;
    }
    if !self.removed.is_empty() {
      for module in self.removed.drain(..) {
        let module_sizes = module_sizes.get(&module).expect("should have module size");
        for (ty, s) in module_sizes.iter() {
          let size = sizes.get(*ty);
          *size -= s;
          *size = size.max(0.0);
          total_size -= s;
        }
      }
    }

    sizes.finish();
    // A named group keeps its own size reduction in the slot instead.
    if self.uses_shared_module_chunks() {
      self.size_reduction = total_size;
    }
    &self.sizes
  }
}

/// Each module of a named group saves its size once for every selected chunk beyond the first.
fn get_named_group_size_reduction(
  modules: &IdentifierSet,
  module_chunks: &IdentifierMap<FxHashSet<ChunkUkey>>,
  module_sizes: &ModuleSizes,
) -> f64 {
  modules
    .iter()
    .map(|module| {
      let chunks = module_chunks
        .get(module)
        .expect("should have selected module chunks");
      let size: f64 = module_sizes
        .get(module)
        .expect("should have module size")
        .values()
        .sum();
      size * chunks.len().saturating_sub(1) as f64
    })
    .sum()
}

pub(crate) fn compare_entries(
  (a_key, a): (&ModuleGroupKey, &mut ModuleGroup),
  (b_key, b): (&ModuleGroupKey, &mut ModuleGroup),
  module_sizes: &ModuleSizes,
) -> f64 {
  // 1. by priority
  // no need to compare priority anymore because we already pick all cache groups with same priority
  // let diff_priority = a.cache_group_priority - b.cache_group_priority;
  // if diff_priority != 0f64 {
  //   return diff_priority;
  // }
  // 2. by number of chunks
  let a_chunks_len = a.chunks.len();
  let b_chunks_len = b.chunks.len();
  let diff_count = a_chunks_len as f64 - b_chunks_len as f64;
  if diff_count != 0f64 {
    return diff_count;
  }

  // 3. by size reduction
  let a_size_reduce = a.get_size_reduction(module_sizes);
  let b_size_reduce = b.get_size_reduction(module_sizes);
  let diff_size_reduce = a_size_reduce - b_size_reduce;
  if diff_size_reduce != 0f64 {
    return diff_size_reduce;
  }

  // 4. by cache group index
  let index_diff = b.cache_group_index as f64 - a.cache_group_index as f64;
  if index_diff != 0f64 {
    return index_diff;
  }

  // 5. by number of modules (to be able to compare by identifier)
  let modules_a_len = a.modules.len();
  let modules_b_len = b.modules.len();
  let diff = modules_a_len as f64 - modules_b_len as f64;
  if diff != 0f64 {
    return diff;
  }

  let mut modules_a = a.sorted_modules_for_compare().iter();
  let mut modules_b = b.sorted_modules_for_compare().iter();

  loop {
    match (modules_a.next(), modules_b.next()) {
      (None, None) => break,
      (Some(a), Some(b)) => {
        let res = a.cmp(b);
        if !res.is_eq() {
          return res as i32 as f64;
        }
      }
      (None, Some(_)) => return -1.0,
      (Some(_), None) => return 1.0,
    }
  }

  match a_key.cmp(b_key) {
    Ordering::Less => -1.0,
    Ordering::Equal => 0.0,
    Ordering::Greater => 1.0,
  }
}