diff --git a/src/graph/__init__.py b/src/graph/__init__.py new file mode 100644 index 0000000..a0e26cb --- /dev/null +++ b/src/graph/__init__.py @@ -0,0 +1,23 @@ +""" +Graph module - Knowledge graph implementation for Hermes Agent. + +Provides: +- GraphNode, GraphEdge data models aligned with Distilled model +- GraphBuilder for constructing graphs from Distilled records +- GraphQuery for BFS navigation and similarity calculations +- LazyIndexer for efficient lookups +""" +from .models import GraphNode, GraphEdge, NodeType, EdgeType +from .builder import GraphBuilder +from .query import GraphQuery +from .indexer import LazyIndexer + +__all__ = [ + 'GraphNode', + 'GraphEdge', + 'NodeType', + 'EdgeType', + 'GraphBuilder', + 'GraphQuery', + 'LazyIndexer', +] diff --git a/src/graph/builder.py b/src/graph/builder.py new file mode 100644 index 0000000..83c329a --- /dev/null +++ b/src/graph/builder.py @@ -0,0 +1,171 @@ +""" +GraphBuilder - constructs knowledge graphs from Distilled objects. +""" +import hashlib +import networkx as nx +from pathlib import Path +from typing import List, Optional +import json + +from .models import GraphNode, GraphEdge, NodeType, EdgeType + + +class GraphBuilder: + """Builds and maintains a NetworkX-based knowledge graph from Distilled records. + + Entities are the primary node source from Distilled.facts field. + """ + + def __init__(self, storage_dir: Path = None): + self.storage_dir = storage_dir or Path.home() / '.memory-fabric' / 'hermes-main' / 'graph' + self.storage_dir.mkdir(parents=True, exist_ok=True) + self._graph: Optional[nx.DiGraph] = None + + @property + def graph(self) -> nx.DiGraph: + """Lazy-load graph from NetworkX.""" + if self._graph is None: + self._graph = nx.DiGraph() + return self._graph + + def from_distilled(self, distilled_list: List) -> nx.DiGraph: + """Build graph from a list of Distilled objects. + + Primary entity source: Distilled.facts + Also processes Distilled.entities for cross-reference. + """ + for distilled in distilled_list: + self._add_distilled(distilled) + return self.graph + + def _add_distilled(self, distilled) -> None: + """Add a single Distilled record to the graph.""" + facts = getattr(distilled, 'facts', []) or [] + entities = getattr(distilled, 'entities', []) or [] + distilled_id = distilled.id + episode_id = getattr(distilled, 'episode_id', '') + confidence = getattr(distilled, 'confidence', 0.5) + importance = getattr(distilled, 'importance', 0) + + # Create nodes from facts (primary entity source) + fact_nodes = [] + for fact in facts: + node = GraphNode.from_fact( + fact=fact, + distilled_id=distilled_id, + episode_id=episode_id, + confidence=confidence, + importance=importance, + ) + self._add_node(node) + fact_nodes.append(node) + + # Create nodes from entities + entity_nodes = [] + for entity in entities: + node = GraphNode.from_entity( + entity=entity, + distilled_id=distilled_id, + episode_id=episode_id, + confidence=confidence, + importance=importance, + ) + self._add_node(node) + entity_nodes.append(node) + + # Create edges: fact -> entity relationships + for fact_node in fact_nodes: + for entity_node in entity_nodes: + if fact_node.label.lower() != entity_node.label.lower(): + edge = GraphEdge.create_relation( + source_id=fact_node.id, + target_id=entity_node.id, + relation=EdgeType.RELATES_TO, + distilled_id=distilled_id, + ) + self._add_edge(edge) + + # Create inter-entity edges based on co-occurrence in same Distilled + self._create_cooccurrence_edges(fact_nodes + entity_nodes, distilled_id) + + def _create_cooccurrence_edges(self, nodes: List[GraphNode], distilled_id: str) -> None: + """Create edges between nodes that co-occur in the same Distilled.""" + for i, node_a in enumerate(nodes): + for node_b in nodes[i + 1:]: + if node_a.id != node_b.id: + edge = GraphEdge.create_relation( + source_id=node_a.id, + target_id=node_b.id, + relation=EdgeType.SIMILAR_TO, + distilled_id=distilled_id, + weight=0.8, # Co-occurrence has moderate weight + ) + self._add_edge(edge) + + def _add_node(self, node: GraphNode) -> None: + """Add or update a node in the graph.""" + self.graph.add_node(node.id, **node.to_dict()) + + def _add_edge(self, edge: GraphEdge) -> None: + """Add or update an edge in the graph.""" + if not self.graph.has_edge(edge.source, edge.target): + self.graph.add_edge(edge.source, edge.target, **edge.to_dict()) + + def add_distilled(self, distilled) -> None: + """Add a single Distilled to the graph (incremental update).""" + self._add_distilled(distilled) + + def remove_distilled(self, distilled_id: str) -> None: + """Remove all nodes/edges associated with a Distilled.""" + nodes_to_remove = [ + n for n, d in self.graph.nodes(data=True) + if d.get('distilled_id') == distilled_id + ] + self.graph.remove_nodes_from(nodes_to_remove) + + def snapshot(self) -> None: + """Persist graph state to JSONL files.""" + nodes_path = self.storage_dir / 'nodes.jsonl' + edges_path = self.storage_dir / 'edges.jsonl' + + # Write nodes + with open(nodes_path, 'w') as f: + for node_id, data in self.graph.nodes(data=True): + record = {'node_id': node_id, **data} + f.write(json.dumps(record) + '\n') + + # Write edges + with open(edges_path, 'w') as f: + for u, v, data in self.graph.edges(data=True): + record = {'source': u, 'target': v, **data} + f.write(json.dumps(record) + '\n') + + def load_snapshot(self) -> None: + """Load graph state from JSONL files.""" + nodes_path = self.storage_dir / 'nodes.jsonl' + edges_path = self.storage_dir / 'edges.jsonl' + + if not nodes_path.exists() or not edges_path.exists(): + return + + self._graph = nx.DiGraph() + + # Load nodes + with open(nodes_path, 'r') as f: + for line in f: + record = json.loads(line) + node_id = record.pop('node_id') + self.graph.add_node(node_id, **record) + + # Load edges + with open(edges_path, 'r') as f: + for line in f: + record = json.loads(line) + source = record.pop('source') + target = record.pop('target') + self.graph.add_edge(source, target, **record) + + def clear(self) -> None: + """Clear the graph.""" + self._graph = None + self._graph = nx.DiGraph() diff --git a/src/graph/indexer.py b/src/graph/indexer.py new file mode 100644 index 0000000..28c3ada --- /dev/null +++ b/src/graph/indexer.py @@ -0,0 +1,149 @@ +""" +LazyIndexer - Lazy loading index for graph nodes and efficient lookup. +""" +import json +import os +import networkx as nx +from pathlib import Path +from typing import Dict, List, Set, Optional +from collections import defaultdict +import hashlib + + +class LazyIndexer: + """Lazy-loading index for efficient graph queries. + + Builds indexes on-demand rather than eagerly to reduce startup time. + """ + + def __init__(self, storage_dir: Path = None): + self.storage_dir = storage_dir or Path.home() / '.memory-fabric' / 'hermes-main' / 'graph' + self.storage_dir.mkdir(parents=True, exist_ok=True) + + # Lazy-built indexes + self._label_index: Dict[str, List[str]] = {} + self._type_index: Dict[str, Set[str]] = defaultdict(set) + self._episode_index: Dict[str, List[str]] = {} + self._distilled_index: Dict[str, List[str]] = {} + + self._index_built = False + + def _ensure_index(self) -> None: + """Ensure all indexes are built before access.""" + if self._index_built: + return + self.build_indexes() + + def build_indexes(self, graph: nx.DiGraph = None) -> None: + """Build all indexes from the graph.""" + if graph is None: + return + + self._label_index.clear() + self._type_index.clear() + self._episode_index.clear() + self._distilled_index.clear() + + for node_id, data in graph.nodes(data=True): + label = data.get('label', '') + node_type = data.get('type', '') + episode_id = data.get('episode_id', '') + distilled_id = data.get('distilled_id', '') + + # Label index + if label: + if label not in self._label_index: + self._label_index[label] = [] + self._label_index[label].append(node_id) + + # Type index + if node_type: + self._type_index[node_type].add(node_id) + + # Episode index + if episode_id: + if episode_id not in self._episode_index: + self._episode_index[episode_id] = [] + self._episode_index[episode_id].append(node_id) + + # Distilled index + if distilled_id: + if distilled_id not in self._distilled_index: + self._distilled_index[distilled_id] = [] + self._distilled_index[distilled_id].append(node_id) + + self._index_built = True + + def invalidate(self) -> None: + """Invalidate all indexes, forcing rebuild on next access.""" + self._index_built = False + + def lookup_by_label(self, label: str) -> List[str]: + """Find node IDs by exact label match.""" + self._ensure_index() + return self._label_index.get(label, []) + + def lookup_by_label_prefix(self, prefix: str) -> List[str]: + """Find node IDs by label prefix.""" + self._ensure_index() + results = [] + for label, node_ids in self._label_index.items(): + if label.startswith(prefix): + results.extend(node_ids) + return results + + def lookup_by_type(self, node_type: str) -> Set[str]: + """Find all node IDs of a given type.""" + self._ensure_index() + return self._type_index.get(node_type, set()).copy() + + def lookup_by_episode(self, episode_id: str) -> List[str]: + """Find all node IDs associated with an episode.""" + self._ensure_index() + return self._episode_index.get(episode_id, []) + + def lookup_by_distilled(self, distilled_id: str) -> List[str]: + """Find all node IDs associated with a Distilled record.""" + self._ensure_index() + return self._distilled_index.get(distilled_id, []) + + def search(self, query: str, limit: int = 20) -> List[tuple]: + """Full-text search across node labels.""" + self._ensure_index() + query_lower = query.lower() + results = [] + + for label, node_ids in self._label_index.items(): + if query_lower in label.lower(): + for node_id in node_ids: + results.append((node_id, label)) + + results.sort(key=lambda x: len(x[1])) + return results[:limit] + + def save_index(self) -> None: + """Persist indexes to disk.""" + index_path = self.storage_dir / 'index.json' + data = { + 'label_index': dict(self._label_index), + 'type_index': {k: list(v) for k, v in self._type_index.items()}, + 'episode_index': self._episode_index, + 'distilled_index': self._distilled_index, + } + with open(index_path, 'w') as f: + json.dump(data, f) + + def load_index(self) -> None: + """Load indexes from disk.""" + index_path = self.storage_dir / 'index.json' + if not index_path.exists(): + return + + with open(index_path, 'r') as f: + data = json.load(f) + + self._label_index = data.get('label_index', {}) + self._type_index = {k: set(v) for k, v in data.get('type_index', {}).items()} + self._episode_index = data.get('episode_index', {}) + self._distilled_index = data.get('distilled_index', {}) + self._index_built = True diff --git a/src/graph/models.py b/src/graph/models.py new file mode 100644 index 0000000..94bd897 --- /dev/null +++ b/src/graph/models.py @@ -0,0 +1,141 @@ +""" +Graph data models aligned with Distilled model schema. +""" +from dataclasses import dataclass, field +from datetime import datetime +from typing import Optional +from enum import Enum + + +class NodeType(str, Enum): + ENTITY = "entity" + FACT = "fact" + EPISODE = "episode" + PATTERN = "pattern" + + +class EdgeType(str, Enum): + RELATES_TO = "relates_to" + DERIVED_FROM = "derived_from" + CONTAINS = "contains" + SIMILAR_TO = "similar_to" + + +@dataclass +class GraphNode: + """Represents a node in the knowledge graph. + + Aligned with Distilled model - facts/entities become graph nodes. + """ + id: str + type: NodeType + label: str + properties: dict = field(default_factory=dict) + + # Alignment with Distilled + distilled_id: Optional[str] = None # Reference to source Distilled + episode_id: Optional[str] = None + confidence: float = 0.5 + importance: int = 0 + created_at: datetime = field(default_factory=datetime.now) + updated_at: datetime = field(default_factory=datetime.now) + + def to_dict(self) -> dict: + return { + 'id': self.id, + 'type': self.type.value, + 'label': self.label, + 'properties': self.properties, + 'distilled_id': self.distilled_id, + 'episode_id': self.episode_id, + 'confidence': self.confidence, + 'importance': self.importance, + 'created_at': self.created_at.isoformat(), + 'updated_at': self.updated_at.isoformat(), + } + + @classmethod + def from_dict(cls, d: dict) -> 'GraphNode': + d = d.copy() + d['type'] = NodeType(d['type']) + d['created_at'] = datetime.fromisoformat(d['created_at']) + d['updated_at'] = datetime.fromisoformat(d['updated_at']) + return cls(**d) + + @classmethod + def from_fact(cls, fact: str, distilled_id: str, episode_id: str, + confidence: float = 0.5, importance: int = 0) -> 'GraphNode': + """Create a GraphNode from a Distilled.facts entry.""" + return cls( + id=f"fact:{distilled_id}:{hash(fact)}", + type=NodeType.FACT, + label=fact, + properties={'source': 'distilled_fact'}, + distilled_id=distilled_id, + episode_id=episode_id, + confidence=confidence, + importance=importance, + ) + + @classmethod + def from_entity(cls, entity: str, distilled_id: str, episode_id: str, + confidence: float = 0.5, importance: int = 0) -> 'GraphNode': + """Create a GraphNode from a Distilled.entities entry.""" + return cls( + id=f"entity:{distilled_id}:{hash(entity)}", + type=NodeType.ENTITY, + label=entity, + properties={'source': 'distilled_entity'}, + distilled_id=distilled_id, + episode_id=episode_id, + confidence=confidence, + importance=importance, + ) + + +@dataclass +class GraphEdge: + """Represents a directed edge in the knowledge graph.""" + id: str + source: str # Source node ID + target: str # Target node ID + relation: EdgeType + properties: dict = field(default_factory=dict) + + # Context + distilled_id: Optional[str] = None + weight: float = 1.0 + created_at: datetime = field(default_factory=datetime.now) + + def to_dict(self) -> dict: + return { + 'id': self.id, + 'source': self.source, + 'target': self.target, + 'relation': self.relation.value, + 'properties': self.properties, + 'distilled_id': self.distilled_id, + 'weight': self.weight, + 'created_at': self.created_at.isoformat(), + } + + @classmethod + def from_dict(cls, d: dict) -> 'GraphEdge': + d = d.copy() + d['relation'] = EdgeType(d['relation']) + d['created_at'] = datetime.fromisoformat(d['created_at']) + return cls(**d) + + @classmethod + def create_relation(cls, source_id: str, target_id: str, + relation: EdgeType, distilled_id: str = None, + weight: float = 1.0) -> 'GraphEdge': + """Create a relationship edge between two nodes.""" + return cls( + id=f"edge:{source_id}:{relation.value}:{target_id}", + source=source_id, + target=target_id, + relation=relation, + distilled_id=distilled_id, + weight=weight, + ) diff --git a/src/graph/query.py b/src/graph/query.py new file mode 100644 index 0000000..13156b5 --- /dev/null +++ b/src/graph/query.py @@ -0,0 +1,137 @@ +""" +GraphQuery - Graph traversal and analysis operations. +""" +import time +import networkx as nx +from collections import deque +from typing import List, Dict, Set, Tuple, Optional + +from .models import NodeType, EdgeType + + +class GraphQuery: + """Graph query operations optimized for 3-hop queries < 200ms.""" + + def __init__(self, graph: nx.DiGraph): + self.graph = graph + + def bfs_n_hops(self, start_node_id: str, max_hops: int = 3) -> Dict[int, Set[str]]: + """BFS multi-hop navigation from a starting node. + + Returns dict mapping hop_level -> set of node_ids reached. + Performance target: 3-hop query < 200ms + """ + start_time = time.time() + + if start_node_id not in self.graph: + return {} + + result: Dict[int, Set[str]] = {0: {start_node_id}} + visited: Set[str] = {start_node_id} + queue = deque([(start_node_id, 0)]) + + while queue: + current, depth = queue.popleft() + + if depth >= max_hops: + continue + + for neighbor in self.graph.neighbors(current): + if neighbor not in visited: + visited.add(neighbor) + if depth + 1 not in result: + result[depth + 1] = set() + result[depth + 1].add(neighbor) + queue.append((neighbor, depth + 1)) + + elapsed = (time.time() - start_time) * 1000 + if elapsed > 200: + import warnings + warnings.warn(f"BFS query took {elapsed:.1f}ms, exceeds 200ms target") + + return result + + def find_path(self, source: str, target: str, max_length: int = 3) -> List[List[str]]: + """Find all paths between source and target within max_length hops.""" + try: + return list(nx.all_simple_paths(self.graph, source, target, cutoff=max_length)) + except (nx.NodeNotFound, nx.NetworkXNoPath): + return [] + + def degree_centrality(self, nodes: List[str] = None) -> Dict[str, float]: + """Calculate degree centrality for specified nodes or all nodes.""" + if nodes: + subgraph = self.graph.subgraph(nodes) + centrality = nx.degree_centrality(subgraph) + n = len(self.graph) + if n > 1: + return {k: v * (n - 1) / (n - 1) for k, v in centrality.items()} + return centrality + return nx.degree_centrality(self.graph) + + def jaccard_similarity(self, node_a: str, node_b: str) -> float: + """Calculate Jaccard similarity between two nodes based on neighbors.""" + if node_a not in self.graph or node_b not in self.graph: + return 0.0 + + neighbors_a = set(self.graph.neighbors(node_a)) + neighbors_b = set(self.graph.neighbors(node_b)) + + if not neighbors_a or not neighbors_b: + return 0.0 + + intersection = len(neighbors_a & neighbors_b) + union = len(neighbors_a | neighbors_b) + + return intersection / union if union > 0 else 0.0 + + def get_node_neighbors(self, node_id: str, edge_type: EdgeType = None) -> Set[str]: + """Get direct neighbors of a node, optionally filtered by edge type.""" + if node_id not in self.graph: + return set() + + neighbors = set(self.graph.neighbors(node_id)) + + if edge_type is None: + return neighbors + + filtered = set() + for neighbor in neighbors: + edge_data = self.graph.edges[node_id, neighbor] + if edge_data.get('relation') == edge_type.value: + filtered.add(neighbor) + + return filtered + + def get_subgraph(self, node_ids: List[str], depth: int = 1) -> nx.DiGraph: + """Get a subgraph containing nodes and their N-hop neighborhood.""" + nodes_visited = set(node_ids) + queue = deque(node_ids) + + for _ in range(depth): + for _ in range(len(queue)): + current = queue.popleft() + for neighbor in self.graph.neighbors(current): + if neighbor not in nodes_visited: + nodes_visited.add(neighbor) + queue.append(neighbor) + + return self.graph.subgraph(nodes_visited).copy() + + def common_neighbors(self, node_a: str, node_b: str) -> Set[str]: + """Get common neighbors between two nodes.""" + neighbors_a = set(self.graph.neighbors(node_a)) + neighbors_b = set(self.graph.neighbors(node_b)) + return neighbors_a & neighbors_b + + def node_importance(self, node_id: str) -> float: + """Calculate importance score for a node based on degree and PageRank.""" + if node_id not in self.graph: + return 0.0 + + degree = self.graph.degree(node_id) + node_data = self.graph.nodes[node_id] + confidence = node_data.get('confidence', 0.5) + importance = node_data.get('importance', 0) + + return (degree * confidence) + importance diff --git a/src/peer/__init__.py b/src/peer/__init__.py new file mode 100644 index 0000000..10ef355 --- /dev/null +++ b/src/peer/__init__.py @@ -0,0 +1,61 @@ +""" +Peer Representation module. + +Implements three-step inference for peer preference learning: +- Explicit: Direct user preferences +- Deductive: Logical inference from behavior +- Inductive: Pattern-based discovery + +With tier-based decay management. +""" + +from .models import ( + PeerRepr, + Tier, + ExplicitPreference, + DeducedPreference, + InducedPreference, +) + +from .inference import ( + ThreeStepInferenceEngine, + ExplicitInference, + DeductiveInference, + InductiveInference, + InferenceContext, +) + +from .decay import ( + DecayCalculator, + DecayResult, + TierClassifier, + PeerDecayManager, + apply_decay_to_peer, + get_tier_for_peer, + DECAY_RATE, + MIN_SCORE, +) + +__all__ = [ + # Models + "PeerRepr", + "Tier", + "ExplicitPreference", + "DeducedPreference", + "InducedPreference", + # Inference + "ThreeStepInferenceEngine", + "ExplicitInference", + "DeductiveInference", + "InductiveInference", + "InferenceContext", + # Decay + "DecayCalculator", + "DecayResult", + "TierClassifier", + "PeerDecayManager", + "apply_decay_to_peer", + "get_tier_for_peer", + "DECAY_RATE", + "MIN_SCORE", +] diff --git a/src/peer/decay.py b/src/peer/decay.py new file mode 100644 index 0000000..020bc9e --- /dev/null +++ b/src/peer/decay.py @@ -0,0 +1,286 @@ +""" +Linear decay and tier-based confidence adjustment. + +Decay Formula: score = max(0.1, 1.0 - days * 0.015) + +Tiers: +- Core: Never decays, highest confidence +- Active: Normal decay +- Passive: Faster decay +- Deprecated: Marked for removal +""" + +from dataclasses import dataclass +from datetime import datetime, timedelta +from typing import Dict, Optional + +from .models import PeerRepr, Tier + + +# Decay parameters +DECAY_RATE = 0.015 # 1.5% decay per day +MIN_SCORE = 0.1 # Minimum score after decay +CORE_DECAY_MULTIPLIER = 0.0 # Core tier doesn't decay + + +@dataclass +class DecayResult: + """Result of applying decay to a preference.""" + original_score: float + decayed_score: float + days_elapsed: float + decay_applied: float + + +class DecayCalculator: + """ + Calculates decayed scores based on time and tier. + + Formula: score = max(MIN_SCORE, initial_score * (1.0 - days * DECAY_RATE)) + + For core tier, scores never decay. + """ + + def __init__(self, decay_rate: float = DECAY_RATE, min_score: float = MIN_SCORE): + self.decay_rate = decay_rate + self.min_score = min_score + + def calculate(self, initial_score: float, days: float, tier: Tier) -> float: + """ + Calculate decayed score. + + Args: + initial_score: Original score (0-1) + days: Number of days since last update + tier: Peer's tier classification + + Returns: + Decayed score, minimum 0.1 + """ + # Core tier never decays + if tier == Tier.CORE: + return initial_score + + # Calculate decay factor + decay_factor = days * self.decay_rate + + # For passive tier, decay 50% faster + if tier == Tier.PASSIVE: + decay_factor *= 1.5 + + # For deprecated tier, decay 100% faster (but still respect minimum) + elif tier == Tier.DEPRECATED: + decay_factor *= 2.0 + + # Apply decay: score = initial * (1 - decay_factor) + decayed = initial_score * (1.0 - decay_factor) + + return max(self.min_score, decayed) + + def calculate_result(self, initial_score: float, days: float, tier: Tier) -> DecayResult: + """Calculate decay with full details.""" + decayed = self.calculate(initial_score, days, tier) + decay_applied = initial_score - decayed + + return DecayResult( + original_score=initial_score, + decayed_score=decayed, + days_elapsed=days, + decay_applied=decay_applied + ) + + +class TierClassifier: + """ + Classifies peers into tiers based on activity and confidence. + """ + + # Activity thresholds (actions per week) + CORE_ACTIVITY_THRESHOLD = 50 # Very high activity + ACTIVE_ACTIVITY_THRESHOLD = 10 # Normal activity + PASSIVE_ACTIVITY_THRESHOLD = 2 # Low activity + + # Confidence thresholds + CORE_CONFIDENCE_THRESHOLD = 0.85 + ACTIVE_CONFIDENCE_THRESHOLD = 0.5 + + @classmethod + def classify(cls, peer: PeerRepr, activity_count: int = 0, + days_since_activity: int = 0) -> Tier: + """ + Classify peer into appropriate tier. + + Args: + peer: Peer representation + activity_count: Number of recent activities + days_since_activity: Days since last activity + + Returns: + Appropriate Tier classification + """ + # Check for core tier + if activity_count >= cls.CORE_ACTIVITY_THRESHOLD: + return Tier.CORE + + # Deprecated if too long inactive + if days_since_activity >= 180: # 6 months + return Tier.DEPRECATED + + # Check confidence levels + if peer.final_confidence >= cls.CORE_CONFIDENCE_THRESHOLD: + return Tier.CORE + + # Check activity levels + if activity_count >= cls.ACTIVE_ACTIVITY_THRESHOLD: + return Tier.ACTIVE + + if activity_count >= cls.PASSIVE_ACTIVITY_THRESHOLD: + return Tier.PASSIVE + + return Tier.DEPRECATED + + @classmethod + def should_upgrade(cls, peer: PeerRepr, activity_count: int) -> bool: + """Check if peer should be upgraded to a higher tier.""" + current = peer.tier + + # Passive can upgrade to Active + if current == Tier.PASSIVE and activity_count >= cls.ACTIVE_ACTIVITY_THRESHOLD: + return True + + # Active can upgrade to Core + if current == Tier.ACTIVE and activity_count >= cls.CORE_ACTIVITY_THRESHOLD: + return True + + return False + + @classmethod + def should_downgrade(cls, peer: PeerRepr, days_inactive: int) -> bool: + """Check if peer should be downgraded.""" + current = peer.tier + + # Core never downgrades automatically + if current == Tier.CORE: + return False + + # Long inactivity triggers downgrade + if days_inactive >= 90: # 3 months + return True + + return False + + +class PeerDecayManager: + """ + Manages decay application for peer representations. + """ + + def __init__(self): + self.calculator = DecayCalculator() + self.classifier = TierClassifier() + + def apply_decay(self, peer: PeerRepr, + activity_count: int = 0, + days_since_activity: int = 0) -> PeerRepr: + """ + Apply tier-based decay to all preferences in a peer. + + Args: + peer: PeerRepr to decay + activity_count: Recent activity count + days_since_activity: Days since last activity + + Returns: + Peer with decayed preferences + """ + # First update tier if needed + new_tier = self.classifier.classify(peer, activity_count, days_since_activity) + peer.tier = new_tier + + # Calculate days since last update + days = peer.days_since_update + + # Decay explicit preferences + for item_id, pref in list(peer.explicit_prefs.items()): + new_score = self.calculator.calculate(pref.score, days, peer.tier) + pref.score = new_score + + # Decay deductive preferences + for item_id, pref in list(peer.deduced_prefs.items()): + new_score = self.calculator.calculate(pref.score, days, peer.tier) + pref.score = new_score + + # Decay inductive preferences + for item_id, pref in list(peer.induced_prefs.items()): + new_score = self.calculator.calculate(pref.score, days, peer.tier) + pref.score = new_score + + # Update decay timestamp + peer.last_decay_update = datetime.now() + + return peer + + def get_decay_report(self, peer: PeerRepr) -> Dict: + """Generate detailed decay report for a peer.""" + days = peer.days_since_update + + explicit_diffs = [] + for item_id, pref in peer.explicit_prefs.items(): + result = self.calculator.calculate_result(pref.score, days, peer.tier) + explicit_diffs.append({ + "item_id": item_id, + "original": result.original_score, + "decayed": result.decayed_score, + "decay_applied": result.decay_applied + }) + + deductive_diffs = [] + for item_id, pref in peer.deduced_prefs.items(): + result = self.calculator.calculate_result(pref.score, days, peer.tier) + deductive_diffs.append({ + "item_id": item_id, + "original": result.original_score, + "decayed": result.decayed_score, + "decay_applied": result.decay_applied + }) + + inductive_diffs = [] + for item_id, pref in peer.induced_prefs.items(): + result = self.calculator.calculate_result(pref.score, days, peer.tier) + inductive_diffs.append({ + "item_id": item_id, + "original": result.original_score, + "decayed": result.decayed_score, + "decay_applied": result.decay_applied + }) + + return { + "peer_id": peer.peer_id, + "tier": peer.tier.value, + "days_since_update": days, + "final_confidence": peer.final_confidence, + "explicit_prefs": explicit_diffs, + "deduced_prefs": deductive_diffs, + "induced_prefs": inductive_diffs + } + + +def apply_decay_to_peer(peer: PeerRepr, + activity_count: int = 0, + days_since_activity: int = 0) -> PeerRepr: + """ + Convenience function to apply decay to a peer. + + Formula: score = max(0.1, score * (1.0 - days * 0.015)) + + For core tier, scores never decay. + """ + manager = PeerDecayManager() + return manager.apply_decay(peer, activity_count, days_since_activity) + + +def get_tier_for_peer(peer: PeerRepr, + activity_count: int = 0, + days_since_activity: int = 0) -> Tier: + """Convenience function to get tier classification.""" + return TierClassifier.classify(peer, activity_count, days_since_activity) diff --git a/src/peer/inference.py b/src/peer/inference.py new file mode 100644 index 0000000..ff1f0b7 --- /dev/null +++ b/src/peer/inference.py @@ -0,0 +1,370 @@ +""" +Three-step inference engine for Peer Representation. + +Implements: +- Explicit: Direct preference extraction from user actions +- Deductive: Logical inference from behavior patterns +- Inductive: Pattern recognition and generalization + +Note: Abductive reasoning is deferred as an exploratory feature. +""" + +from dataclasses import dataclass +from datetime import datetime +from typing import Dict, List, Optional, Set, Tuple + +from .models import PeerRepr, ExplicitPreference, DeducedPreference, InducedPreference + + +@dataclass +class InferenceContext: + """Context for inference operations.""" + peer: PeerRepr + current_item: Optional[str] = None + timestamp: datetime = None + + def __post_init__(self): + if self.timestamp is None: + self.timestamp = datetime.now() + + +class ExplicitInference: + """ + Explicit preference extraction from direct user actions. + + Sources: + - Ratings (1-5 stars, thumbs up/down) + - Likes, bookmarks, saves + - Explicit searches or requests + """ + + def extract(self, context: InferenceContext, + item_id: str, action_type: str, + action_value: float) -> ExplicitPreference: + """ + Extract explicit preference from user action. + + Args: + context: Inference context + item_id: Target item identifier + action_type: Type of action (e.g., "rating", "like", "bookmark") + action_value: Normalized value (0.0 to 1.0) + + Returns: + ExplicitPreference with full confidence + """ + # Normalize different action types to 0-1 scale + normalized_score = self._normalize_action(action_type, action_value) + + return ExplicitPreference( + item_id=item_id, + score=normalized_score, + source=action_type, + timestamp=context.timestamp, + confidence=1.0 + ) + + def _normalize_action(self, action_type: str, value: float) -> float: + """Normalize different action types to 0-1 range.""" + # Rating scales normalization + if action_type == "rating_5": + return value / 5.0 + elif action_type == "rating_10": + return value / 10.0 + elif action_type == "rating_100": + return value / 100.0 + # Binary actions + elif action_type in ("like", "bookmark", "save", "follow"): + return 1.0 if value > 0 else 0.0 + # Percentage + elif action_type == "percentage": + return max(0.0, min(1.0, value / 100.0)) + # Already normalized + else: + return max(0.0, min(1.0, value)) + + def batch_extract(self, context: InferenceContext, + actions: List[Tuple[str, str, float]]) -> Dict[str, ExplicitPreference]: + """ + Extract multiple explicit preferences from a batch of actions. + + Args: + context: Inference context + actions: List of (item_id, action_type, action_value) tuples + + Returns: + Dict mapping item_id to ExplicitPreference + """ + results = {} + for item_id, action_type, action_value in actions: + pref = self.extract(context, item_id, action_type, action_value) + results[item_id] = pref + return results + + +class DeductiveInference: + """ + Deductive reasoning to infer preferences from behavior. + + Types: + - Transitive: If A likes B and B likes C, might like C + - Contextual: Items consumed in similar contexts + - Behavioral: Actions that imply preference (e.g., repeat purchases) + """ + + def infer(self, context: InferenceContext, + item_id: str, + base_item_id: str, + base_score: float, + inference_type: str = "transitive", + confidence: float = 0.8) -> DeducedPreference: + """ + Infer a preference through deductive reasoning. + + Args: + context: Inference context + item_id: Target item being inferred + base_item_id: Source item that drives the inference + base_score: Score of the base item + inference_type: Type of deduction + confidence: Confidence level for this deduction + + Returns: + DeducedPreference with evidence + """ + # Apply deduction strength based on inference type + strength = self._get_inference_strength(inference_type) + inferred_score = base_score * strength + + return DeducedPreference( + item_id=item_id, + score=inferred_score, + inference_type=inference_type, + evidence=[base_item_id], + confidence=confidence * strength, + timestamp=context.timestamp + ) + + def _get_inference_strength(self, inference_type: str) -> float: + """Get strength multiplier for inference type.""" + strengths = { + "transitive": 0.9, # High confidence transitive inference + "contextual": 0.85, # Contextual similarity + "behavioral": 0.75, # Behavioral patterns + "temporal": 0.7, # Time-based patterns + } + return strengths.get(inference_type, 0.8) + + def infer_from_multiple(self, context: InferenceContext, + item_id: str, + base_items: List[Tuple[str, float]], + inference_type: str = "combined") -> DeducedPreference: + """ + Infer preference from multiple base items. + + Args: + context: Inference context + item_id: Target item being inferred + base_items: List of (base_item_id, score) tuples + inference_type: Type of combined deduction + + Returns: + DeducedPreference aggregated from multiple sources + """ + if not base_items: + return DeducedPreference( + item_id=item_id, + score=0.0, + inference_type=inference_type, + evidence=[], + confidence=0.0, + timestamp=context.timestamp + ) + + # Aggregate scores from multiple sources + scores = [s for _, s in base_items] + avg_score = sum(scores) / len(scores) + + return DeducedPreference( + item_id=item_id, + score=avg_score, + inference_type=inference_type, + evidence=[item for item, _ in base_items], + confidence=0.8 * min(1.0, len(base_items) / 3), # More evidence = higher confidence + timestamp=context.timestamp + ) + + +class InductiveInference: + """ + Inductive reasoning to discover preferences through pattern recognition. + + Types: + - Cluster: Items in same cluster as liked items + - Sequence: Items frequently following liked items + - Collaborative: Items liked by similar peers + """ + + def discover(self, context: InferenceContext, + item_id: str, + pattern_type: str, + supporting_items: List[str], + pattern_score: float, + pattern_strength: float = 0.7) -> InducedPreference: + """ + Discover a preference through pattern recognition. + + Args: + context: Inference context + item_id: Target item being discovered + pattern_type: Type of pattern detected + supporting_items: Items that support this pattern + pattern_score: Score derived from the pattern + pattern_strength: Strength of the pattern (0-1) + + Returns: + InducedPreference based on pattern analysis + """ + # Apply pattern strength to score + inferred_score = pattern_score * pattern_strength + + return InducedPreference( + item_id=item_id, + score=inferred_score, + pattern_type=pattern_type, + supporting_items=supporting_items, + pattern_strength=pattern_strength, + confidence=0.7 * pattern_strength, + timestamp=context.timestamp + ) + + def _get_pattern_strength(self, pattern_type: str) -> float: + """Get default strength for pattern type.""" + strengths = { + "cluster": 0.75, # Item clustering patterns + "sequence": 0.7, # Sequential patterns + "collaborative": 0.8, # Collaborative filtering patterns + "temporal": 0.65, # Temporal patterns + } + return strengths.get(pattern_type, 0.7) + + def discover_from_clusters(self, context: InferenceContext, + item_id: str, + liked_items: List[str], + cluster_membership: Dict[str, List[str]], + base_score: float) -> InducedPreference: + """ + Discover preference based on cluster membership. + + Args: + context: Inference context + item_id: Target item + liked_items: Items the peer likes + cluster_membership: Map of cluster_id -> [items] + base_score: Base score to propagate + + Returns: + InducedPreference based on cluster membership + """ + # Find clusters that contain liked items + supporting = [] + for cluster_id, items in cluster_membership.items(): + if any(item in liked_items for item in items) and item_id in items: + supporting.append(cluster_id) + + pattern_strength = min(0.9, 0.5 + 0.1 * len(supporting)) + + return InducedPreference( + item_id=item_id, + score=base_score * pattern_strength, + pattern_type="cluster", + supporting_items=supporting, + pattern_strength=pattern_strength, + confidence=0.7 * pattern_strength, + timestamp=context.timestamp + ) + + +class ThreeStepInferenceEngine: + """ + Combines explicit, deductive, and inductive inference. + + The three steps work together: + 1. Explicit captures direct user actions + 2. Deductive reasons from known preferences + 3. Inductive discovers patterns across the peer graph + """ + + def __init__(self): + self.explicit = ExplicitInference() + self.deductive = DeductiveInference() + self.inductive = InductiveInference() + + def build_representation(self, peer: PeerRepr, + explicit_actions: List[Tuple[str, str, float]] = None, + deductive_bases: List[Tuple[str, str, float, str]] = None, + inductive_patterns: List[Tuple[str, str, List[str], float]] = None) -> PeerRepr: + """ + Build complete peer representation from inference steps. + + Args: + peer: PeerRepr to populate + explicit_actions: List of (item_id, action_type, action_value) + deductive_bases: List of (item_id, base_item_id, base_score, inference_type) + inductive_patterns: List of (item_id, pattern_type, supporting_items, pattern_score) + + Returns: + Populated PeerRepr + """ + context = InferenceContext(peer=peer) + + # Step 1: Explicit preferences + if explicit_actions: + for item_id, action_type, action_value in explicit_actions: + pref = self.explicit.extract(context, item_id, action_type, action_value) + peer.explicit_prefs[item_id] = pref + + # Step 2: Deductive preferences + if deductive_bases: + for item_id, base_item_id, base_score, inference_type in deductive_bases: + pref = self.deductive.infer( + context, item_id, base_item_id, base_score, inference_type + ) + peer.deduced_prefs[item_id] = pref + + # Step 3: Inductive preferences + if inductive_patterns: + for item_id, pattern_type, supporting_items, pattern_score in inductive_patterns: + pref = self.inductive.discover( + context, item_id, pattern_type, supporting_items, pattern_score + ) + peer.induced_prefs[item_id] = pref + + peer.updated_at = datetime.now() + return peer + + def aggregate_preference(self, peer: PeerRepr, item_id: str) -> float: + """ + Get aggregated preference score for an item. + + Combines all three inference types with their confidence weights. + """ + explicit_score = peer.get_explicit_score(item_id) + deductive_score = peer.get_deductive_score(item_id) + inductive_score = peer.get_inductive_score(item_id) + + # Weighted aggregation + return ( + 0.30 * explicit_score + + 0.35 * deductive_score + + 0.35 * inductive_score + ) + + def get_preference_explanation(self, peer: PeerRepr, item_id: str) -> Dict[str, float]: + """Get breakdown of preference by inference type.""" + return { + "explicit": peer.get_explicit_score(item_id), + "deductive": peer.get_deductive_score(item_id), + "inductive": peer.get_inductive_score(item_id), + "aggregated": self.aggregate_preference(peer, item_id) + } diff --git a/src/peer/models.py b/src/peer/models.py new file mode 100644 index 0000000..fea303c --- /dev/null +++ b/src/peer/models.py @@ -0,0 +1,217 @@ +""" +PeerRepr data model - Three-step inference results representation. + +Represents a peer's learned representation based on: +- Explicit: Directly stated preferences (e.g., user ratings, likes) +- Deductive: Preferences derived through logical inference from behavior +- Inductive: Preferences discovered through pattern recognition +""" + +from dataclasses import dataclass, field +from datetime import datetime +from enum import Enum +from typing import Dict, List, Optional, Set +from uuid import UUID, uuid4 + + +class Tier(Enum): + """Peer tier classification determining decay behavior.""" + CORE = "core" # Never decays, highest confidence + ACTIVE = "active" # Normal decay rate + PASSIVE = "passive" # Faster decay rate + DEPRECATED = "deprecated" # Marked for removal + + +@dataclass +class ExplicitPreference: + """An explicitly stated preference (direct rating, like, vote).""" + item_id: str + score: float # Typically 0.0 to 1.0 + source: str # e.g., "rating", "like", "bookmark" + timestamp: datetime = field(default_factory=datetime.now) + confidence: float = 1.0 # Explicit prefs have full confidence + + +@dataclass +class DeducedPreference: + """A preference derived through deductive reasoning from behavior patterns.""" + item_id: str + score: float + inference_type: str # e.g., "transitive", "contextual", "behavioral" + evidence: List[str] = field(default_factory=list) # Item IDs that supported this inference + confidence: float = 0.8 # Deductive reasoning has high but not perfect confidence + timestamp: datetime = field(default_factory=datetime.now) + + +@dataclass +class InducedPreference: + """A preference discovered through inductive pattern recognition.""" + item_id: str + score: float + pattern_type: str # e.g., "cluster", "sequence", "collaborative" + supporting_items: List[str] = field(default_factory=list) + pattern_strength: float = 0.7 # How strong the pattern is + confidence: float = 0.7 # Inductive reasoning confidence + timestamp: datetime = field(default_factory=datetime.now) + + +@dataclass +class PeerRepr: + """ + Complete peer representation combining all three inference types. + + Attributes: + id: Unique identifier for this peer representation + peer_id: Identifier of the peer this represents + tier: Current tier classification + explicit_prefs: Explicitly stated preferences + deduced_prefs: Deductively inferred preferences + induced_prefs: Inductively discovered preferences + tags: Set of interest tags for this peer + created_at: When this representation was created + updated_at: When this representation was last updated + decay_days: Number of days since last update for decay calculation + """ + id: UUID = field(default_factory=uuid4) + peer_id: str = "" + tier: Tier = Tier.ACTIVE + + explicit_prefs: Dict[str, ExplicitPreference] = field(default_factory=dict) + deduced_prefs: Dict[str, DeducedPreference] = field(default_factory=dict) + induced_prefs: Dict[str, InducedPreference] = field(default_factory=dict) + + tags: Set[str] = field(default_factory=set) + + created_at: datetime = field(default_factory=datetime.now) + updated_at: datetime = field(default_factory=datetime.now) + last_decay_update: datetime = field(default_factory=datetime.now) + + @property + def days_since_update(self) -> float: + """Calculate days since last update for decay.""" + delta = datetime.now() - self.last_decay_update + return delta.total_seconds() / 86400.0 + + @property + def all_item_ids(self) -> Set[str]: + """Get all item IDs across all preference types.""" + items = set() + items.update(self.explicit_prefs.keys()) + items.update(self.deduced_prefs.keys()) + items.update(self.induced_prefs.keys()) + return items + + def get_explicit_score(self, item_id: str) -> float: + """Get explicit preference score for an item.""" + pref = self.explicit_prefs.get(item_id) + return pref.score if pref else 0.0 + + def get_deductive_score(self, item_id: str) -> float: + """Get deductive preference score for an item.""" + pref = self.deduced_prefs.get(item_id) + return pref.score if pref else 0.0 + + def get_inductive_score(self, item_id: str) -> float: + """Get inductive preference score for an item.""" + pref = self.induced_prefs.get(item_id) + return pref.score if pref else 0.0 + + @property + def max_explicit(self) -> float: + """Maximum explicit preference score.""" + if not self.explicit_prefs: + return 0.0 + return max(p.score for p in self.explicit_prefs.values()) + + @property + def max_deductive(self) -> float: + """Maximum deductive preference score.""" + if not self.deduced_prefs: + return 0.0 + return max(p.score for p in self.deduced_prefs.values()) + + @property + def max_inductive(self) -> float: + """Maximum inductive preference score.""" + if not self.induced_prefs: + return 0.0 + return max(p.score for p in self.induced_prefs.values()) + + @property + def final_confidence(self) -> float: + """ + Calculate final confidence using weighted aggregation. + + Formula: 0.35*max_deductive + 0.35*max_inductive + 0.30*max_explicit + + This weights deductive and inductive equally higher than explicit, + as behavioral inferences often provide stronger signals. + """ + return ( + 0.35 * self.max_deductive + + 0.35 * self.max_inductive + + 0.30 * self.max_explicit + ) + + def add_explicit(self, item_id: str, score: float, source: str = "interaction") -> None: + """Add or update an explicit preference.""" + self.explicit_prefs[item_id] = ExplicitPreference( + item_id=item_id, + score=score, + source=source, + timestamp=datetime.now() + ) + self.updated_at = datetime.now() + + def add_deductive(self, item_id: str, score: float, + inference_type: str, evidence: List[str] = None) -> None: + """Add a deductively inferred preference.""" + self.deduced_prefs[item_id] = DeducedPreference( + item_id=item_id, + score=score, + inference_type=inference_type, + evidence=evidence or [], + timestamp=datetime.now() + ) + self.updated_at = datetime.now() + + def add_inductive(self, item_id: str, score: float, + pattern_type: str, supporting_items: List[str] = None) -> None: + """Add an inductively discovered preference.""" + self.induced_prefs[item_id] = InducedPreference( + item_id=item_id, + score=score, + pattern_type=pattern_type, + supporting_items=supporting_items or [], + timestamp=datetime.now() + ) + self.updated_at = datetime.now() + + def to_dict(self) -> Dict: + """Serialize to dictionary.""" + return { + "id": str(self.id), + "peer_id": self.peer_id, + "tier": self.tier.value, + "explicit_prefs": { + k: {"item_id": v.item_id, "score": v.score, "source": v.source, + "timestamp": v.timestamp.isoformat()} + for k, v in self.explicit_prefs.items() + }, + "deduced_prefs": { + k: {"item_id": v.item_id, "score": v.score, + "inference_type": v.inference_type, "evidence": v.evidence, + "timestamp": v.timestamp.isoformat()} + for k, v in self.deduced_prefs.items() + }, + "induced_prefs": { + k: {"item_id": v.item_id, "score": v.score, + "pattern_type": v.pattern_type, "supporting_items": v.supporting_items, + "timestamp": v.timestamp.isoformat()} + for k, v in self.induced_prefs.items() + }, + "tags": list(self.tags), + "created_at": self.created_at.isoformat(), + "updated_at": self.updated_at.isoformat(), + "final_confidence": self.final_confidence + } diff --git a/tests/test_graph.py b/tests/test_graph.py new file mode 100644 index 0000000..2accd7f --- /dev/null +++ b/tests/test_graph.py @@ -0,0 +1,250 @@ +""" +Tests for graph module. +""" +import pytest +import tempfile +from pathlib import Path +from datetime import datetime +import networkx as nx + +from src.graph.models import GraphNode, GraphEdge, NodeType, EdgeType +from src.graph.builder import GraphBuilder +from src.graph.query import GraphQuery +from src.graph.indexer import LazyIndexer +from src.models.distilled import Distilled + + +class TestGraphNode: + def test_create_entity_node(self): + node = GraphNode.from_entity( + entity="牧尘", + distilled_id="test-123", + episode_id="ep-456", + confidence=0.8, + importance=2 + ) + assert node.type == NodeType.ENTITY + assert node.label == "牧尘" + assert node.distilled_id == "test-123" + + def test_create_fact_node(self): + node = GraphNode.from_fact( + fact="牧尘喜欢简洁的回答", + distilled_id="test-123", + episode_id="ep-456", + confidence=0.9 + ) + assert node.type == NodeType.FACT + assert "简洁" in node.label + + def test_to_dict_roundtrip(self): + node = GraphNode.from_entity("测试", "d1", "e1") + d = node.to_dict() + node2 = GraphNode.from_dict(d) + assert node.id == node2.id + assert node.label == node2.label + assert node.type == node2.type + + def test_node_importance_assignment(self): + node = GraphNode.from_entity("重要人物", "d1", "e1", importance=3) + assert node.importance == 3 + + +class TestGraphEdge: + def test_create_edge(self): + node_a = GraphNode.from_entity("A", "d1", "e1") + node_b = GraphNode.from_entity("B", "d2", "e2") + edge = GraphEdge.create_relation( + source_id=node_a.id, + target_id=node_b.id, + relation=EdgeType.RELATES_TO, + weight=0.9 + ) + assert edge.source == node_a.id + assert edge.target == node_b.id + assert edge.weight == 0.9 + + def test_to_dict_roundtrip(self): + node_a = GraphNode.from_entity("A", "d1", "e1") + node_b = GraphNode.from_entity("B", "d2", "e2") + edge = GraphEdge.create_relation(node_a.id, node_b.id, EdgeType.SIMILAR_TO, weight=0.8) + d = edge.to_dict() + edge2 = GraphEdge.from_dict(d) + assert edge.id == edge2.id + assert edge.relation == edge2.relation + + +class TestGraphBuilder: + def test_build_graph_from_distilled(self): + """Test building a graph from a Distilled record.""" + distilled = Distilled( + id="distilled-1", + episode_id="ep-1", + type="fact", + summary="测试总结", + facts=[ + "牧尘喜欢简洁", + "牧尘偏好Python", + "牧尘用Arch Linux" + ], + entities=["牧尘"], + confidence=0.8, + status="active", + importance=2 + ) + + builder = GraphBuilder() + builder.add_distilled(distilled) + graph = builder.graph + + # Should create entity nodes + fact nodes + assert len(graph.nodes) >= 4 # 至少:entity "牧尘" + 3 facts + + def test_entity_extraction_from_facts(self): + """Test that entities are properly extracted from facts.""" + distilled = Distilled( + id="distilled-2", + episode_id="ep-2", + type="fact", + summary="", + facts=["牧尘使用ComfyUI"], + entities=["牧尘", "ComfyUI"], + confidence=0.7 + ) + + builder = GraphBuilder() + builder.add_distilled(distilled) + graph = builder.graph + + # Both entity and fact should create nodes + assert len(graph.nodes) >= 2 + + +class TestGraphQuery: + def setup_method(self): + """Set up a test graph using NetworkX directly.""" + # Create a simple graph: A -> B -> C, A -> D + self.graph = nx.DiGraph() + + self.node_a = GraphNode.from_entity("A", "d1", "e1") + self.node_b = GraphNode.from_entity("B", "d2", "e2") + self.node_c = GraphNode.from_entity("C", "d3", "e3") + self.node_d = GraphNode.from_entity("D", "d4", "e4") + + # Add nodes to graph with data + self.graph.add_node(self.node_a.id, **self.node_a.to_dict()) + self.graph.add_node(self.node_b.id, **self.node_b.to_dict()) + self.graph.add_node(self.node_c.id, **self.node_c.to_dict()) + self.graph.add_node(self.node_d.id, **self.node_d.to_dict()) + + # A -> B -> C (2 hops), A -> D (1 hop) + self.graph.add_edge(self.node_a.id, self.node_b.id, **GraphEdge.create_relation( + self.node_a.id, self.node_b.id, EdgeType.RELATES_TO, weight=0.9 + ).to_dict()) + self.graph.add_edge(self.node_b.id, self.node_c.id, **GraphEdge.create_relation( + self.node_b.id, self.node_c.id, EdgeType.RELATES_TO, weight=0.9 + ).to_dict()) + self.graph.add_edge(self.node_a.id, self.node_d.id, **GraphEdge.create_relation( + self.node_a.id, self.node_d.id, EdgeType.RELATES_TO, weight=0.8 + ).to_dict()) + + def test_bfs_1_hop(self): + """Test BFS with 1 hop.""" + query = GraphQuery(self.graph) + result = query.bfs_n_hops(self.node_a.id, max_hops=1) + + # 1 hop should reach B and D (not C which is 2 hops away) + assert 1 in result + found_1hop = result.get(1, set()) + assert self.node_b.id in found_1hop + assert self.node_d.id in found_1hop + assert self.node_c.id not in found_1hop + + def test_bfs_2_hops(self): + """Test BFS with 2 hops.""" + query = GraphQuery(self.graph) + result = query.bfs_n_hops(self.node_a.id, max_hops=2) + + # 2 hops should reach C (through B) + assert 2 in result + found_2hops = result.get(2, set()) + assert self.node_c.id in found_2hops + + def test_degree_centrality(self): + """Test degree centrality calculation.""" + query = GraphQuery(self.graph) + centrality = query.degree_centrality() + + # Graph has 4 nodes, n-1 = 3 + # A: out-degree=2, degree=2 → 2/3 + # B: out-degree=1, degree=2 → 2/3 (in+out) + # C: out-degree=0, degree=1 → 1/3 + # D: out-degree=0, degree=1 → 1/3 + assert centrality[self.node_a.id] == 2.0 / 3.0 + assert centrality[self.node_b.id] == 2.0 / 3.0 + assert centrality[self.node_c.id] == 1.0 / 3.0 + assert centrality[self.node_d.id] == 1.0 / 3.0 + + def test_jaccard_similarity(self): + """Test Jaccard similarity between nodes.""" + # Add shared neighbor for A and B + node_e = GraphNode.from_entity("E", "d5", "e5") + self.graph.add_node(node_e.id, **node_e.to_dict()) + + # A -> E, B -> E (both connect to E) + self.graph.add_edge(self.node_a.id, node_e.id, **GraphEdge.create_relation( + self.node_a.id, node_e.id, EdgeType.RELATES_TO, weight=0.9 + ).to_dict()) + self.graph.add_edge(self.node_b.id, node_e.id, **GraphEdge.create_relation( + self.node_b.id, node_e.id, EdgeType.RELATES_TO, weight=0.9 + ).to_dict()) + + query = GraphQuery(self.graph) + sim = query.jaccard_similarity(self.node_a.id, self.node_b.id) + + # A has neighbors {B, D, E}, B has neighbors {C, E} + # Jaccard = |{E}| / |{B, D, E, C}| = 1/4 + assert 0 < sim <= 1 + + +class TestLazyIndexer: + def test_indexer_creation(self): + """Test lazy indexer initialization.""" + with tempfile.TemporaryDirectory() as tmpdir: + indexer = LazyIndexer(storage_dir=Path(tmpdir)) + assert indexer.storage_dir.exists() + + def test_build_and_lookup(self): + """Test building indexes and looking up.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a simple graph + graph = nx.DiGraph() + node = GraphNode.from_entity("测试节点", "d1", "e1") + graph.add_node(node.id, **node.to_dict()) + + indexer = LazyIndexer(storage_dir=Path(tmpdir)) + indexer.build_indexes(graph) + + # Should find the node by label + results = indexer.lookup_by_label("测试节点") + assert len(results) == 1 + + def test_save_and_load_index(self): + """Test saving and loading indexes.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a graph + graph = nx.DiGraph() + node = GraphNode.from_entity("测试节点", "d1", "e1") + graph.add_node(node.id, **node.to_dict()) + + # Build and save + indexer1 = LazyIndexer(storage_dir=Path(tmpdir)) + indexer1.build_indexes(graph) + indexer1.save_index() + + # Load in new indexer + indexer2 = LazyIndexer(storage_dir=Path(tmpdir)) + indexer2.load_index() + + results = indexer2.lookup_by_label("测试节点") + assert len(results) == 1 \ No newline at end of file diff --git a/tests/test_peer.py b/tests/test_peer.py new file mode 100644 index 0000000..a861dd0 --- /dev/null +++ b/tests/test_peer.py @@ -0,0 +1,245 @@ +""" +Tests for peer module. +""" +import pytest +from datetime import datetime, timedelta + +from src.peer.models import ( + PeerRepr, Tier, + ExplicitPreference, DeducedPreference, InducedPreference +) +from src.peer.decay import DecayCalculator, DecayResult, DECAY_RATE, MIN_SCORE +from src.peer.inference import ExplicitInference, DeductiveInference, InductiveInference, InferenceContext + + +class TestPeerRepr: + def test_create_peer_repr(self): + """Test basic PeerRepr creation.""" + peer = PeerRepr(peer_id="user-1", tier=Tier.ACTIVE) + assert peer.peer_id == "user-1" + assert peer.tier == Tier.ACTIVE + assert len(peer.explicit_prefs) == 0 + + def test_add_explicit_preference(self): + """Test adding explicit preferences.""" + peer = PeerRepr(peer_id="user-1") + peer.add_explicit("item-a", 0.9, "rating") + + assert "item-a" in peer.explicit_prefs + assert peer.get_explicit_score("item-a") == 0.9 + + def test_add_deductive_preference(self): + """Test adding deduced preferences.""" + peer = PeerRepr(peer_id="user-1") + peer.add_deductive("item-b", 0.7, "transitive", evidence=["item-a"]) + + assert "item-b" in peer.deduced_prefs + assert peer.get_deductive_score("item-b") == 0.7 + + def test_add_inductive_preference(self): + """Test adding induced preferences.""" + peer = PeerRepr(peer_id="user-1") + peer.add_inductive("item-c", 0.8, "cluster", supporting_items=["item-a", "item-b"]) + + assert "item-c" in peer.induced_prefs + assert peer.get_inductive_score("item-c") == 0.8 + + def test_max_scores(self): + """Test max score calculations.""" + peer = PeerRepr(peer_id="user-1") + peer.add_explicit("item-a", 0.9, "rating") + peer.add_explicit("item-b", 0.7, "rating") + peer.add_deductive("item-c", 0.8, "transitive") + + assert peer.max_explicit == 0.9 + assert peer.max_deductive == 0.8 + + def test_final_confidence_calculation(self): + """Test weighted confidence aggregation.""" + peer = PeerRepr(peer_id="user-1") + peer.add_explicit("item-a", 1.0, "rating") + peer.add_deductive("item-b", 1.0, "transitive") + peer.add_inductive("item-c", 1.0, "cluster") + + # Formula: 0.35*max_deductive + 0.35*max_inductive + 0.30*max_explicit + expected = 0.35 * 1.0 + 0.35 * 1.0 + 0.30 * 1.0 + assert peer.final_confidence == expected + + def test_all_item_ids(self): + """Test collecting all item IDs.""" + peer = PeerRepr(peer_id="user-1") + peer.add_explicit("item-a", 0.9, "rating") + peer.add_deductive("item-b", 0.8, "transitive") + peer.add_inductive("item-c", 0.7, "cluster") + + items = peer.all_item_ids + assert len(items) == 3 + assert "item-a" in items + assert "item-b" in items + assert "item-c" in items + + def test_tier_assignment(self): + """Test tier property.""" + peer = PeerRepr(peer_id="user-1", tier=Tier.CORE) + assert peer.tier == Tier.CORE + + +class TestDecayCalculator: + def test_normal_decay(self): + """Test normal decay rate.""" + calc = DecayCalculator() + + # After 10 days: score = max(0.1, 1.0 - 10 * 0.015) = max(0.1, 0.85) = 0.85 + score = calc.calculate(1.0, 10.0, Tier.ACTIVE) + assert score == 0.85 + + def test_core_no_decay(self): + """Test core tier never decays.""" + calc = DecayCalculator() + + score = calc.calculate(0.9, 100.0, Tier.CORE) + assert score == 0.9 # No decay + + def test_minimum_score_floor(self): + """Test that score doesn't go below minimum.""" + calc = DecayCalculator() + + # After 100 days: score = max(0.1, 1.0 - 100 * 0.015) = max(0.1, -0.5) = 0.1 + score = calc.calculate(1.0, 100.0, Tier.ACTIVE) + assert score == 0.1 + + def test_passive_faster_decay(self): + """Test passive tier decays faster.""" + calc = DecayCalculator() + + # Passive decays 50% faster + # After 10 days: 1.0 - 10 * 0.015 * 1.5 = 0.775 + score_passive = calc.calculate(1.0, 10.0, Tier.PASSIVE) + score_active = calc.calculate(1.0, 10.0, Tier.ACTIVE) + + assert score_passive < score_active + + def test_deprecated_faster_decay(self): + """Test deprecated tier decays fastest.""" + calc = DecayCalculator() + + # Deprecated decays 100% faster + score_deprecated = calc.calculate(1.0, 10.0, Tier.DEPRECATED) + score_active = calc.calculate(1.0, 10.0, Tier.ACTIVE) + + assert score_deprecated < score_active + + def test_decay_result_details(self): + """Test DecayResult contains all details.""" + calc = DecayCalculator() + + result = calc.calculate_result(1.0, 10.0, Tier.ACTIVE) + + assert isinstance(result, DecayResult) + assert result.original_score == 1.0 + assert result.days_elapsed == 10.0 + assert result.decay_applied == pytest.approx(0.15) + + +class TestExplicitInference: + def test_extract_like_action(self): + """Test extracting from like action.""" + inferrer = ExplicitInference() + context = InferenceContext(peer=PeerRepr(peer_id="user-1")) + + pref = inferrer.extract(context, "item-1", "like", 1.0) + + assert pref.item_id == "item-1" + assert pref.score == 1.0 + assert pref.source == "like" + + def test_extract_rating_normalization(self): + """Test rating normalization to 0-1.""" + inferrer = ExplicitInference() + context = InferenceContext(peer=PeerRepr(peer_id="user-1")) + + # 5-star rating -> 5/5 = 1.0 + pref = inferrer.extract(context, "item-1", "rating_5", 4.0) + assert pref.score == 0.8 + + def test_extract_percentage(self): + """Test percentage action.""" + inferrer = ExplicitInference() + context = InferenceContext(peer=PeerRepr(peer_id="user-1")) + + pref = inferrer.extract(context, "item-1", "percentage", 75.0) + assert pref.score == 0.75 + + +class TestDeductiveInference: + def test_infer_deductive_preference(self): + """Test deductive inference.""" + inferrer = DeductiveInference() + context = InferenceContext(peer=PeerRepr(peer_id="user-1")) + + # Setup: User likes item-a + peer = context.peer + peer.add_explicit("item-a", 0.9, "rating") + + pref = inferrer.infer( + context, "item-b", "item-a", 0.9, + inference_type="transitive", confidence=0.8 + ) + + assert pref.item_id == "item-b" + assert pref.inference_type == "transitive" + assert 0 < pref.score <= 0.9 # transitive has 0.9 strength + + +class TestInductiveInference: + def test_discover_from_cluster(self): + """Test discovering preference from cluster.""" + inferrer = InductiveInference() + context = InferenceContext(peer=PeerRepr(peer_id="user-1")) + + # Setup: User likes item-a + peer = context.peer + peer.add_explicit("item-a", 0.9, "rating") + + cluster_membership = { + "cluster-1": ["item-a", "item-b", "item-c"] + } + + pref = inferrer.discover_from_clusters( + context, "item-b", ["item-a"], cluster_membership, 0.8 + ) + + assert pref.item_id == "item-b" + assert pref.pattern_type == "cluster" + + def test_discover(self): + """Test basic discover method.""" + inferrer = InductiveInference() + context = InferenceContext(peer=PeerRepr(peer_id="user-1")) + + pref = inferrer.discover( + context, "item-x", "cluster", ["item-a", "item-b"], 0.8, 0.75 + ) + + assert pref.item_id == "item-x" + assert pref.pattern_type == "cluster" + assert 0 < pref.score <= 0.8 + + +class TestTierEnum: + def test_tier_values(self): + """Test all tier values exist.""" + assert Tier.CORE.value == "core" + assert Tier.ACTIVE.value == "active" + assert Tier.PASSIVE.value == "passive" + assert Tier.DEPRECATED.value == "deprecated" + + def test_tier_assignment_affects_decay(self): + """Test different tiers produce different decay results.""" + calc = DecayCalculator() + + core = calc.calculate(1.0, 10.0, Tier.CORE) + active = calc.calculate(1.0, 10.0, Tier.ACTIVE) + + # Core should be higher (no decay) + assert core > active \ No newline at end of file