@@ -656,25 +656,24 @@ async def _energy_log_records_load_from_cache(self) -> bool:
656656 return False
657657
658658 collected_logs = _collect_records (cache_data )
659- # Sort and prune the records loaded from cache
660- sorted_logs : dict [ int , dict [ int , tuple [ datetime , int ]]] = {}
659+
660+ # Cutoff timestamp for filtering
661661 skip_before = datetime .now (tz = UTC ) - timedelta (hours = MAX_LOG_HOURS )
662- sorted_addresses = sorted (collected_logs .keys (), reverse = True )
663- for address in sorted_addresses :
664- sorted_slots = sorted (collected_logs [address ].keys (), reverse = True )
665- for slot in sorted_slots :
666- if collected_logs [address ][slot ][0 ] > skip_before :
667- if sorted_logs .get (address ) is None :
668- sorted_logs [address ] = {}
669- sorted_logs [address ][slot ] = collected_logs [address ][slot ]
670-
671- for address , data in sorted_logs .items ():
672- for slot , pulse_data in data .items ():
662+
663+ # Iterate in reverse sorted order directly
664+ for address in sorted (collected_logs , reverse = True ):
665+ slots = collected_logs [address ]
666+ filtered_slots = {
667+ slot : data
668+ for slot , data in sorted (slots .items (), reverse = True )
669+ if data [0 ] > skip_before
670+ }
671+ for slot , (timestamp , pulses ) in filtered_slots .items ():
673672 self ._energy_counters .add_pulse_log (
674673 address = address ,
675674 slot = slot ,
676- pulses = pulse_data [ 1 ] ,
677- timestamp = pulse_data [ 0 ] ,
675+ pulses = pulses ,
676+ timestamp = timestamp ,
678677 import_only = True ,
679678 )
680679
0 commit comments