microReticulum icon indicating copy to clipboard operation
microReticulum copied to clipboard

[Bug] std::set eviction logic in packet hashlist deletes lowest numerical hashes instead of oldest packets

Open nilu96 opened this issue 5 months ago • 2 comments

Bug Description There is a critical logical bug in the capacity management of _packet_hashlist. The current implementation intended to enforce a maximum size limit by culling the oldest elements, but due to the underlying data structure, it is actually culling based on the byte-value of the hash.

Here is the problematic snippet:

// Cull the packet hashlist if it has reached its max size
if (_packet_hashlist.size() > _hashlist_maxsize) {
    std::set<Bytes>::iterator iter = _packet_hashlist.begin();
    std::advance(iter, _packet_hashlist.size() - _hashlist_maxsize);
    _packet_hashlist.erase(_packet_hashlist.begin(), iter);
}

Root Cause The code assumes that _packet_hashlist.begin() points to the oldest packets (First-In-First-Out behavior). However, _packet_hashlist is a std::set.
In C++, std::set is implemented as a self-balancing binary search tree (typically a Red-Black tree). It strictly orders its elements by value, not by insertion time. Because hashes are essentially random bytes, this code does not delete the oldest packets. Instead, it deletes the packets with the lowest numerical hash values.

Impact This means: A brand-new packet could be deleted immediately just because its hash starts with 0x00. An incredibly old packet might be kept in memory forever simply because its hash starts with 0xFF. This effectively breaks the deduplication window and creates unpredictable memory behavior under high network load.

Proposed Solution To fix this, we need a structure that supports both O(1) duplicate lookups and safe chronological eviction. I propose replacing this logic with a two-generation ring buffer (using two set instances). Instead of shifting elements or deleting per-packet, we rotate the active set into a previous set when the threshold is reached.

I have already implemented this two-generation ring buffer locally and tested it. I would be happy to submit a PR to fix this issue!

Cheers!

nilu96 avatar Jun 05 '26 20:06 nilu96

Hey @nilu96 , nice find! I implemented it the same way as a previous Python RNS version did, but it used a list and not a set so wasn't as problematic. I checked the current Python RNS and it uses a two sets as your suggested so I'll go with that and implement it as a re-usable STL-like container.

Cheers!

attermann avatar Jun 06 '26 00:06 attermann

Fixed in https://github.com/attermann/microReticulum/commit/ae5b2214dbfdcd8a9e04c137a85b9a6beadaeed9.

attermann avatar Jun 06 '26 01:06 attermann