Skip to content

Issue with uncacheModuleTree function - incorrect array iteration during splice #11524

@TurboRx

Description

@TurboRx

Problem

The uncacheModuleTree function in lib/utils.ts has a bug in its array iteration logic when splicing elements.

Current code:

for (const [i, child] of mod.children.entries()) {
    if (excludes.some(p => child.filename.includes(p))) continue;
    mod.children?.splice(i, 1);  // This modifies the array being iterated
    uncacheModuleTree(child, excludes);
}

Issue

When using splice() inside a forward iteration with entries(), removing an element shifts all subsequent elements to lower indices. This causes:

  • Elements to be skipped during iteration
  • Potential incorrect behavior when uncaching module trees

Example

Array: [A, B, C, D]
Iteration 0: Remove A → Array becomes [B, C, D], but iterator moves to index 1
Iteration 1: Now at index 1, but element at index 1 is now C (B was skipped)

Solution Options

  1. Iterate backwards (most common fix):

    for (let i = mod.children.length - 1; i >= 0; i--) {
        const child = mod.children[i];
        if (excludes.some(p => child.filename.includes(p))) continue;
        mod.children.splice(i, 1);
        uncacheModuleTree(child, excludes);
    }
  2. Collect indices and remove afterwards

  3. Filter the array instead of splicing during iteration

Impact

This bug could lead to incomplete module cache clearing, potentially causing stale module references in development environments.


Originally discovered during code quality review in PR #11522

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions