Skip to content

popoto.fields.co_occurrence_field

popoto.fields.co_occurrence_field

CoOccurrenceField — weighted association edges with graph propagation.

Maintains weighted bidirectional (or unidirectional) edges between model instances using Redis sorted sets. Weights strengthen via co-retrieval and decay when not reinforced. BFS graph propagation with exponential weight decay per hop enables multi-hop associative retrieval.

Each CoOccurrenceField instance owns per-PK sorted sets

$CoOcF:{ClassName}:{field_name}:{pk} -> ZSET { target_pk: weight, ... }

When symmetric=True (default), link/strengthen/unlink operations mirror on both source and target sorted sets.

Example

class Memory(Model): key = UniqueKeyField() content = StringField() associations = CoOccurrenceField(symmetric=True, max_edges=100)

Create edges

CoOccurrenceField.link(Memory, "pk_a", "pk_b", initial_weight=0.1) CoOccurrenceField.strengthen(Memory, "pk_a", "pk_b", delta=0.05)

Query associations

linked = CoOccurrenceField.get_linked(Memory, "pk_a")

=> [("pk_b", 0.15)]

Multi-hop propagation

scores = CoOccurrenceField.propagate(Memory, ["pk_a"], depth=2)

=> {"pk_b": 0.5, "pk_c": 0.25}

CoOccurrenceField

Bases: Field

A field that maintains weighted association edges between model instances.

Uses per-PK Redis sorted sets to store weighted edges to other PKs. Supports symmetric (bidirectional) and asymmetric (unidirectional) modes.

Edge weights are clamped at Defaults.CO_OCCURRENCE_WEIGHT_CAP (default 1.0) on every strengthen() write via an atomic Lua script, and a read-time min(edge_weight, cap) in the propagation BFS handles pre-existing over-cap stored weights as defense-in-depth. This guarantees the per-hop contraction invariant used by propagate(): decay_per_hop * effective_edge_weight <= decay_per_hop * cap < 1 (at default config, 0.5 * 1.0 = 0.5 < 1), so activation decays monotonically with hop count and the BFS threshold reliably terminates the walk. A runtime guard in propagate() raises ValueError if cap * decay_per_hop >= 1.0 to catch future misconfiguration.

Parameters:

Name Type Description Default
symmetric

If True, edges are bidirectional. Default True.

required
max_edges

Maximum edges per PK. Lowest-weight edges pruned when exceeded. Default 500.

required
decay_factor

Multiplicative decay factor for weaken_all(). Default 0.95.

required
Example

class Memory(Model): key = UniqueKeyField() content = StringField() associations = CoOccurrenceField(symmetric=True, max_edges=100)

Source code in src/popoto/fields/co_occurrence_field.py
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 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
 575
 576
 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
 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
