astral-sh/ruff · error

Ranges must be inserted in sorted order

Error message

Ranges must be inserted in sorted order

What it means

Panics in push_mapping when a new TextRange is inserted before the last range already in the list. The mapping structure requires strictly sorted, non-overlapping ranges; an out-of-order push means an upstream caller violated that contract, not bad user input.

Source

Thrown at crates/ruff_linter/src/noqa.rs:1352

            }
        });

        if let Ok(index) = index {
            self.ranges[index].end()
        } else {
            offset
        }
    }

    pub(crate) fn push_mapping(&mut self, range: TextRange) {
        if let Some(last_range) = self.ranges.last_mut() {
            // Strictly sorted insertion
            if last_range.end() < range.start() {
                // OK
            } else if range.end() < last_range.start() {
                // Incoming range is strictly before the last range which violates
                // the function's contract.
                panic!("Ranges must be inserted in sorted order")
            } else {
                // Here, it's guaranteed that `last_range` and `range` overlap
                // in some way. We want to merge them into a single range.
                *last_range = last_range.cover(range);
                return;
            }
        }

        self.ranges.push(range);
    }
}

impl FromIterator<TextRange> for NoqaMapping {
    fn from_iter<T: IntoIterator<Item = TextRange>>(iter: T) -> Self {
        let mut mappings = NoqaMapping::default();

        for range in iter {
            mappings.push_mapping(range);

View on GitHub (pinned to 26f38c119c)

Solutions

  1. Ensure callers of push_mapping emit ranges in ascending start order
  2. Add a debug assertion or sort merge at the call site before pushing
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at crates/ruff_linter/src/noqa.rs:1352 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of astral-sh/ruff@26f38c119c (2026-09-05). Data as JSON: /api/errors/7398fc79577f009a. Report an issue: GitHub.