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 use the Kirschner-Mitzenmacher double hashing optimization: h_i(x) = (h1(x) + i * h2(x)) mod m, where h1 is DJB2 and h2 is FNV-1. Two hash functions simulate k independent ones with identical guarantees.
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)
- 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")
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.
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
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
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
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 2000. |
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
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 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 | |
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. |