databendlabs/databend · error

internal error: entered unreachable code

Error message

internal error: entered unreachable code

What it means

A `unreachable!()` in physical_sort.rs when converting a window function type to a `WindowPartitionTopNFunc`. Only RowNumber, Rank, and DenseRank are valid for partition-top-N optimization; any other WindowFuncType (e.g., sum, lag, lead) reaching this conversion panics. The optimizer assumes it only builds WindowPartitionTopN for ranking functions.

Solutions

  1. Restructure the query to use ROW_NUMBER(), RANK(), or DENSE_RANK() for the partitioned TopN pattern
  2. Upgrade Databend to a version where the optimizer only applies the WindowPartitionTopN rewrite to ranking functions
  3. Check EXPLAIN output to see which window function triggered the rewrite; rewrite the query to avoid it in the partitioned-top-N position
  4. Report the failing query to Databend — the rewrite guard should exclude non-ranking window functions

Example fix

// before
_ => unreachable!(),
// after
_ => return Ok(None), // not a ranking function: skip WindowPartitionTopN rewrite
Defensive patterns

Strategy: validation

Validate before calling

if !matches!(window.func, WindowFuncType::RowNumber | WindowFuncType::Rank | WindowFuncType::DenseRank) {
    return Ok(None); // skip WindowPartitionTopN rewrite
}

Type guard

fn is_ranking_func(f: &WindowFuncType) -> bool {
    matches!(f, WindowFuncType::RowNumber | WindowFuncType::Rank | WindowFuncType::DenseRank)
}

Try / catch

catch_unwind around physical planning; map panic to ErrorCode::Internal with the plan fragment

Prevention

When it happens

Trigger: Physical planning of a WindowPartitionTopN (partitioned TopN via window functions) where `window.func` is a non-ranking window function such as WindowFuncType::Aggregate, LagLead, or Ntile.

Common situations: Queries combining ORDER BY/LIMIT per partition with window functions other than row_number/rank/dense_rank; optimizer rewrites that incorrectly classify a window operator as partition-top-N eligible.

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


AI-assisted analysis of databendlabs/databend@288d84d76e (2026-09-11). Data as JSON: /api/errors/cfa4e926e92e350c. Report an issue: GitHub.

Appendix: source

Thrown at src/query/service/src/physical_plans/physical_sort.rs:421

                .iter()
                .map(|v| v.index)
                .collect::<Vec<_>>();

            assert!(sort.after_exchange.is_none());

            let input_plan = self.build(s_expr.unary_child(), required).await?;

            return Ok(PhysicalPlan::new(WindowPartition {
                meta: PhysicalPlanMeta::new("WindowPartition"),
                input: input_plan,
                partition_by: window_partition.clone(),
                order_by: order_by.clone(),
                top_n: window.top.map(|top| WindowPartitionTopN {
                    func: match window.func {
                        WindowFuncType::RowNumber => WindowPartitionTopNFunc::RowNumber,
                        WindowFuncType::Rank => WindowPartitionTopNFunc::Rank,
                        WindowFuncType::DenseRank => WindowPartitionTopNFunc::DenseRank,
                        _ => unreachable!(),
                    },
                    top,
                }),
                stat_info: Some(stat_info.clone()),
            }));
        };

        // 2. Build physical plan.
        let settings = self.ctx.get_settings();
        let enable_fixed_rows = settings.get_enable_fixed_rows_sort()?;

        let Some(after_exchange) = sort.after_exchange else {
            let input_plan = self.build(s_expr.unary_child(), required).await?;
            return Ok(PhysicalPlan::new(Sort {
                input: input_plan,
                order_by,
                limit: sort.limit,
                step: SortStep::Single,

View on GitHub (pinned to 288d84d76e)