memory / graph.py — GraphMemory
SQLite-persisted knowledge graph mirrored into NetworkX for spreading-activation retrieval. Temporal triplet versioning handles belief updates.
Storage
- SQLite at
memory_dir/knowledge_graph.db. - In-memory
networkx.MultiDiGraphrebuilt at startup viainitialize_graph().
Schema
| Column | Type | Notes |
|---|---|---|
| subject / predicate / object | TEXT | UNIQUE composite key. Subjects/objects lowercased; predicates uppercased. |
| timestamp | REAL | Last-touched epoch. |
| weight | REAL | Reinforcement counter. |
| valid_from | REAL | Creation time. |
| valid_until | REAL nullable | NULL until superseded. |
Indexes on subject and object.
API
| Method | Purpose |
|---|---|
add_triplets(triplets) -> int | Bulk insert / reinforce. Functional predicates (WORKS_AT, LIVES_IN, DRIVES, …) auto-expire prior values. |
delete_by_target(target) | Substring match deletion. |
wipe_all() | Truncate. |
get_recent_triplets(limit) | Most recent edges. |
get_expired_triplets(subject, limit) | Superseded facts. |
execute_graph_compression(merges) | Merge synonym nodes (line 216-266). |
get_neighborhood(words, global_limit) | Spreading-activation BFS retrieval. |
Spreading-activation retrieval
- Word-to-node fuzzy match: exact → substring →
difflib.get_close_matches. - 3-hop BFS from each seed.
- Score paths by sum of edge weights.
- Format winners as
(subject)-[PREDICATE]-> (object) -[P2]-> (target).
Functional vs. non-functional predicates
One-to-one predicates (WORKS_AT, LIVES_IN, DRIVES) auto-expire old values when a new fact arrives. Many-to-many predicates (LIKES, KNOWS, HAS) accumulate.
Concurrency
threading.RLock guards both SQLite and the networkx mirror. initialize_graph() rebuilds the entire mirror from disk.