class CoOccurrenceField(Field):
    """A field that maintains weighted association edges between model instances.

    Uses per-PK Redis sorted sets to store weighted edges to other PKs.
    Supports symmetric (bidirectional) and asymmetric (unidirectional) modes.

    Edge weights are clamped at ``Defaults.CO_OCCURRENCE_WEIGHT_CAP``
    (default 1.0) on every ``strengthen()`` write via an atomic Lua script,
    and a read-time ``min(edge_weight, cap)`` in the propagation BFS
    handles pre-existing over-cap stored weights as defense-in-depth. This
    guarantees the per-hop contraction invariant used by ``propagate()``:
    ``decay_per_hop * effective_edge_weight <= decay_per_hop * cap < 1``
    (at default config, 0.5 * 1.0 = 0.5 < 1), so activation decays
    monotonically with hop count and the BFS threshold reliably terminates
    the walk. A runtime guard in ``propagate()`` raises ``ValueError`` if
    ``cap * decay_per_hop >= 1.0`` to catch future misconfiguration.

    Args:
        symmetric: If True, edges are bidirectional. Default True.
        max_edges: Maximum edges per PK. Lowest-weight edges pruned when exceeded.
            Default 500.
        decay_factor: Multiplicative decay factor for weaken_all(). Default 0.95.

    Example:
        class Memory(Model):
            key = UniqueKeyField()
            content = StringField()
            associations = CoOccurrenceField(symmetric=True, max_edges=100)
    """

    # Export/import: the edge set is stored per-record -- get_edge_key()
    # appends the source pk -- and a ZSET score is the stored weight itself,
    # with no derived encoding. So it is carried verbatim by a raw ZADD.
    # A replay-based restore is not merely inferior here but impossible:
    # strengthen() and weaken_all() take a delta and a factor, never an
    # absolute target weight, so reaching an exported weight through them
    # would mean inventing an interaction history that never happened.
    # See #556.
    roundtrip_policy: str = "carry"

    @classmethod
    def export_state(
        cls,
        model_instance: Any,
        field_name: str,
        field_value: Any = None,
        **kwargs: Any,
    ) -> Optional[dict[str, Any]]:
        """Export this record's association edges.

        Returns:
            ``{"edges": {target_pk: weight}, "max_edges": int}``, or ``None``
            when this record has no edges.
        """
        field = model_instance._meta.fields.get(field_name)
        if not isinstance(field, CoOccurrenceField):
            return None

        model_class = type(model_instance)
        try:
            pk = model_instance.db_key.redis_key
        except Exception:
            return None

        backend = _graph_backend(model_class)
        if backend is not None:
            rows = backend.graph_expand(
                _spec(model_class),
                field_name,
                [_rid(model_class, pk)],
                depth=1,
                decay_per_hop=1.0,
                threshold=None,
                fanout=None,
                mode="edges",
            )
            if not rows:
                return None
            return {
                "edges": {rid.canonical: score for rid, score in rows},
                "max_edges": int(field.max_edges),
            }

        raw = cast(
            "list[tuple[Any, float]]",
            get_REDIS_DB().zrange(
                field.get_edge_key(model_class, pk), 0, -1, withscores=True
            ),
        )
        if not raw:
            return None

        # Members come back as bytes. They must be decoded here, not left for
        # the JSON layer: to_jsonable routes a dict with bytes keys through the
        # __dictpairs__/__bytes__ tagged encoding, which round-trips correctly
        # but silently stops matching the plain-object export shape the docs
        # describe. Same idiom as get_linked() and on_delete().
        edges = {
            (member.decode("utf-8") if isinstance(member, bytes) else str(member)): (
                float(score)
            )
            for member, score in raw
        }
        return {"edges": edges, "max_edges": int(field.max_edges)}

    @classmethod
    def import_state(
        cls,
        model_instance: Any,
        field_name: str,
        state: Any,
        **kwargs: Any,
    ) -> None:
        """Restore this record's association edges after import.

        Written as a raw ``DELETE`` + ``ZADD``, never through ``link`` or
        ``strengthen``: those apply relative adjustments and NX semantics, and
        cannot reproduce an absolute weight. Symmetric mirroring is
        deliberately NOT performed -- each record owns its own edge set, so a
        partner's mirror edge arrives with the partner record if it is in the
        export.

        This REPLACES rather than merges. ``on_save`` never touches edge keys
        (``CoOccurrenceField`` defines no ``on_save``), so there is nothing to
        merge with except edges the destination accumulated on its own since
        the export was taken -- and under ``on_conflict="overwrite"``, whose
        contract is that the record is replaced wholesale, keeping those would
        leave a graph matching neither side.

        Two normalizations to the DESTINATION's configuration are applied, and
        both are load-bearing rather than cosmetic:

        * weights are clamped to ``Defaults.CO_OCCURRENCE_WEIGHT_CAP``, because
          ``propagate()`` depends on a contraction invariant that an over-cap
          weight would break -- BFS would stop decaying with hop count;
        * the set is truncated to the destination field's ``max_edges``,
          keeping the highest weights, exactly as ``LINK_WITH_PRUNE_LUA`` does
          on the normal path.
        """
        if not state:
            return None
        edges = state.get("edges")
        if not isinstance(edges, dict) or not edges:
            return None

        field = model_instance._meta.fields.get(field_name)
        if not isinstance(field, CoOccurrenceField):
            return None

        model_class = type(model_instance)
        try:
            pk = model_instance.db_key.redis_key
        except Exception:
            return None

        cap = Defaults.CO_OCCURRENCE_WEIGHT_CAP
        ranked = sorted(
            (
                (
                    (
                        target.decode("utf-8")
                        if isinstance(target, bytes)
                        else str(target)
                    ),
                    min(float(weight), cap),
                )
                for target, weight in edges.items()
            ),
            key=lambda pair: pair[1],
            reverse=True,
        )[: max(1, int(field.max_edges))]

        backend = _graph_backend(model_class)
        if backend is not None:
            backend.graph_update(
                _spec(model_class),
                field_name,
                "replace",
                _rid(model_class, pk),
                None,
                None,
                edges=dict(ranked),
            )
            return None

        edge_key = field.get_edge_key(model_class, pk)
        get_REDIS_DB().delete(edge_key)
        get_REDIS_DB().zadd(edge_key, dict(ranked))
        return None

    def __init__(self, **kwargs):
        self.symmetric = kwargs.pop("symmetric", True)
        self.max_edges = kwargs.pop("max_edges", 500)
        decay_factor = kwargs.pop("decay_factor", None)
        self.decay_factor = (
            decay_factor
            if decay_factor is not None
            else Defaults.CO_OCCURRENCE_DECAY_FACTOR
        )

        if self.max_edges < 1:
            from ..exceptions import ModelException

            raise ModelException(f"max_edges must be >= 1 (got {self.max_edges})")
        if not (0 <= self.decay_factor < 1):
            from ..exceptions import ModelException

            raise ModelException(
                f"decay_factor must be >= 0 and < 1 (got {self.decay_factor})"
            )

        # CoOccurrenceField stores no value on the model instance itself
        kwargs.setdefault("type", str)
        kwargs.setdefault("null", True)
        kwargs.setdefault("default", None)
        super().__init__(**kwargs)

    def get_edge_key(self, model_class, pk):
        """Build the Redis key for a PK's edge sorted set.

        Public API for external callers that need direct Redis access to
        a PK's edge set (e.g., bulk edge inspection, custom graph queries,
        monitoring). Prefer the higher-level methods (link, get_linked,
        propagate) for normal operations.

        Pattern: $CoOcF:{ClassName}:{field_name}:{pk}

        Args:
            model_class: The Model class (or instance).
            pk: The primary key string.

        Returns:
            str: The Redis key for this PK's edge sorted set.
        """
        base_key = self.get_special_use_field_db_key(model_class, self.name)
        return base_key.redis_key + ":" + str(pk)

    def get_edge_key_prefix(self, model_class):
        """Build the Redis key prefix for BFS propagation.

        Public API for external callers that need to scan or iterate over
        all edge sorted sets for a field (e.g., graph analytics, bulk cleanup).

        Pattern: $CoOcF:{ClassName}:{field_name}:

        Args:
            model_class: The Model class.

        Returns:
            str: The key prefix (ending with colon).
        """
        base_key = self.get_special_use_field_db_key(model_class, self.name)
        return base_key.redis_key + ":"

    def link(
        self,
        model_class,
        source_pk,
        target_pk,
        initial_weight=_UNSET,
        pipeline=None,
    ):
        """Create a weighted edge between two PKs.

        If symmetric=True, creates edges in both directions. Uses an atomic
        Lua script to handle ZADD + ZCARD + conditional pruning.

        Args:
            model_class: The Model class.
            source_pk: Source primary key string.
            target_pk: Target primary key string.
            initial_weight: Weight for the new edge. Default from
                ``Defaults.CO_OCCURRENCE_INITIAL_WEIGHT``.
            pipeline: Optional Redis pipeline (unused for Lua eval).

        Returns:
            float: The weight of the edge (existing weight if already linked).

        Raises:
            ValueError: If source_pk == target_pk (no self-loops), or if
                ``initial_weight`` exceeds ``Defaults.CO_OCCURRENCE_WEIGHT_CAP``
                (would violate the contraction invariant).
        """
        if initial_weight is _UNSET:
            initial_weight = Defaults.CO_OCCURRENCE_INITIAL_WEIGHT
        source_pk = str(source_pk)
        target_pk = str(target_pk)

        if source_pk == target_pk:
            raise ValueError("Cannot link a PK to itself (no self-loops)")
        if initial_weight > Defaults.CO_OCCURRENCE_WEIGHT_CAP:
            raise ValueError(
                f"initial_weight ({initial_weight}) exceeds "
                f"CO_OCCURRENCE_WEIGHT_CAP "
                f"({Defaults.CO_OCCURRENCE_WEIGHT_CAP}); edges above the "
                f"cap violate the per-hop contraction invariant used by "
                f"propagate()."
            )

        backend = _graph_backend(model_class)
        if backend is not None:
            return float(
                backend.graph_update(
                    _spec(model_class),
                    _name(self),
                    "link",
                    _rid(model_class, source_pk),
                    _rid(model_class, target_pk),
                    initial_weight,
                    uow=_uow(pipeline, backend),
                )
            )

        source_key = self.get_edge_key(model_class, source_pk)
        result = run_lua(
            get_REDIS_DB(),
            LINK_WITH_PRUNE_LUA,
            1,
            source_key,
            target_pk,
            str(initial_weight),
            str(self.max_edges),
        )

        if self.symmetric:
            target_key = self.get_edge_key(model_class, target_pk)
            run_lua(
                get_REDIS_DB(),
                LINK_WITH_PRUNE_LUA,
                1,
                target_key,
                source_pk,
                str(initial_weight),
                str(self.max_edges),
            )

        return float(result)

    def strengthen(
        self,
        model_class,
        source_pk,
        target_pk,
        delta=0.05,
        pipeline=None,
    ):
        """Increase the weight of an existing edge.

        Uses an atomic Lua script (STRENGTHEN_CLAMP_LUA) to read the
        current weight, add delta, and clamp at
        ``Defaults.CO_OCCURRENCE_WEIGHT_CAP`` so stored weights can never
        exceed the cap. This guarantees the per-hop contraction invariant
        used by ``propagate()`` (``decay_per_hop * effective_edge_weight``
        stays <= ``decay_per_hop * cap`` < 1 at default config).

        Args:
            model_class: The Model class.
            source_pk: Source primary key string.
            target_pk: Target primary key string.
            delta: Amount to increase weight by. Must be > 0. Default 0.05.
            pipeline: Optional Redis pipeline.

        Returns:
            float: The new (clamped) weight after increment, or None when
                called with a pipeline (execution deferred).

        Raises:
            ValueError: If delta <= 0.
        """
        if delta <= 0:
            raise ValueError(f"delta must be > 0 (got {delta})")

        source_pk = str(source_pk)
        target_pk = str(target_pk)

        cap = Defaults.CO_OCCURRENCE_WEIGHT_CAP
        backend = _graph_backend(model_class)
        if backend is not None:
            # No EventStreamMixin entry: its stream is a Redis structure,
            # and Postgres pub/sub arrives in M5.
            uow = _uow(pipeline, backend)
            weight = backend.graph_update(
                _spec(model_class),
                _name(self),
                "strengthen",
                _rid(model_class, source_pk),
                _rid(model_class, target_pk),
                delta,
                uow=uow,
                cap=cap,
            )
            if pipeline and uow is None:
                return None  # a Redis pipeline: the queued call's reply
            return float(weight)

        source_key = self.get_edge_key(model_class, source_pk)
        db = pipeline if pipeline else get_REDIS_DB()
        new_weight = run_lua(
            db,
            STRENGTHEN_CLAMP_LUA,
            1,
            source_key,
            target_pk,
            str(delta),
            str(cap),
        )

        if self.symmetric:
            target_key = self.get_edge_key(model_class, target_pk)
            run_lua(
                db,
                STRENGTHEN_CLAMP_LUA,
                1,
                target_key,
                source_pk,
                str(delta),
                str(cap),
            )

        # EventStreamMixin: log strengthen event
        from .event_stream import EventStreamMixin

        if not pipeline and issubclass(model_class, EventStreamMixin):
            try:
                import time

                stream_name = getattr(
                    model_class, "_stream_name", EventStreamMixin._stream_name
                )
                max_length = getattr(
                    model_class,
                    "_stream_max_length",
                    EventStreamMixin._stream_max_length,
                )
                stream_key = f"stream:{stream_name}"
                partition_field = getattr(model_class, "_stream_partition_field", None)
                if partition_field:
                    stream_key = f"{stream_key}:{source_pk}"
                entry = {
                    "model": model_class.__name__,
                    "pk": str(source_pk),
                    "op": "strengthen",
                    "ts": str(time.time()),
                    "changed_fields": "",
                    "source_pk": str(source_pk),
                    "target_pk": str(target_pk),
                    "delta": str(delta),
                }
                get_REDIS_DB().xadd(
                    stream_key, entry, maxlen=max_length, approximate=True
                )
            except Exception:
                pass  # Best-effort, don't block strengthen

        if pipeline:
            return None  # Pipeline defers execution
        return float(new_weight)

    def unlink(self, model_class, source_pk, target_pk, pipeline=None):
        """Remove an edge between two PKs.

        If symmetric=True, removes edges in both directions.

        Args:
            model_class: The Model class.
            source_pk: Source primary key string.
            target_pk: Target primary key string.
            pipeline: Optional Redis pipeline.
        """
        source_pk = str(source_pk)
        target_pk = str(target_pk)

        backend = _graph_backend(model_class)
        if backend is not None:
            backend.graph_update(
                _spec(model_class),
                _name(self),
                "unlink",
                _rid(model_class, source_pk),
                _rid(model_class, target_pk),
                None,
                uow=_uow(pipeline, backend),
            )
            return None

        source_key = self.get_edge_key(model_class, source_pk)
        db = pipeline if pipeline else get_REDIS_DB()
        db.zrem(source_key, target_pk)

        if self.symmetric:
            target_key = self.get_edge_key(model_class, target_pk)
            db.zrem(target_key, source_pk)

    def weaken_all(self, model_class, pk, factor=None, pipeline=None):
        """Multiplicatively decay all edge weights for a PK.

        Edges that fall below a threshold (factor * 0.01) after weakening
        are automatically pruned.

        Args:
            model_class: The Model class.
            pk: Primary key whose edges to weaken.
            factor: Decay factor (0 < factor < 1). Defaults to self.decay_factor.
                factor=0 removes all edges.
            pipeline: Optional Redis pipeline (unused for Lua eval).

        Returns:
            int: Number of edges removed by pruning.

        Raises:
            ValueError: If factor > 1 or factor < 0.
        """
        if factor is None:
            factor = self.decay_factor

        if factor < 0 or factor > 1:
            raise ValueError(f"factor must be between 0 and 1 inclusive (got {factor})")

        pk = str(pk)
        backend = _graph_backend(model_class)
        if backend is not None:
            return int(
                backend.graph_update(
                    _spec(model_class),
                    _name(self),
                    "weaken",
                    _rid(model_class, pk),
                    None,
                    factor,
                    uow=_uow(pipeline, backend),
                )
            )
        edge_key = self.get_edge_key(model_class, pk)

        if factor == 0:
            # Special case: remove all edges
            count = get_REDIS_DB().zcard(edge_key)
            get_REDIS_DB().delete(edge_key)
            return int(count)

        # Use threshold of 0.001 for pruning
        threshold = 0.001
        result = run_lua(
            get_REDIS_DB(),
            WEAKEN_ALL_LUA,
            1,
            edge_key,
            str(factor),
            str(threshold),
        )
        return int(result)

    def get_linked(self, model_class, pk, min_weight=0.01, limit=20):
        """Get linked PKs sorted by weight descending.

        Args:
            model_class: The Model class.
            pk: Primary key to get links for.
            min_weight: Minimum weight threshold. Default 0.01.
            limit: Maximum number of results. Default 20.

        Returns:
            list[tuple[str, float]]: List of (pk, weight) tuples,
                sorted by weight descending.
        """
        pk = str(pk)
        backend = _graph_backend(model_class)
        if backend is not None:
            # graph_expand at depth 1: the stored weights, unclamped, as the
            # scores (plan §1).
            return [
                (rid.canonical, score)
                for rid, score in backend.graph_expand(
                    _spec(model_class),
                    _name(self),
                    [_rid(model_class, pk)],
                    depth=1,
                    decay_per_hop=1.0,
                    threshold=min_weight,
                    fanout=limit,
                    mode="linked",
                )
            ]
        edge_key = self.get_edge_key(model_class, pk)

        # ZREVRANGEBYSCORE: highest to lowest, with score filter
        results = get_REDIS_DB().zrevrangebyscore(
            edge_key,
            "+inf",
            str(min_weight),
            start=0,
            num=limit,
            withscores=True,
        )

        return [
            (
                member.decode("utf-8") if isinstance(member, bytes) else member,
                float(score),
            )
            for member, score in results
        ]

    def propagate(
        self,
        model_class,
        seed_pks,
        depth=2,
        decay_per_hop=_UNSET,
        threshold=0.01,
    ):
        """BFS graph propagation with exponential weight decay per hop.

        Traverses edges starting from seed PKs, applying multiplicative
        decay at each hop. When the same PK is reached via multiple paths,
        the maximum weight is kept.

        Edge weights are clamped at ``Defaults.CO_OCCURRENCE_WEIGHT_CAP``
        at read time (defense-in-depth) so pre-existing over-cap stored
        weights cannot amplify propagation. A runtime guard raises
        ``ValueError`` if ``cap * decay_per_hop >= 1.0`` (misconfiguration
        that would amplify instead of decay).

        Args:
            model_class: The Model class.
            seed_pks: List of starting primary keys.
            depth: Maximum BFS depth. Default 2. depth=0 returns seeds only.
            decay_per_hop: Weight multiplier per hop. Default from
                ``Defaults.CO_OCCURRENCE_DECAY_PER_HOP``.
            threshold: Minimum propagated weight to continue. Default 0.01.

        Returns:
            dict[str, float]: Mapping of discovered PKs to their propagated
                weights. Seeds are not included in results (except for depth=0).

        Raises:
            ValueError: If ``CO_OCCURRENCE_WEIGHT_CAP * decay_per_hop >= 1.0``
                (contraction invariant violated; propagation would amplify).
        """
        if decay_per_hop is _UNSET:
            decay_per_hop = Defaults.CO_OCCURRENCE_DECAY_PER_HOP
        # Runtime contraction guard: enforces cap * decay_per_hop < 1 so
        # that each hop strictly decays activation. Fires on
        # misconfiguration only (e.g. a future constants sweep raises
        # decay_per_hop above 1/cap); under current defaults
        # (1.0 * 0.5 = 0.5 < 1) this never raises.
        if Defaults.CO_OCCURRENCE_WEIGHT_CAP * decay_per_hop >= 1.0:
            raise ValueError(
                f"Contraction invariant violated: CO_OCCURRENCE_WEIGHT_CAP "
                f"({Defaults.CO_OCCURRENCE_WEIGHT_CAP}) * decay_per_hop "
                f"({decay_per_hop}) >= 1.0; propagation would amplify "
                f"instead of decay. Lower the cap or decay_per_hop."
            )
        if not seed_pks:
            return {}

        seed_pks = [str(pk) for pk in seed_pks]

        if depth == 0:
            return {pk: 1.0 for pk in seed_pks}

        backend = _graph_backend(model_class)
        if backend is not None:
            return {
                rid.canonical: score
                for rid, score in backend.graph_expand(
                    _spec(model_class),
                    _name(self),
                    [_rid(model_class, pk) for pk in seed_pks],
                    depth=depth,
                    decay_per_hop=decay_per_hop,
                    threshold=threshold,
                    fanout=self.max_edges,
                    cap=Defaults.CO_OCCURRENCE_WEIGHT_CAP,
                )
            }

        key_prefix = self.get_edge_key_prefix(model_class)

        result = run_lua(
            get_REDIS_DB(),
            PROPAGATE_BFS_LUA,
            1,
            key_prefix,
            json.dumps(seed_pks),
            str(depth),
            str(decay_per_hop),
            str(threshold),
            str(self.max_edges),
            str(Defaults.CO_OCCURRENCE_WEIGHT_CAP),
        )

        # Parse flat array [pk1, weight1, pk2, weight2, ...]
        scores = {}
        if result:
            for i in range(0, len(result), 2):
                pk = result[i]
                if isinstance(pk, bytes):
                    pk = pk.decode("utf-8")
                weight = float(result[i + 1])
                scores[pk] = weight

        return scores

    @classmethod
    def on_delete(
        cls,
        model_instance,
        field_name,
        field_value,
        pipeline=None,
        **kwargs,
    ):
        """Clean up edges when a model instance is deleted.

        Removes the instance's own edge sorted set AND removes it from
        all other instances' edge sorted sets via SCAN + ZREM.

        Args:
            model_instance: The Model instance being deleted.
            field_name: Name of this CoOccurrenceField.
            field_value: Current field value (unused).
            pipeline: Optional Redis pipeline.
            **kwargs: Additional context.
        """
        field = model_instance._meta.fields.get(field_name)
        if not isinstance(field, CoOccurrenceField):
            return super().on_delete(
                model_instance, field_name, field_value, pipeline=pipeline, **kwargs
            )

        # Get this instance's PK from its redis key
        member_key = kwargs.get("saved_redis_key") or model_instance.db_key.redis_key

        # Get the edge key for this instance
        edge_key = field.get_edge_key(model_instance, member_key)

        if field.symmetric:
            # Get all linked PKs so we can remove reverse edges
            linked = get_REDIS_DB().zrange(edge_key, 0, -1)
            for target_pk in linked:
                if isinstance(target_pk, bytes):
                    target_pk = target_pk.decode("utf-8")
                target_edge_key = field.get_edge_key(model_instance, target_pk)
                if pipeline:
                    pipeline.zrem(target_edge_key, member_key)
                else:
                    get_REDIS_DB().zrem(target_edge_key, member_key)

        # Delete this instance's edge sorted set
        if pipeline:
            pipeline.delete(edge_key)
        else:
            get_REDIS_DB().delete(edge_key)

        return super().on_delete(
            model_instance, field_name, field_value, pipeline=pipeline, **kwargs
        )

