{"record":{"id":"cfa4e926e92e350c","repo":"databendlabs/databend","slug":"internal-error-entered-unreachable-code-cfa4e9","errorCode":null,"errorMessage":"internal error: entered unreachable code","messagePattern":"internal error: entered unreachable code","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/query/service/src/physical_plans/physical_sort.rs","lineNumber":421,"sourceCode":"                .iter()\n                .map(|v| v.index)\n                .collect::<Vec<_>>();\n\n            assert!(sort.after_exchange.is_none());\n\n            let input_plan = self.build(s_expr.unary_child(), required).await?;\n\n            return Ok(PhysicalPlan::new(WindowPartition {\n                meta: PhysicalPlanMeta::new(\"WindowPartition\"),\n                input: input_plan,\n                partition_by: window_partition.clone(),\n                order_by: order_by.clone(),\n                top_n: window.top.map(|top| WindowPartitionTopN {\n                    func: match window.func {\n                        WindowFuncType::RowNumber => WindowPartitionTopNFunc::RowNumber,\n                        WindowFuncType::Rank => WindowPartitionTopNFunc::Rank,\n                        WindowFuncType::DenseRank => WindowPartitionTopNFunc::DenseRank,\n                        _ => unreachable!(),\n                    },\n                    top,\n                }),\n                stat_info: Some(stat_info.clone()),\n            }));\n        };\n\n        // 2. Build physical plan.\n        let settings = self.ctx.get_settings();\n        let enable_fixed_rows = settings.get_enable_fixed_rows_sort()?;\n\n        let Some(after_exchange) = sort.after_exchange else {\n            let input_plan = self.build(s_expr.unary_child(), required).await?;\n            return Ok(PhysicalPlan::new(Sort {\n                input: input_plan,\n                order_by,\n                limit: sort.limit,\n                step: SortStep::Single,","sourceCodeStart":403,"sourceCodeEnd":439,"githubUrl":"https://github.com/databendlabs/databend/blob/288d84d76e20a2f8f7173bda9691eb6ece301aa9/src/query/service/src/physical_plans/physical_sort.rs#L403-L439","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Restructure the query to use ROW_NUMBER(), RANK(), or DENSE_RANK() for the partitioned TopN pattern","Upgrade Databend to a version where the optimizer only applies the WindowPartitionTopN rewrite to ranking functions","Check EXPLAIN output to see which window function triggered the rewrite; rewrite the query to avoid it in the partitioned-top-N position","Report the failing query to Databend — the rewrite guard should exclude non-ranking window functions"],"exampleFix":"// before\n_ => unreachable!(),\n// after\n_ => return Ok(None), // not a ranking function: skip WindowPartitionTopN rewrite","handlingStrategy":"validation","validationCode":"if !matches!(window.func, WindowFuncType::RowNumber | WindowFuncType::Rank | WindowFuncType::DenseRank) {\n    return Ok(None); // skip WindowPartitionTopN rewrite\n}","typeGuard":"fn is_ranking_func(f: &WindowFuncType) -> bool {\n    matches!(f, WindowFuncType::RowNumber | WindowFuncType::Rank | WindowFuncType::DenseRank)\n}","tryCatchPattern":"catch_unwind around physical planning; map panic to ErrorCode::Internal with the plan fragment","preventionTips":["Apply the WindowPartitionTopN rewrite only after checking the function is a ranking function","Add an exhaustive match test over WindowFuncType in the rewrite","Return Ok(None)/skip instead of panicking for non-ranking functions","Review new WindowFuncType additions for impact on the TopN rewrite"],"tags":["rust","panic","unreachable","window-function","top-n","optimizer"],"backgroundTag":"internal-invariant-violation","analyzedSha":"288d84d76e20a2f8f7173bda9691eb6ece301aa9","analyzedAt":"2026-09-11T11:29:36.208Z","contentChangedAt":"2026-09-11T11:29:36.208Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}