popoto.fields.existence_filter¶
popoto.fields.existence_filter
¶
ExistenceFilter and FrequencySketch — probabilistic data structures as Popoto fields.
ExistenceFilter wraps a Bloom filter implemented with Redis strings (SETBIT/GETBIT) and Lua scripts. Answers "have I ever stored a record matching this fingerprint?" in O(1). No Redis modules required — works on both Redis and Valkey.
FrequencySketch wraps a Count-Min Sketch implemented with Redis hashes (HINCRBY/HGET) and Lua scripts. Provides approximate frequency counting for fingerprints. No Redis modules required — works on both Redis and Valkey.
Design
Both fields are "side-effect fields" — they do not store a value on the model instance. They only maintain probabilistic indexes via on_save() hooks. This follows the same pattern as SortedFieldMixin maintaining a sorted set index.
Hash functions:
ExistenceFilter uses the Kirsch–Mitzenmacher double hashing optimization:
h_i(x) = (h1(x) + i * h2(x)) mod m. Two hash functions simulate k
independent Bloom-row hashes. The pair is versioned per filter (#775):
v2 uses 32-bit FNV-1a over the bytes forward and reversed, with all
arithmetic exact in Lua doubles; v1 (DJB2 plus an FNV-1-shaped multiply)
loses low-order bits past 2^53. v1 is still the default for a new
filter, because a process running pre-#775 code reads every filter with
the v1 hash; v2 is opt-in (ExistenceFilter(hash_version=2) for new
filters, rebuild_indexes(bloom_hash_version=2) to convert existing
ones) once every process runs this version. See BLOOM_V2_HEADER.
FrequencySketch uses independent per-row polynomial hashes: each of the
depth rows has its own prime multiplier and modulus, forming a practically
pairwise-independent family that restores the standard CMS error bound.
Tokenization: On save, fingerprint strings are automatically tokenized into individual words. Each token is added to the bloom filter / count-min sketch separately. This enables word-level queries: saving "kubernetes deployment guide" allows might_exist("kubernetes") to return True. Tokenization lowercases, splits on non-word characters, filters tokens shorter than 3 characters, and removes common English stop words. If tokenization produces zero tokens, the raw fingerprint is used as a fallback.
Redis Key Patterns
- Bloom filter: $EF:{ClassName}:{field_name} — single Redis string (bit array, followed by a 4-byte version marker on v2 filters)
- Bloom rebuild lock: $EF:{ClassName}:{field_name}:rebuild — a string holding the token of the one rebuild converting the filter to v2 (expires unless that rebuild keeps renewing it)
- Bloom rebuild staging: $EF:{ClassName}:{field_name}:rebuild:staging — the v2 filter that rebuild is filling (same expiry). One fixed name: the lock's token decides who may renew, swap or drop it
- Count-Min Sketch: $FS:{ClassName}:{field_name} — single Redis hash
Valkey Compatibility
Uses only core Redis commands: SETBIT, GETBIT, HINCRBY, HGET, EVAL. No BF., CMS., or other module commands. Works identically on Redis and Valkey.
Example
from popoto import Model, KeyField, Field from popoto.fields.existence_filter import ExistenceFilter, FrequencySketch
class Memory(Model): agent_id = KeyField() topic = Field(type=str) bloom = ExistenceFilter( error_rate=0.01, capacity=100_000, fingerprint_fn=lambda inst: inst.topic, ) freq = FrequencySketch( fingerprint_fn=lambda inst: inst.topic, )
After saving some memories...¶
if Memory.bloom.definitely_missing("kubernetes"): print("No memories about kubernetes") else: results = Memory.query.filter(agent_id="agent-1")
count = Memory.freq.get_frequency("kubernetes")
BloomRebuildError
¶
Bases: RuntimeError
A v2 bloom rebuild could not start or could not swap its result in.
Raised by Model.rebuild_indexes(bloom_hash_version=2). Whenever it is
raised the live filter is the one that was there before: a rebuild only
replaces it in a single atomic compare-and-rename, never partly.
Source code in src/popoto/fields/existence_filter.py
BloomRebuildInProgressError
¶
Bases: BloomRebuildError
Another process holds this filter's v2 rebuild lock.
Raised before rebuild_indexes() has changed anything -- no index is
deleted and no filter touched -- so the caller can simply retry once the
other rebuild has finished (by which time the conversion it asked for is
usually already done). lock_key, holder and expires_in_ms say
which rebuild holds it and when the lock lapses if that rebuild has died.
Source code in src/popoto/fields/existence_filter.py
BloomRebuildLostLockError
¶
Bases: BloomRebuildError
The rebuild's lock lapsed before its swap, so the swap was refused.
Every record was re-saved (the other indexes are rebuilt), but the v2 staging filter was discarded and the live filter is unchanged -- still complete for every token it held. Rerun the rebuild to convert it.
Source code in src/popoto/fields/existence_filter.py
BloomLockRenewer
¶
Renews v2 rebuild locks on a timer for as long as they are held.
Model.rebuild_indexes(bloom_hash_version=2) holds each filter's lock
from before step 1 (deleting the other indexes) until the swap. Renewal
must not depend on what the rebuild is doing at the time: step 1 can run
for seconds on a large store without visiting a record (PR #801 review,
N1), so a background thread renews every third of
Defaults.BLOOM_REBUILD_LOCK_TTL_MS, through the token-checked renew
script. async_rebuild_indexes runs rebuild_indexes in a worker
thread on Redis, so it gets the same renewer.
Use as a context manager around the work. The thread is started on
entry and stopped and joined on exit, whatever ends the block (an
exception, KeyboardInterrupt), so it never outlives the rebuild. It
is a daemon too, so a hard interpreter exit is never held up by it.
A renewal that finds its lock lost (lapsed, or taken over by another
rebuild) records the field in :attr:lost and stops renewing it; the
caller refuses that filter's swap. A pause of the whole process
(SIGSTOP, a VM freeze) pauses this thread with it, so the lock still
lapses then -- and the swap's own compare-and-rename refuses it.
Source code in src/popoto/fields/existence_filter.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | |
interval_s()
staticmethod
¶
A third of the lock TTL, read at call time (it is a tuning constant tests patch).
stop()
¶
Stop renewing and wait for the thread to end. Idempotent.
renew_once()
¶
Renew every lock still held; record any found lost.
Source code in src/popoto/fields/existence_filter.py
ExistenceFilter
¶
Bases: Field
Bloom filter for O(1) probabilistic membership checks.
Implemented with Redis SETBIT/GETBIT and Lua scripts. No Redis modules required -- works on both Redis and Valkey.
ExistenceFilter is a "side-effect field" that does not store a value on the model instance. It maintains a Bloom filter index via on_save() hooks. On query, might_exist() checks the filter; definitely_missing() is its inverse.
False positives are possible (might_exist returns True for an item never added). False negatives are impossible (definitely_missing never returns True for an item that was added).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error_rate
|
Target false positive rate. Default 0.01 (1%). |
required | |
capacity
|
Expected number of distinct items. Default 100,000. |
required | |
fingerprint_fn
|
Callable that takes a model instance and returns a string fingerprint. This is required -- there is no default. |
required |
Redis Key
$EF:{ClassName}:{field_name} -- single Redis string used as bit array.
hash_version: The hash a missing filter is created with: 1
(default) or 2. An existing filter is always read and written
with the hash it was built with, whatever this says.
Hash version (#775):
v1 packs similar tokens onto few bits (low-order bits are lost past
2^53 in Lua's doubles), so its false-positive rate is far above
error_rate for tokens shaped like the ones it holds; it never
gives a false negative. v2 is exact, and marks itself with four bytes
after its bit array. v2 is opt-in: pre-#775 code reads and writes
every filter with the v1 hash, so a v2 filter gives false negatives
to any process still running it. Upgrade every process first, then
opt in -- hash_version=2 here for new filters, and
Model.rebuild_indexes(bloom_hash_version=2) to convert existing
ones (one rebuild at a time per filter, swapped in atomically).
hash_version() says which one a filter is, and
check_indexes() lists v1 filters under legacy_hash.
Example
class Memory(Model): topic = Field(type=str) bloom = ExistenceFilter( error_rate=0.01, capacity=100_000, fingerprint_fn=lambda inst: inst.topic, )
memory = Memory(topic="kubernetes") memory.save()
Memory.bloom.might_exist(Memory, "kubernetes") # True Memory.bloom.definitely_missing(Memory, "new-topic") # True
Source code in src/popoto/fields/existence_filter.py
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 | |
hash_version(model_class)
¶
The hash version this field's Redis filter is built with (#775).
2 for a v2 filter, 1 for a v1 one (every filter built before
775, and every filter created since unless the field opts in with¶
hash_version=2), None when the filter does not exist yet.
Always None off Redis: Postgres keeps an exact token table, not a
bit array, so it has no hash to version.
Source code in src/popoto/fields/existence_filter.py
stale_rebuild_staging(model_class)
¶
[staging key] when a staging key exists with no lock -- left
by a rebuild that died -- else []; check_indexes() lists it.
Nothing reads it, no save writes it (saves write it only under a
lock), it expires on its own, and the next v2 rebuild of this filter
deletes it. Two EXISTS in one MULTI, no keyspace scan.
Always [] off Redis.
Source code in src/popoto/fields/existence_filter.py
on_save(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
Add the model instance's fingerprint tokens to the Bloom filter.
Called automatically by Model.save() for each field. Computes the fingerprint, tokenizes it into individual words, and runs BLOOM_ADD_MULTI_LUA to set bits for each token. If tokenization produces no tokens, falls back to adding the raw fingerprint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_instance
|
The model instance being saved. |
required | |
field_name
|
Name of this field on the model. |
required | |
field_value
|
Current field value (unused -- ExistenceFilter is side-effect only). |
required | |
pipeline
|
Optional Redis pipeline for batch operations. |
None
|
|
**kwargs
|
Additional context. |
{}
|
Returns:
| Type | Description |
|---|---|
|
The pipeline if provided, otherwise the Lua script result. |
Source code in src/popoto/fields/existence_filter.py
on_delete(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
No-op. Bloom filters do not support removal by design.
Bloom filters guarantee zero false negatives. Removing items would violate this guarantee because multiple items may share bit positions. Stale positives are harmless for a pre-filter use case.
Returns:
| Type | Description |
|---|---|
|
The pipeline if provided, otherwise None. |
Source code in src/popoto/fields/existence_filter.py
might_exist(model_class, fingerprint)
¶
Check if a fingerprint might exist in the Bloom filter.
The query is tokenized using the same rules as on_save(). If the query produces tokens, returns True if ANY token is found in the filter. If tokenization produces no tokens, checks the raw lowercased query (matching the on_save fallback behavior).
Returns True if the fingerprint is possibly in the set (may be a false positive). Returns False if the fingerprint is definitely not in the set (guaranteed correct).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class to check against. |
required | |
fingerprint
|
The fingerprint string to look up. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if possibly present, False if definitely absent. |
Source code in src/popoto/fields/existence_filter.py
definitely_missing(model_class, fingerprint)
¶
Check if a fingerprint is definitely not in the Bloom filter.
Convenience inverse of might_exist(). When this returns True, the caller can skip expensive retrieval entirely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class to check against. |
required | |
fingerprint
|
The fingerprint string to look up. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if definitely absent, False if possibly present. |
Source code in src/popoto/fields/existence_filter.py
fill_ratio(model_class)
¶
Diagnostic: compute the proportion of set bits in the Bloom filter.
Useful for monitoring capacity usage. When fill_ratio approaches 0.5, the false positive rate starts degrading beyond the configured error_rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class whose Bloom filter to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
Ratio of set bits to total bits (0.0 to 1.0). Returns 0.0 if the Bloom filter key doesn't exist yet. |
Source code in src/popoto/fields/existence_filter.py
might_exist_batch(model_class, fingerprints)
¶
Check multiple fingerprints against the Bloom filter in one round-trip.
Each fingerprint is tokenized using the same rules as might_exist(). A fingerprint is considered a hit if ANY of its tokens is found in the filter. Uses a single Lua EVAL call for all tokens, then maps results back to the original fingerprints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class to check against. |
required | |
fingerprints
|
List of fingerprint strings to check. |
required |
Returns:
| Type | Description |
|---|---|
|
dict[str, bool]: Mapping of fingerprint -> might_exist result. Returns empty dict for empty input list. |
Source code in src/popoto/fields/existence_filter.py
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 | |
might_exist_count(model_class, fingerprints)
¶
Count how many fingerprints might exist in a single round-trip.
Convenience wrapper around might_exist_batch(). Returns the number of fingerprints for which might_exist would return True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class to check against. |
required | |
fingerprints
|
List of fingerprint strings to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
Number of fingerprints that might exist. |
Source code in src/popoto/fields/existence_filter.py
FrequencySketch
¶
Bases: Field
Count-Min Sketch for approximate frequency queries.
Implemented with Redis hashes and Lua scripts. No Redis modules required -- works on both Redis and Valkey.
FrequencySketch is a "side-effect field" that maintains a Count-Min Sketch alongside the model. Each save increments counters for the fingerprint. get_frequency() returns the approximate count.
The Count-Min Sketch may overcount (never undercount). The error bound depends on width and depth parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
width
|
Number of counters per row. Default 2003 (prime, minimises hash collision). |
required | |
depth
|
Number of hash functions (rows). Default 7. |
required | |
fingerprint_fn
|
Callable that takes a model instance and returns a string fingerprint. This is required -- there is no default. |
required |
Redis Key
$FS:{ClassName}:{field_name} -- single Redis hash with
row:column field names and integer counter values.
Example
class Memory(Model): topic = Field(type=str) freq = FrequencySketch( fingerprint_fn=lambda inst: inst.topic, )
memory = Memory(topic="kubernetes") memory.save() memory.save() # increment again
Memory.freq.get_frequency(Memory, "kubernetes") # ~2
Source code in src/popoto/fields/existence_filter.py
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 | |
on_save(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
Increment the Count-Min Sketch counters for this instance's fingerprint tokens.
Called automatically by Model.save() for each field. Tokenizes the fingerprint and increments counters for each token individually. If tokenization produces no tokens, falls back to the raw fingerprint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_instance
|
The model instance being saved. |
required | |
field_name
|
Name of this field on the model. |
required | |
field_value
|
Current field value (unused). |
required | |
pipeline
|
Optional Redis pipeline for batch operations. |
None
|
|
**kwargs
|
Additional context. |
{}
|
Returns:
| Type | Description |
|---|---|
|
The pipeline if provided, otherwise the Lua script result. |
Source code in src/popoto/fields/existence_filter.py
on_delete(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
No-op. Count-Min Sketch does not support decrement.
CMS counters are monotonically increasing. Decrementing would violate the "never undercount" guarantee.
Returns:
| Type | Description |
|---|---|
|
The pipeline if provided, otherwise None. |
Source code in src/popoto/fields/existence_filter.py
get_frequency(model_class, fingerprint)
¶
Query the approximate frequency of a fingerprint.
The query is tokenized using the same rules as on_save(). If the query produces tokens, returns the minimum frequency across those tokens (conservative estimate). If tokenization produces no tokens, queries the raw lowercased fingerprint (matching the on_save fallback).
Returns the Count-Min Sketch estimate. This value may overcount but never undercounts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class to query against. |
required | |
fingerprint
|
The fingerprint string to look up. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
Approximate frequency count. Returns 0 if the fingerprint has never been seen or the CMS key doesn't exist yet. |