Build a Bloom Filter using Murmur3 and FNV-1a hash functions. Implement a counting Bloom filter variant using 4-bit counters instead of single bits to allow element deletion with a small probability of false negatives.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question about building a Bloom Filter with some advanced features. Let me break down what's needed:
A standard Bloom Filter using two hash functions (Murmur3 and FNV-1a)
A Counting Bloom Filter variant with 4-bit counters (allowing deletions)
Handle false negatives properly in the counting variant
Let me implement this comprehensively:
python
import struct
from abc import ABC, abstractmethod
from typing import Any, Set, Tuple
import hashlib
# First, let's implement both hash functions
class HashFunction:
"""Base class for hash functions"""
@abstractmethod
def hash(self, data: bytes, seed: int = 0) -> int:
pass
class FNV1aHash(HashFunction):
"""FNV-1a hash function"""
FNV_32_PRIME = 0x01000193
FNV1_32A_INIT = 0x811c9dc5
def hash(self, data: bytes, seed: int = 0) -> int:
hash_value = self.FNV1_32A_INIT ^ seed
for byte in data:
hash_value ^= byte
hash_value = (hash_value * self.FNV_32_PRIME) & 0xffffffff
return hash_value
class Murmur3Hash(HashFunction):
"""
Murmur3 hash function (simplified 32-bit implementation)
"""
def hash(self, data: bytes, seed: int = 0) -> int:
length = len(data)
h1 = seed
c1 = 0xcc9e2d51
c2 = 0x1b873593
# Process 4-byte chunks
nblocks = length // 4
for i in range(nblocks):
k1 = struct.unpack('<I', data[i*4:(i+1)*4])[0]
k1 = (k1 * c1) & 0xffffffff
k1 = ((k1 << 15) | (k1 >> 17)) & 0xffffffff
k1 = (k1 * c2) & 0xffffffff
h1 ^= k1
h1 = ((h1 << 13) | (h1 >> 19)) & 0xffffffff
I'm implementing the Murmur3 hash by processing the input data in 4-byte blocks, applying bitwise operations and constant multiplications to mix the bits thoroughly before combining with the running hash value.
After the main loop, I need to handle any remaining bytes in the tail, applying the same mixing operations if at least one byte exists. Then I finalize by XORing with the input length and running the FMix32 algorithm to avalanche the bits, which involves alternating right shifts with multiplications by specific constants before returning the final hash.
The BloomFilterBase class serves as an abstract foundation, initialized with a bit size and number of hash functions. It validates that sufficient hash implementations are available, stores references to FNV1a and Murmur3 hashers, and provides utility methods to convert various item types to bytes for hashing.
The hashing mechanism combines multiple hash functions through XOR operations to produce a composite hash value, which is then transformed into k distinct positions within the filter using modular arithmetic with a large prime offset to ensure independence across positions.
The base class defines abstract methods for core operations—adding items, checking membership, and supporting the in operator—which concrete implementations like the standard BloomFilter must override. The BloomFilter class uses a bytearray for memory-efficient bit storage, tracking the number of elements added, with helper methods to manipulate individual bits within that array.
When adding an item, I hash it to get multiple positions and set those bits to 1. Membership checks verify whether all corresponding bits are set, returning true only if none are missing. The false positive rate can be estimated using the mathematical formula (1 - e^(-k*n/m))^k, where k is the number of hash functions, m is the filter size, and n is the number of elements added.
The string representation displays the filter's configuration including its size, hash function count, element count, and approximate false positive rate. A counting variant extends this by using 4-bit counters instead of single bits, enabling deletion while accepting some tradeoffs—counters range from 0 to 15, with saturation at 15 preventing further decrements but preserving correctness.
The counting filter initializes with a bytearray where each byte holds two 4-bit counters, tracking both the element count and which positions have saturated. When retrieving a counter value, the implementation extracts the appropriate nibble from the byte array based on whether the index is even or odd.
Setting a counter clamps the value to the maximum of 15 and updates the saturated positions set when reaching that limit. Incrementing and decrementing operations respect the counter bounds, with increments capping at the maximum value and decrements stopping at zero.
When adding an item, I hash it to get positions and increment the counter at each position. For removal, I first check if the item exists in the filter, then verify none of its positions are saturated before decrementing the counters—returning false if saturation prevents reliable removal.
The contains method checks whether all counters at the item's hash positions are positive. I also track saturation levels across the filter and maintain a distribution of counter values to monitor fill patterns. The string representation summarizes the filter's configuration and current saturation percentage. d" if result else "✗ Not Found"
print(f"{item:15} {status}")
("\n--- Adding Multiple Instances ---")
for item, count in items.items():
for _ in range(count):
cbf.add(item)
code
print(f"Added items with multiplicities: {items}")
print(f"Filter state: {cbf}")
# Test membership
print("\n--- Membership Tests (Before Deletion) ---")
for item in items.keys():
result = item in cbf
status = "✓ Found" if result else "✗ Not Found"
print(f"{item:15} {status}")
# Test removal
print("\n--- Testing Deletions ---")
test_removals = {
'server1': 30,
'server2': 50, # Remove all instances
'server3': 10,
}
for item, count in test_removals.items():
print(f"\nRemoving {count} instances of '{item}':")
successful_removals = 0
for i in range(count):
if cbf.remove(item):
successful_removals += 1
else:
print(f" Failed to remove at iteration {i+1}")
break
print(f" Removed {successful_removals}/{count} instances")
print(f" '{item}' still in filter: {item in cbf}")
# Show counter distribution
print("\n--- Counter Distribution ---")
distribution = cbf.get_fill_distribution()
for value, count in distribution.items():
if count > 0:
print(f" Counter value {value:2d}: {count:4d} positions ({count/cbf.size*100:5.2f}%)")
print(f"\nSaturation level: {cbf.get_saturation_level():.2%}")
I'm iterating through removal operations for each item, tracking successful deletions and checking whether items remain in the filter afterward. Then I'm examining the counter distribution across filter positions and calculating the overall saturation level to understand the filter's state after these operations.
def test_hash_functions():
"""Test the hash functions"""
print("\n" + "=" * 70)
print("HASH FUNCTION VERIFICATION")
print("=" * 70)
code
fnv = FNV1aHash()
murmur = Murmur3Hash()
test_strings = ['hello', 'world', 'bloom filter', 'hash function']
print("\nHash values for test strings:")
print(f"{'String':<20} {'FNV-1a':<12} {'Murmur3':<12}")
print("-" * 44)
for s in test_strings:
data = s.encode('utf-8')
fnv_hash = fnv.hash(data)
murmur_hash = murmur.hash(data)
print(f"{s:<20} {fnv_hash:<12x} {murmur_hash:<12x}")
# Test consistency
print("\n--- Hash Consistency Test ---")
test_string = "consistency test"
data = test_string.encode('utf-8')
fnv_results = [fnv.hash(data) for _ in range(5)]
murmur_results = [murmur.hash(data) for _ in range(5)]
fnv_consistent = len(set(fnv_results)) == 1
murmur_consistent = len(set(murmur_results)) == 1
I'm setting up hash function tests by instantiating both FNV-1a and Murmur3 implementations, then computing their outputs across several test strings to display the hash values. I'm also verifying consistency by hashing the same string multiple times and checking whether each function produces identical results across iterations. _consistent = len(set(murmur_results)) == 1
code
print(f"FNV-1a consistent: {'✓' if fnv_consistent else '✗'}")
print(f"Murmur3 consistent: {'✓' if murmur_consistent else '✗'}")