export_state(model_instance, field_name, field_value=None, **kwargs) classmethod

Export this record's association edges.

Returns:

Type Description
Optional[dict[str, Any]]

{"edges": {target_pk: weight}, "max_edges": int}, or None

Optional[dict[str, Any]]

when this record has no edges.

Source code in src/popoto/fields/co_occurrence_field.py
@classmethod
def export_state(
    cls,
    model_instance: Any,
    field_name: str,
    field_value: Any = None,
    **kwargs: Any,
) -> Optional[dict[str, Any]]:
    """Export this record's association edges.

    Returns:
        ``{"edges": {target_pk: weight}, "max_edges": int}``, or ``None``
        when this record has no edges.
    """
    field = model_instance._meta.fields.get(field_name)
    if not isinstance(field, CoOccurrenceField):
        return None

    model_class = type(model_instance)
    try:
        pk = model_instance.db_key.redis_key
    except Exception:
        return None

    backend = _graph_backend(model_class)
    if backend is not None:
        rows = backend.graph_expand(
            _spec(model_class),
            field_name,
            [_rid(model_class, pk)],
            depth=1,
            decay_per_hop=1.0,
            threshold=None,
            fanout=None,
            mode="edges",
        )
        if not rows:
            return None
        return {
            "edges": {rid.canonical: score for rid, score in rows},
            "max_edges": int(field.max_edges),
        }

    raw = cast(
        "list[tuple[Any, float]]",
        get_REDIS_DB().zrange(
            field.get_edge_key(model_class, pk), 0, -1, withscores=True
        ),
    )
    if not raw:
        return None

    # Members come back as bytes. They must be decoded here, not left for
    # the JSON layer: to_jsonable routes a dict with bytes keys through the
    # __dictpairs__/__bytes__ tagged encoding, which round-trips correctly
    # but silently stops matching the plain-object export shape the docs
    # describe. Same idiom as get_linked() and on_delete().
    edges = {
        (member.decode("utf-8") if isinstance(member, bytes) else str(member)): (
            float(score)
        )
        for member, score in raw
    }
    return {"edges": edges, "max_edges": int(field.max_edges)}

