popoto.recipes.graph_traversal¶
popoto.recipes.graph_traversal
¶
graph_traversal — separable seed→expand stage for multi-hop retrieval.
Wraps the two existing association primitives (CoOccurrenceField and
Relationship) into a single, budget-bounded expansion step that
ContextAssembler can drop in wherever it currently calls
CoOccurrenceField.propagate() directly. Deliberately kept independent of
context_assembler.py's internals: everything here takes primitives
(model class, field objects/names, seed PK strings) and returns a plain
list[(pk, weight)] — the exact shape propagate() already returns, so
call sites are a pure conditional swap, not a rewrite (see issue #462).
No graph database, no Redis modules — only ZADD/ZRANGE (via
CoOccurrenceField, unchanged) and SRANDMEMBER (bounded-sample Set
reads for Relationship edges). Valkey-safe by construction.
Two things this module adds beyond the CoOccurrence-only graph arm already
shipped in ContextAssembler:
- RelationshipField edge expansion — walks a self-referential
Relationshipfield (a field onmodel_classpointing back tomodel_class) in both directions: forward (a node's own relationship value) and reverse (other nodes pointing at it, via the field's existing$RelationshipF:...index Set). Bounded per-hop fan-out viaSRANDMEMBER(a capped sample, never a fullSMEMBERSscan of a potentially large Set). - Confidence/decay-modulated hop admission — after co-occurrence and
relationship expansion are merged and capped to
max_candidates, each surviving candidate's weight is multiplied by its ownConfidenceField/decaying-field state (when configured), so a low-confidence or heavily decayed node is less likely to survive into the merged candidate set than a fresh, corroborated one.
Example
from popoto.recipes.graph_traversal import traverse
results = traverse( Memory, seed_pks=["Memory:abc", "Memory:def"], co_occurrence_field=Memory._meta.fields["associations"], relationship_field_names=["related_memory"], confidence_field_name="certainty", )
=> [("Memory:xyz", 0.42), ("Memory:qrs", 0.18), ...]¶
RELATIONSHIP_HOP_DECAY = 0.5
module-attribute
¶
Weight multiplier applied per relationship hop (weight ** hop),
matching CoOccurrenceField's default decay_per_hop so relationship- and
co-occurrence-derived edges are comparable in magnitude when merged.
RELATIONSHIP_HOP_FANOUT_LIMIT = 50
module-attribute
¶
Dual-purpose fan-out bound for relationship expansion:
- Max related PKs consumed per node per hop, per direction. Enforced via
SRANDMEMBER(key, n)— a bounded sample read at the Redis level, not a fullSMEMBERSfollowed by a Python-side slice, so a single high-degree node cannot force an unbounded Set transfer. - Max number of frontier nodes expanded per hop (
frontier[:fanout_limit]in :func:expand_relationships), bounding per-hop instance-load fan-out when a prior hop discovers many nodes.
GRAPH_TRAVERSAL_MAX_CANDIDATES = 200
module-attribute
¶
Candidate expansion is capped to this many PKs (by weight, descending) before the confidence/decay modulation pass, which is the only part of this module that pays per-candidate Redis round-trips (an instance load per candidate). This bounds worst-case traversal cost independent of graph fan-out.
ADMISSION_THRESHOLD = 0.01
module-attribute
¶
Minimum weight (before or after modulation) for a candidate to survive into the returned list. Matches CoOccurrenceField.propagate()'s default threshold.
expand_relationships(model_class, seed_pks, relationship_field_names, *, depth=2, decay_per_hop=RELATIONSHIP_HOP_DECAY, fanout_limit=RELATIONSHIP_HOP_FANOUT_LIMIT)
¶
BFS-style expansion over self-referential Relationship field(s).
Only Relationship fields declared on model_class whose model
is model_class itself are honored (self-referential edges) — a
relationship pointing at a different model class would surface
instances of the wrong type into a candidate set that
ContextAssembler treats as homogeneous. Any other configured field
name is skipped with a warning, not an error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Popoto Model class being traversed. |
required | |
seed_pks
|
Starting PK (redis_key) strings. |
required | |
relationship_field_names
|
Names of self-referential Relationship
field(s) on |
required | |
depth
|
Max hops. Default 2. |
2
|
|
decay_per_hop
|
Weight multiplier applied per hop. |
RELATIONSHIP_HOP_DECAY
|
|
fanout_limit
|
Max related PKs sampled per node per hop per direction. |
RELATIONSHIP_HOP_FANOUT_LIMIT
|
Returns:
| Type | Description |
|---|---|
|
dict[str, float]: Discovered PKs (excluding seeds) mapped to their |
|
|
propagated weight (max across all discovered paths). |
Source code in src/popoto/recipes/graph_traversal.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 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 | |
traverse(model_class, seed_pks, *, co_occurrence_field=None, relationship_field_names=None, depth=2, decay_per_hop=0.5, threshold=ADMISSION_THRESHOLD, max_candidates=GRAPH_TRAVERSAL_MAX_CANDIDATES, confidence_field_name=None, decay_field_name=None)
¶
Seed→expand traversal: co-occurrence BFS + relationship walk, merged, budget-capped, and confidence/decay-modulated.
Drop-in replacement for a bare CoOccurrenceField.propagate() call —
returns the same list[(pk, weight)] shape, so existing callers only
need to swap the call, not restructure downstream consumption (RRF
graph arm, co_occurrence_boost).
Cost is bounded independent of graph fan-out: expansion (co-occurrence
BFS + relationship walk) is pure sorted-set/set operations, capped to
max_candidates before any instance is loaded; only the
(optional) modulation pass pays per-candidate Redis round-trips, and
only for the capped set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Popoto Model class. |
required | |
seed_pks
|
Seed PK (redis_key) strings from the upstream retrieval arm(s) (BM25/vector/composite). |
required | |
co_occurrence_field
|
A |
None
|
|
relationship_field_names
|
List of self-referential |
None
|
|
depth
|
Max hops for both expansion sources. Default 2. |
2
|
|
decay_per_hop
|
Weight multiplier per hop (co-occurrence and relationship expansion both use this constant so their magnitudes are comparable when merged). |
0.5
|
|
threshold
|
Minimum weight to survive expansion/modulation. |
ADMISSION_THRESHOLD
|
|
max_candidates
|
Cap on merged candidates before modulation. |
GRAPH_TRAVERSAL_MAX_CANDIDATES
|
|
confidence_field_name
|
Optional |
None
|
|
decay_field_name
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
|
list[tuple[str, float]]: Discovered PKs (excluding seeds) with |
|
|
their final weight, sorted descending. Empty list on no signal or |
|
|
on any internal failure (logs a warning, never raises). |
Source code in src/popoto/recipes/graph_traversal.py
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 | |