@@ -1131,27 +1131,31 @@ function accumulateInvertedNode(parent, stackFrame, leaf) {
11311131 return node ;
11321132}
11331133
1134- function traverseInvert ( path , currentNode , invertedRoot ) {
1135- if ( ! currentNode . children || currentNode . children . length === 0 ) {
1136- // We've reached a leaf node
1137- if ( ! path || path . length === 0 ) {
1138- return ;
1139- }
1134+ function processLeaf ( invertedRoot , path , leafNode ) {
1135+ if ( ! path || path . length === 0 ) {
1136+ return ;
1137+ }
11401138
1141- let invertedParent = accumulateInvertedNode ( invertedRoot , currentNode , currentNode ) ;
1139+ let invertedParent = accumulateInvertedNode ( invertedRoot , leafNode , leafNode ) ;
11421140
1143- // Walk backwards through the call stack
1144- for ( let i = path . length - 2 ; i >= 0 ; i -- ) {
1145- invertedParent = accumulateInvertedNode ( invertedParent , path [ i ] , currentNode ) ;
1146- }
1147- } else {
1148- // Not a leaf, continue traversing down the tree
1149- for ( const child of currentNode . children ) {
1150- traverseInvert ( path . concat ( [ child ] ) , child , invertedRoot ) ;
1151- }
1141+ // Walk backwards through the call stack
1142+ for ( let i = path . length - 2 ; i >= 0 ; i -- ) {
1143+ invertedParent = accumulateInvertedNode ( invertedParent , path [ i ] , leafNode ) ;
11521144 }
11531145}
11541146
1147+ function traverseInvert ( path , currentNode , invertedRoot ) {
1148+ const children = currentNode . children || [ ] ;
1149+ const childThreads = new Set ( children . flatMap ( c => c . threads || [ ] ) ) ;
1150+ const selfThreads = ( currentNode . threads || [ ] ) . filter ( t => ! childThreads . has ( t ) ) ;
1151+
1152+ if ( selfThreads . length > 0 ) {
1153+ processLeaf ( invertedRoot , path , { ...currentNode , threads : selfThreads } ) ;
1154+ }
1155+
1156+ children . forEach ( child => traverseInvert ( path . concat ( [ child ] ) , child , invertedRoot ) ) ;
1157+ }
1158+
11551159function convertInvertDictToArray ( node ) {
11561160 if ( node . threads instanceof Set ) {
11571161 node . threads = Array . from ( node . threads ) . sort ( ( a , b ) => a - b ) ;
@@ -1175,13 +1179,15 @@ function generateInvertedFlamegraph(data) {
11751179 threads : data . threads
11761180 } ;
11771181
1178- data . children ?. forEach ( child => {
1179- traverseInvert ( [ child ] , child , invertedRoot ) ;
1180- } ) ;
1182+ const children = data . children || [ ] ;
1183+ if ( children . length === 0 ) {
1184+ // Single-frame tree: the root is its own leaf
1185+ processLeaf ( invertedRoot , [ data ] , data ) ;
1186+ } else {
1187+ children . forEach ( child => traverseInvert ( [ child ] , child , invertedRoot ) ) ;
1188+ }
11811189
1182- // Convert children dictionaries to arrays for rendering
11831190 convertInvertDictToArray ( invertedRoot ) ;
1184-
11851191 return invertedRoot ;
11861192}
11871193
0 commit comments