import_state(model_instance, field_name, state, **kwargs) classmethod

Restore this record's association edges after import.

Written as a raw DELETE + ZADD, never through link or strengthen: those apply relative adjustments and NX semantics, and cannot reproduce an absolute weight. Symmetric mirroring is deliberately NOT performed -- each record owns its own edge set, so a partner's mirror edge arrives with the partner record if it is in the export.

This REPLACES rather than merges. on_save never touches edge keys (CoOccurrenceField defines no on_save), so there is nothing to merge with except edges the destination accumulated on its own since the export was taken -- and under on_conflict="overwrite", whose contract is that the record is replaced wholesale, keeping those would leave a graph matching neither side.

Two normalizations to the DESTINATION's configuration are applied, and both are load-bearing rather than cosmetic:

  • weights are clamped to Defaults.CO_OCCURRENCE_WEIGHT_CAP, because propagate() depends on a contraction invariant that an over-cap weight would break -- BFS would stop decaying with hop count;
  • the set is truncated to the destination field's max_edges, keeping the highest weights, exactly as LINK_WITH_PRUNE_LUA does on the normal path.
Source code in src/popoto/fields/co_occurrence_field.py
@classmethod
def import_state(
    cls,
    model_instance: Any,
    field_name: str,
    state: Any,
    **kwargs: Any,
) -> None:
    """Restore this record's association edges after import.

    Written as a raw ``DELETE`` + ``ZADD``, never through ``link`` or
    ``strengthen``: those apply relative adjustments and NX semantics, and
    cannot reproduce an absolute weight. Symmetric mirroring is
    deliberately NOT performed -- each record owns its own edge set, so a
    partner's mirror edge arrives with the partner record if it is in the
    export.

    This REPLACES rather than merges. ``on_save`` never touches edge keys
    (``CoOccurrenceField`` defines no ``on_save``), so there is nothing to
    merge with except edges the destination accumulated on its own since
    the export was taken -- and under ``on_conflict="overwrite"``, whose
    contract is that the record is replaced wholesale, keeping those would
    leave a graph matching neither side.

    Two normalizations to the DESTINATION's configuration are applied, and
    both are load-bearing rather than cosmetic:

    * weights are clamped to ``Defaults.CO_OCCURRENCE_WEIGHT_CAP``, because
      ``propagate()`` depends on a contraction invariant that an over-cap
      weight would break -- BFS would stop decaying with hop count;
    * the set is truncated to the destination field's ``max_edges``,
      keeping the highest weights, exactly as ``LINK_WITH_PRUNE_LUA`` does
      on the normal path.
    """
    if not state:
        return None
    edges = state.get("edges")
    if not isinstance(edges, dict) or not edges:
        return None

    field = model_instance._meta.fields.get(field_name)
    if not isinstance(field, CoOccurrenceField):
        return None

    model_class = type(model_instance)
    try:
        pk = model_instance.db_key.redis_key
    except Exception:
        return None

    cap = Defaults.CO_OCCURRENCE_WEIGHT_CAP
    ranked = sorted(
        (
            (
                (
                    target.decode("utf-8")
                    if isinstance(target, bytes)
                    else str(target)
                ),
                min(float(weight), cap),
            )
            for target, weight in edges.items()
        ),
        key=lambda pair: pair[1],
        reverse=True,
    )[: max(1, int(field.max_edges))]

    backend = _graph_backend(model_class)
    if backend is not None:
        backend.graph_update(
            _spec(model_class),
            field_name,
            "replace",
            _rid(model_class, pk),
            None,
            None,
            edges=dict(ranked),
        )
        return None

    edge_key = field.get_edge_key(model_class, pk)
    get_REDIS_DB().delete(edge_key)
    get_REDIS_DB().zadd(edge_key, dict(ranked))
    return None

get_edge_key(model_class, pk)

Build the Redis key for a PK's edge sorted set.

Public API for external callers that need direct Redis access to a PK's edge set (e.g., bulk edge inspection, custom graph queries, monitoring). Prefer the higher-level methods (link, get_linked, propagate) for normal operations.

Pattern: $CoOcF:{ClassName}:{field_name}:{pk}

Parameters:

Name Type Description Default
model_class

The Model class (or instance).

required
pk

The primary key string.

required

Returns:

Name Type Description
str

The Redis key for this PK's edge sorted set.

Source code in src/popoto/fields/co_occurrence_field.py
def get_edge_key(self, model_class, pk):
    """Build the Redis key for a PK's edge sorted set.

    Public API for external callers that need direct Redis access to
    a PK's edge set (e.g., bulk edge inspection, custom graph queries,
    monitoring). Prefer the higher-level methods (link, get_linked,
    propagate) for normal operations.

    Pattern: $CoOcF:{ClassName}:{field_name}:{pk}

    Args:
        model_class: The Model class (or instance).
        pk: The primary key string.

    Returns:
        str: The Redis key for this PK's edge sorted set.
    """
    base_key = self.get_special_use_field_db_key(model_class, self.name)
    return base_key.redis_key + ":" + str(pk)

get_edge_key_prefix(model_class)

Build the Redis key prefix for BFS propagation.

Public API for external callers that need to scan or iterate over all edge sorted sets for a field (e.g., graph analytics, bulk cleanup).

Pattern: $CoOcF:{ClassName}:{field_name}:

Parameters:

Name Type Description Default
model_class

The Model class.

required

Returns:

Name Type Description
str

The key prefix (ending with colon).

Source code in src/popoto/fields/co_occurrence_field.py
def get_edge_key_prefix(self, model_class):
    """Build the Redis key prefix for BFS propagation.

    Public API for external callers that need to scan or iterate over
    all edge sorted sets for a field (e.g., graph analytics, bulk cleanup).

    Pattern: $CoOcF:{ClassName}:{field_name}:

    Args:
        model_class: The Model class.

    Returns:
        str: The key prefix (ending with colon).
    """
    base_key = self.get_special_use_field_db_key(model_class, self.name)
    return base_key.redis_key + ":"

Create a weighted edge between two PKs.

If symmetric=True, creates edges in both directions. Uses an atomic Lua script to handle ZADD + ZCARD + conditional pruning.

Parameters:

Name Type Description Default
model_class

The Model class.

required
source_pk

Source primary key string.

required
target_pk

Target primary key string.

required
initial_weight

Weight for the new edge. Default from Defaults.CO_OCCURRENCE_INITIAL_WEIGHT.

_UNSET
pipeline

Optional Redis pipeline (unused for Lua eval).

None

Returns:

Name Type Description
float

The weight of the edge (existing weight if already linked).

Raises:

Type Description
ValueError

If source_pk == target_pk (no self-loops), or if initial_weight exceeds Defaults.CO_OCCURRENCE_WEIGHT_CAP (would violate the contraction invariant).

Source code in src/popoto/fields/co_occurrence_field.py
def link(
    self,
    model_class,
    source_pk,
    target_pk,
    initial_weight=_UNSET,
    pipeline=None,
):
    """Create a weighted edge between two PKs.

    If symmetric=True, creates edges in both directions. Uses an atomic
    Lua script to handle ZADD + ZCARD + conditional pruning.

    Args:
        model_class: The Model class.
        source_pk: Source primary key string.
        target_pk: Target primary key string.
        initial_weight: Weight for the new edge. Default from
            ``Defaults.CO_OCCURRENCE_INITIAL_WEIGHT``.
        pipeline: Optional Redis pipeline (unused for Lua eval).

    Returns:
        float: The weight of the edge (existing weight if already linked).

    Raises:
        ValueError: If source_pk == target_pk (no self-loops), or if
            ``initial_weight`` exceeds ``Defaults.CO_OCCURRENCE_WEIGHT_CAP``
            (would violate the contraction invariant).
    """
    if initial_weight is _UNSET:
        initial_weight = Defaults.CO_OCCURRENCE_INITIAL_WEIGHT
    source_pk = str(source_pk)
    target_pk = str(target_pk)

    if source_pk == target_pk:
        raise ValueError("Cannot link a PK to itself (no self-loops)")
    if initial_weight > Defaults.CO_OCCURRENCE_WEIGHT_CAP:
        raise ValueError(
            f"initial_weight ({initial_weight}) exceeds "
            f"CO_OCCURRENCE_WEIGHT_CAP "
            f"({Defaults.CO_OCCURRENCE_WEIGHT_CAP}); edges above the "
            f"cap violate the per-hop contraction invariant used by "
            f"propagate()."
        )

    backend = _graph_backend(model_class)
    if backend is not None:
        return float(
            backend.graph_update(
                _spec(model_class),
                _name(self),
                "link",
                _rid(model_class, source_pk),
                _rid(model_class, target_pk),
                initial_weight,
                uow=_uow(pipeline, backend),
            )
        )

    source_key = self.get_edge_key(model_class, source_pk)
    result = run_lua(
        get_REDIS_DB(),
        LINK_WITH_PRUNE_LUA,
        1,
        source_key,
        target_pk,
        str(initial_weight),
        str(self.max_edges),
    )

    if self.symmetric:
        target_key = self.get_edge_key(model_class, target_pk)
        run_lua(
            get_REDIS_DB(),
            LINK_WITH_PRUNE_LUA,
            1,
            target_key,
            source_pk,
            str(initial_weight),
            str(self.max_edges),
        )

    return float(result)

strengthen(model_class, source_pk, target_pk, delta=0.05, pipeline=None)

Increase the weight of an existing edge.

Uses an atomic Lua script (STRENGTHEN_CLAMP_LUA) to read the current weight, add delta, and clamp at Defaults.CO_OCCURRENCE_WEIGHT_CAP so stored weights can never exceed the cap. This guarantees the per-hop contraction invariant used by propagate() (decay_per_hop * effective_edge_weight stays <= decay_per_hop * cap < 1 at default config).

Parameters:

Name Type Description Default
model_class

The Model class.

required
source_pk

Source primary key string.

required
target_pk

Target primary key string.

required
delta

Amount to increase weight by. Must be > 0. Default 0.05.

0.05
pipeline

Optional Redis pipeline.

None

Returns:

Name Type Description
float

The new (clamped) weight after increment, or None when called with a pipeline (execution deferred).

Raises:

Type Description
ValueError

If delta <= 0.

Source code in src/popoto/fields/co_occurrence_field.py
def strengthen(
    self,
    model_class,
    source_pk,
    target_pk,
    delta=0.05,
    pipeline=None,
):
    """Increase the weight of an existing edge.

    Uses an atomic Lua script (STRENGTHEN_CLAMP_LUA) to read the
    current weight, add delta, and clamp at
    ``Defaults.CO_OCCURRENCE_WEIGHT_CAP`` so stored weights can never
    exceed the cap. This guarantees the per-hop contraction invariant
    used by ``propagate()`` (``decay_per_hop * effective_edge_weight``
    stays <= ``decay_per_hop * cap`` < 1 at default config).

    Args:
        model_class: The Model class.
        source_pk: Source primary key string.
        target_pk: Target primary key string.
        delta: Amount to increase weight by. Must be > 0. Default 0.05.
        pipeline: Optional Redis pipeline.

    Returns:
        float: The new (clamped) weight after increment, or None when
            called with a pipeline (execution deferred).

    Raises:
        ValueError: If delta <= 0.
    """
    if delta <= 0:
        raise ValueError(f"delta must be > 0 (got {delta})")

    source_pk = str(source_pk)
    target_pk = str(target_pk)

    cap = Defaults.CO_OCCURRENCE_WEIGHT_CAP
    backend = _graph_backend(model_class)
    if backend is not None:
        # No EventStreamMixin entry: its stream is a Redis structure,
        # and Postgres pub/sub arrives in M5.
        uow = _uow(pipeline, backend)
        weight = backend.graph_update(
            _spec(model_class),
            _name(self),
            "strengthen",
            _rid(model_class, source_pk),
            _rid(model_class, target_pk),
            delta,
            uow=uow,
            cap=cap,
        )
        if pipeline and uow is None:
            return None  # a Redis pipeline: the queued call's reply
        return float(weight)

    source_key = self.get_edge_key(model_class, source_pk)
    db = pipeline if pipeline else get_REDIS_DB()
    new_weight = run_lua(
        db,
        STRENGTHEN_CLAMP_LUA,
        1,
        source_key,
        target_pk,
        str(delta),
        str(cap),
    )

    if self.symmetric:
        target_key = self.get_edge_key(model_class, target_pk)
        run_lua(
            db,
            STRENGTHEN_CLAMP_LUA,
            1,
            target_key,
            source_pk,
            str(delta),
            str(cap),
        )

    # EventStreamMixin: log strengthen event
    from .event_stream import EventStreamMixin

    if not pipeline and issubclass(model_class, EventStreamMixin):
        try:
            import time

            stream_name = getattr(
                model_class, "_stream_name", EventStreamMixin._stream_name
            )
            max_length = getattr(
                model_class,
                "_stream_max_length",
                EventStreamMixin._stream_max_length,
            )
            stream_key = f"stream:{stream_name}"
            partition_field = getattr(model_class, "_stream_partition_field", None)
            if partition_field:
                stream_key = f"{stream_key}:{source_pk}"
            entry = {
                "model": model_class.__name__,
                "pk": str(source_pk),
                "op": "strengthen",
                "ts": str(time.time()),
                "changed_fields": "",
                "source_pk": str(source_pk),
                "target_pk": str(target_pk),
                "delta": str(delta),
            }
            get_REDIS_DB().xadd(
                stream_key, entry, maxlen=max_length, approximate=True
            )
        except Exception:
            pass  # Best-effort, don't block strengthen

    if pipeline:
        return None  # Pipeline defers execution
    return float(new_weight)

Remove an edge between two PKs.

If symmetric=True, removes edges in both directions.

Parameters:

Name Type Description Default
model_class

The Model class.

required
source_pk

Source primary key string.

required
target_pk

Target primary key string.

required
pipeline

Optional Redis pipeline.

None
Source code in src/popoto/fields/co_occurrence_field.py
def unlink(self, model_class, source_pk, target_pk, pipeline=None):
    """Remove an edge between two PKs.

    If symmetric=True, removes edges in both directions.

    Args:
        model_class: The Model class.
        source_pk: Source primary key string.
        target_pk: Target primary key string.
        pipeline: Optional Redis pipeline.
    """
    source_pk = str(source_pk)
    target_pk = str(target_pk)

    backend = _graph_backend(model_class)
    if backend is not None:
        backend.graph_update(
            _spec(model_class),
            _name(self),
            "unlink",
            _rid(model_class, source_pk),
            _rid(model_class, target_pk),
            None,
            uow=_uow(pipeline, backend),
        )
        return None

    source_key = self.get_edge_key(model_class, source_pk)
    db = pipeline if pipeline else get_REDIS_DB()
    db.zrem(source_key, target_pk)

    if self.symmetric:
        target_key = self.get_edge_key(model_class, target_pk)
        db.zrem(target_key, source_pk)

weaken_all(model_class, pk, factor=None, pipeline=None)

Multiplicatively decay all edge weights for a PK.

Edges that fall below a threshold (factor * 0.01) after weakening are automatically pruned.

Parameters:

Name Type Description Default
model_class

The Model class.

required
pk

Primary key whose edges to weaken.

required
factor

Decay factor (0 < factor < 1). Defaults to self.decay_factor. factor=0 removes all edges.

None
pipeline

Optional Redis pipeline (unused for Lua eval).

None

Returns:

Name Type Description
int

Number of edges removed by pruning.

Raises:

Type Description
ValueError

If factor > 1 or factor < 0.

Source code in src/popoto/fields/co_occurrence_field.py
def weaken_all(self, model_class, pk, factor=None, pipeline=None):
    """Multiplicatively decay all edge weights for a PK.

    Edges that fall below a threshold (factor * 0.01) after weakening
    are automatically pruned.

    Args:
        model_class: The Model class.
        pk: Primary key whose edges to weaken.
        factor: Decay factor (0 < factor < 1). Defaults to self.decay_factor.
            factor=0 removes all edges.
        pipeline: Optional Redis pipeline (unused for Lua eval).

    Returns:
        int: Number of edges removed by pruning.

    Raises:
        ValueError: If factor > 1 or factor < 0.
    """
    if factor is None:
        factor = self.decay_factor

    if factor < 0 or factor > 1:
        raise ValueError(f"factor must be between 0 and 1 inclusive (got {factor})")

    pk = str(pk)
    backend = _graph_backend(model_class)
    if backend is not None:
        return int(
            backend.graph_update(
                _spec(model_class),
                _name(self),
                "weaken",
                _rid(model_class, pk),
                None,
                factor,
                uow=_uow(pipeline, backend),
            )
        )
    edge_key = self.get_edge_key(model_class, pk)

    if factor == 0:
        # Special case: remove all edges
        count = get_REDIS_DB().zcard(edge_key)
        get_REDIS_DB().delete(edge_key)
        return int(count)

    # Use threshold of 0.001 for pruning
    threshold = 0.001
    result = run_lua(
        get_REDIS_DB(),
        WEAKEN_ALL_LUA,
        1,
        edge_key,
        str(factor),
        str(threshold),
    )
    return int(result)

get_linked(model_class, pk, min_weight=0.01, limit=20)

Get linked PKs sorted by weight descending.

Parameters:

Name Type Description Default
model_class

The Model class.

required
pk

Primary key to get links for.

required
min_weight

Minimum weight threshold. Default 0.01.

0.01
limit

Maximum number of results. Default 20.

20

Returns:

Type Description

list[tuple[str, float]]: List of (pk, weight) tuples, sorted by weight descending.

Source code in src/popoto/fields/co_occurrence_field.py
def get_linked(self, model_class, pk, min_weight=0.01, limit=20):
    """Get linked PKs sorted by weight descending.

    Args:
        model_class: The Model class.
        pk: Primary key to get links for.
        min_weight: Minimum weight threshold. Default 0.01.
        limit: Maximum number of results. Default 20.

    Returns:
        list[tuple[str, float]]: List of (pk, weight) tuples,
            sorted by weight descending.
    """
    pk = str(pk)
    backend = _graph_backend(model_class)
    if backend is not None:
        # graph_expand at depth 1: the stored weights, unclamped, as the
        # scores (plan §1).
        return [
            (rid.canonical, score)
            for rid, score in backend.graph_expand(
                _spec(model_class),
                _name(self),
                [_rid(model_class, pk)],
                depth=1,
                decay_per_hop=1.0,
                threshold=min_weight,
                fanout=limit,
                mode="linked",
            )
        ]
    edge_key = self.get_edge_key(model_class, pk)

    # ZREVRANGEBYSCORE: highest to lowest, with score filter
    results = get_REDIS_DB().zrevrangebyscore(
        edge_key,
        "+inf",
        str(min_weight),
        start=0,
        num=limit,
        withscores=True,
    )

    return [
        (
            member.decode("utf-8") if isinstance(member, bytes) else member,
            float(score),
        )
        for member, score in results
    ]

propagate(model_class, seed_pks, depth=2, decay_per_hop=_UNSET, threshold=0.01)

BFS graph propagation with exponential weight decay per hop.

Traverses edges starting from seed PKs, applying multiplicative decay at each hop. When the same PK is reached via multiple paths, the maximum weight is kept.

Edge weights are clamped at Defaults.CO_OCCURRENCE_WEIGHT_CAP at read time (defense-in-depth) so pre-existing over-cap stored weights cannot amplify propagation. A runtime guard raises ValueError if cap * decay_per_hop >= 1.0 (misconfiguration that would amplify instead of decay).

Parameters:

Name Type Description Default
model_class

The Model class.

required
seed_pks

List of starting primary keys.

required
depth

Maximum BFS depth. Default 2. depth=0 returns seeds only.

2
decay_per_hop

Weight multiplier per hop. Default from Defaults.CO_OCCURRENCE_DECAY_PER_HOP.

_UNSET
threshold

Minimum propagated weight to continue. Default 0.01.

0.01

Returns:

Type Description

dict[str, float]: Mapping of discovered PKs to their propagated weights. Seeds are not included in results (except for depth=0).

Raises:

Type Description
ValueError

If CO_OCCURRENCE_WEIGHT_CAP * decay_per_hop >= 1.0 (contraction invariant violated; propagation would amplify).

Source code in src/popoto/fields/co_occurrence_field.py
def propagate(
    self,
    model_class,
    seed_pks,
    depth=2,
    decay_per_hop=_UNSET,
    threshold=0.01,
):
    """BFS graph propagation with exponential weight decay per hop.

    Traverses edges starting from seed PKs, applying multiplicative
    decay at each hop. When the same PK is reached via multiple paths,
    the maximum weight is kept.

    Edge weights are clamped at ``Defaults.CO_OCCURRENCE_WEIGHT_CAP``
    at read time (defense-in-depth) so pre-existing over-cap stored
    weights cannot amplify propagation. A runtime guard raises
    ``ValueError`` if ``cap * decay_per_hop >= 1.0`` (misconfiguration
    that would amplify instead of decay).

    Args:
        model_class: The Model class.
        seed_pks: List of starting primary keys.
        depth: Maximum BFS depth. Default 2. depth=0 returns seeds only.
        decay_per_hop: Weight multiplier per hop. Default from
            ``Defaults.CO_OCCURRENCE_DECAY_PER_HOP``.
        threshold: Minimum propagated weight to continue. Default 0.01.

    Returns:
        dict[str, float]: Mapping of discovered PKs to their propagated
            weights. Seeds are not included in results (except for depth=0).

    Raises:
        ValueError: If ``CO_OCCURRENCE_WEIGHT_CAP * decay_per_hop >= 1.0``
            (contraction invariant violated; propagation would amplify).
    """
    if decay_per_hop is _UNSET:
        decay_per_hop = Defaults.CO_OCCURRENCE_DECAY_PER_HOP
    # Runtime contraction guard: enforces cap * decay_per_hop < 1 so
    # that each hop strictly decays activation. Fires on
    # misconfiguration only (e.g. a future constants sweep raises
    # decay_per_hop above 1/cap); under current defaults
    # (1.0 * 0.5 = 0.5 < 1) this never raises.
    if Defaults.CO_OCCURRENCE_WEIGHT_CAP * decay_per_hop >= 1.0:
        raise ValueError(
            f"Contraction invariant violated: CO_OCCURRENCE_WEIGHT_CAP "
            f"({Defaults.CO_OCCURRENCE_WEIGHT_CAP}) * decay_per_hop "
            f"({decay_per_hop}) >= 1.0; propagation would amplify "
            f"instead of decay. Lower the cap or decay_per_hop."
        )
    if not seed_pks:
        return {}

    seed_pks = [str(pk) for pk in seed_pks]

    if depth == 0:
        return {pk: 1.0 for pk in seed_pks}

    backend = _graph_backend(model_class)
    if backend is not None:
        return {
            rid.canonical: score
            for rid, score in backend.graph_expand(
                _spec(model_class),
                _name(self),
                [_rid(model_class, pk) for pk in seed_pks],
                depth=depth,
                decay_per_hop=decay_per_hop,
                threshold=threshold,
                fanout=self.max_edges,
                cap=Defaults.CO_OCCURRENCE_WEIGHT_CAP,
            )
        }

    key_prefix = self.get_edge_key_prefix(model_class)

    result = run_lua(
        get_REDIS_DB(),
        PROPAGATE_BFS_LUA,
        1,
        key_prefix,
        json.dumps(seed_pks),
        str(depth),
        str(decay_per_hop),
        str(threshold),
        str(self.max_edges),
        str(Defaults.CO_OCCURRENCE_WEIGHT_CAP),
    )

    # Parse flat array [pk1, weight1, pk2, weight2, ...]
    scores = {}
    if result:
        for i in range(0, len(result), 2):
            pk = result[i]
            if isinstance(pk, bytes):
                pk = pk.decode("utf-8")
            weight = float(result[i + 1])
            scores[pk] = weight

    return scores

on_delete(model_instance, field_name, field_value, pipeline=None, **kwargs) classmethod

Clean up edges when a model instance is deleted.

Removes the instance's own edge sorted set AND removes it from all other instances' edge sorted sets via SCAN + ZREM.

Parameters:

Name Type Description Default
model_instance

The Model instance being deleted.

required
field_name

Name of this CoOccurrenceField.

required
field_value

Current field value (unused).

required
pipeline

Optional Redis pipeline.

None
**kwargs

Additional context.

{}
Source code in src/popoto/fields/co_occurrence_field.py
@classmethod
def on_delete(
    cls,
    model_instance,
    field_name,
    field_value,
    pipeline=None,
    **kwargs,
):
    """Clean up edges when a model instance is deleted.

    Removes the instance's own edge sorted set AND removes it from
    all other instances' edge sorted sets via SCAN + ZREM.

    Args:
        model_instance: The Model instance being deleted.
        field_name: Name of this CoOccurrenceField.
        field_value: Current field value (unused).
        pipeline: Optional Redis pipeline.
        **kwargs: Additional context.
    """
    field = model_instance._meta.fields.get(field_name)
    if not isinstance(field, CoOccurrenceField):
        return super().on_delete(
            model_instance, field_name, field_value, pipeline=pipeline, **kwargs
        )

    # Get this instance's PK from its redis key
    member_key = kwargs.get("saved_redis_key") or model_instance.db_key.redis_key

    # Get the edge key for this instance
    edge_key = field.get_edge_key(model_instance, member_key)

    if field.symmetric:
        # Get all linked PKs so we can remove reverse edges
        linked = get_REDIS_DB().zrange(edge_key, 0, -1)
        for target_pk in linked:
            if isinstance(target_pk, bytes):
                target_pk = target_pk.decode("utf-8")
            target_edge_key = field.get_edge_key(model_instance, target_pk)
            if pipeline:
                pipeline.zrem(target_edge_key, member_key)
            else:
                get_REDIS_DB().zrem(target_edge_key, member_key)

    # Delete this instance's edge sorted set
    if pipeline:
        pipeline.delete(edge_key)
    else:
        get_REDIS_DB().delete(edge_key)

    return super().on_delete(
        model_instance, field_name, field_value, pipeline=pipeline, **kwargs
    )