tortoise-graph 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. tortoise/__init__.py +45 -0
  2. tortoise/__main__.py +1865 -0
  3. tortoise/analyze.py +473 -0
  4. tortoise/api.py +303 -0
  5. tortoise/archived/search_legacy.py +31 -0
  6. tortoise/audit.py +236 -0
  7. tortoise/audit_events.py +284 -0
  8. tortoise/auth.py +107 -0
  9. tortoise/backup.py +155 -0
  10. tortoise/config.py +99 -0
  11. tortoise/connector_loader.py +74 -0
  12. tortoise/connectors/__init__.py +5 -0
  13. tortoise/connectors/github.py +432 -0
  14. tortoise/connectors/github_docs.py +146 -0
  15. tortoise/connectors/linear.py +199 -0
  16. tortoise/connectors/slack.py +222 -0
  17. tortoise/consistency.py +132 -0
  18. tortoise/crypto.py +52 -0
  19. tortoise/deployment.py +62 -0
  20. tortoise/domain_loader.py +142 -0
  21. tortoise/dream.py +153 -0
  22. tortoise/embedded_reaper.py +744 -0
  23. tortoise/embeddings.py +227 -0
  24. tortoise/ep.py +534 -0
  25. tortoise/exceptions.py +16 -0
  26. tortoise/extractor.py +945 -0
  27. tortoise/hosted_api.py +1982 -0
  28. tortoise/hosted_middleware.py +22 -0
  29. tortoise/idempotency.py +39 -0
  30. tortoise/ids.py +23 -0
  31. tortoise/indexer/github_indexer.py +129 -0
  32. tortoise/ingest.py +614 -0
  33. tortoise/log.py +29 -0
  34. tortoise/m0.py +50 -0
  35. tortoise/mcp_auth.py +337 -0
  36. tortoise/mcp_client.py +108 -0
  37. tortoise/mcp_server.py +1356 -0
  38. tortoise/memory_orchestrator.py +492 -0
  39. tortoise/memory_scope.py +15 -0
  40. tortoise/migrate_db.py +244 -0
  41. tortoise/migrate_kinds.py +141 -0
  42. tortoise/mining.py +338 -0
  43. tortoise/models.py +109 -0
  44. tortoise/monitoring.py +133 -0
  45. tortoise/navigation.py +216 -0
  46. tortoise/pack_registry.py +767 -0
  47. tortoise/pipeline_cli.py +197 -0
  48. tortoise/projection/__init__.py +913 -0
  49. tortoise/projection/edges.py +311 -0
  50. tortoise/projection/entities.py +521 -0
  51. tortoise/projection/grounding.py +95 -0
  52. tortoise/projection/propagation.py +114 -0
  53. tortoise/projection.py +37 -0
  54. tortoise/quadrature.py +90 -0
  55. tortoise/query_suggestions.py +194 -0
  56. tortoise/quota.py +163 -0
  57. tortoise/ranking.py +280 -0
  58. tortoise/render.py +108 -0
  59. tortoise/scripts/manifest.py +67 -0
  60. tortoise/sdk.py +4713 -0
  61. tortoise/search_engine.py +887 -0
  62. tortoise/security.py +268 -0
  63. tortoise/selfhost.py +157 -0
  64. tortoise/selfhost_api.py +201 -0
  65. tortoise/session_continuity.py +82 -0
  66. tortoise/session_indexer.py +569 -0
  67. tortoise/shared_state/__init__.py +20 -0
  68. tortoise/shared_state/concurrency.py +113 -0
  69. tortoise/shared_state/event_log.py +192 -0
  70. tortoise/shared_state/events.py +150 -0
  71. tortoise/shared_state/monitoring.py +87 -0
  72. tortoise/shared_state/recovery.py +126 -0
  73. tortoise/shared_state/tests/__init__.py +15 -0
  74. tortoise/shared_state/tests/test_concurrency.py +123 -0
  75. tortoise/shared_state/tests/test_events.py +145 -0
  76. tortoise/shared_state/tests/test_monitoring.py +54 -0
  77. tortoise/shared_state/tests/test_recovery.py +181 -0
  78. tortoise/source_credibility.py +306 -0
  79. tortoise/svbp.py +446 -0
  80. tortoise/taxonomy.py +71 -0
  81. tortoise/test_cross_ontology.py +180 -0
  82. tortoise/test_tortoise_client.py +206 -0
  83. tortoise/tool_registry.py +805 -0
  84. tortoise/tortoise_client.py +262 -0
  85. tortoise/verify_ontology.py +154 -0
  86. tortoise/version_vector.py +97 -0
  87. tortoise/weights.py +61 -0
  88. tortoise_graph-0.2.0.dist-info/METADATA +152 -0
  89. tortoise_graph-0.2.0.dist-info/RECORD +93 -0
  90. tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
  91. tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
  92. tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
  93. tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,887 @@
1
+ """Hybrid search engine for Tortoise — RRF fusion of FTS + vector + structural queries.
2
+
3
+ Phase 0 (#7748): Foundation — FalkorDB indexes, RRF fusion, degradation chain,
4
+ 3-tier query classifier, EP batch annotation, and tortoise_fts_query() API.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import threading
10
+ import time
11
+ from dataclasses import dataclass, asdict, field
12
+ from typing import Literal
13
+
14
+
15
+ # ── Circuit breaker (#249) ──────────────────────────────────────────────────
16
+ # Per-strategy breaker: trips after consecutive slow/failed queries so a
17
+ # wedged FalkorDB (or a pathological query) stops consuming caller time and
18
+ # DB resources. While OPEN the strategy short-circuits to degradation
19
+ # (empty results → RRF falls through to the next strategy / TF-IDF fallback).
20
+ # HALF_OPEN after cooldown lets exactly one probe through; success closes.
21
+ # Thread-safe: strategies run concurrently (degradation_chain's executor)
22
+ # and search calls share the module-level breakers.
23
+
24
+
25
+ class _CircuitBreaker:
26
+ """Minimal thread-safe circuit breaker for a search strategy.
27
+
28
+ State machine: CLOSED → (fail_threshold failures) → OPEN →
29
+ (cooldown_seconds elapsed) → HALF_OPEN → (probe success) → CLOSED
30
+ or (probe failure) → OPEN. At most one HALF_OPEN probe is in flight.
31
+ """
32
+
33
+ __slots__ = ("fail_threshold", "cooldown_seconds", "_fails", "_open_until",
34
+ "_probing", "_lock")
35
+
36
+ def __init__(self, fail_threshold: int = 3, cooldown_seconds: float = 30.0):
37
+ self.fail_threshold = fail_threshold
38
+ self.cooldown_seconds = cooldown_seconds
39
+ self._fails = 0
40
+ self._open_until = 0.0 # 0.0 == CLOSED; monotonic deadline while OPEN
41
+ self._probing = False
42
+ self._lock = threading.Lock()
43
+
44
+ def allow(self) -> bool:
45
+ """True if a query may run: CLOSED, or the single HALF_OPEN probe."""
46
+ with self._lock:
47
+ if self._open_until == 0.0:
48
+ return True # CLOSED
49
+ now = time.monotonic()
50
+ if now < self._open_until:
51
+ return False # OPEN
52
+ # Cooldown expired → HALF_OPEN; exactly one caller probes.
53
+ if self._probing:
54
+ return False
55
+ self._probing = True
56
+ return True
57
+
58
+ def is_open(self) -> bool:
59
+ """True if the breaker is currently OPEN (read-only status check)."""
60
+ with self._lock:
61
+ return 0.0 < self._open_until and time.monotonic() < self._open_until
62
+
63
+ def record_success(self) -> None:
64
+ with self._lock:
65
+ self._fails = 0
66
+ self._open_until = 0.0
67
+ self._probing = False
68
+
69
+ def record_failure(self) -> None:
70
+ with self._lock:
71
+ self._fails += 1
72
+ self._probing = False
73
+ if self._fails >= self.fail_threshold:
74
+ self._open_until = time.monotonic() + self.cooldown_seconds
75
+ logger.warning(
76
+ "Circuit breaker OPEN for search strategy (%d consecutive failures, "
77
+ "%.0fs cooldown)",
78
+ self._fails, self.cooldown_seconds,
79
+ )
80
+
81
+ def reset(self) -> None:
82
+ with self._lock:
83
+ self._fails = 0
84
+ self._open_until = 0.0
85
+ self._probing = False
86
+
87
+
88
+ _BREAKERS: dict[str, _CircuitBreaker] = {}
89
+ _BREAKERS_LOCK = threading.Lock()
90
+
91
+
92
+ def _breaker(name: str) -> _CircuitBreaker:
93
+ """Get (creating if needed) the circuit breaker for a strategy."""
94
+ with _BREAKERS_LOCK:
95
+ b = _BREAKERS.get(name)
96
+ if b is None:
97
+ b = _CircuitBreaker()
98
+ _BREAKERS[name] = b
99
+ return b
100
+
101
+
102
+ def reset_circuit_breakers() -> None:
103
+ """Reset all breaker state (used by tests and after DB recovery)."""
104
+ for b in _BREAKERS.values():
105
+ b.reset()
106
+
107
+
108
+ def _breaker_allow(name: str) -> bool:
109
+ """True if the strategy may run (breaker CLOSED or the single HALF_OPEN
110
+ probe)."""
111
+ return _breaker(name).allow()
112
+
113
+
114
+ def _breaker_record(name: str, success: bool) -> None:
115
+ """Record an outcome. Success closes the breaker; failure counts toward
116
+ tripping (a HALF_OPEN probe that fails re-opens immediately)."""
117
+ b = _breaker(name)
118
+ if success:
119
+ b.record_success()
120
+ else:
121
+ b.record_failure()
122
+
123
+ logger = logging.getLogger(__name__)
124
+
125
+ # ── Data model ───────────────────────────────────────────────────────────────
126
+
127
+ @dataclass
128
+ class SearchScores:
129
+ fts: float | None = None
130
+ vector: float | None = None
131
+ structural: float | None = None
132
+ rrf: float = 0.0
133
+
134
+
135
+ @dataclass
136
+ class EpEvidence:
137
+ impl_count: int = 0
138
+ nand_count: int = 0
139
+ total: int = 0
140
+
141
+
142
+ @dataclass
143
+ class EpBreakdown:
144
+ confidence_mean: float = 0.0
145
+ evidence: EpEvidence | None = None
146
+ # Structural ratio nand/(impl+nand) — kept for backward compat. It answers
147
+ # "how much of the incoming evidence is contradiction" but is NOT a
148
+ # posterior-stability measure: a claim with 1 IMPL + 1 NAND that EP
149
+ # converged tightly still reads 0.5.
150
+ contention: float = 0.0
151
+ # True EP posterior variance v = αβ/((α+β)²(α+β+1)) from the persisted
152
+ # ep_alpha/ep_beta — the epistemically correct "is this claim destabilized"
153
+ # signal (same formula as TortoiseEP.get_contested_claims).
154
+ variance: float = 0.0
155
+ # variance > CONTESTED_VARIANCE_THRESHOLD → the claim's posterior is
156
+ # contested: competing evidence is actively destabilizing it. Surface this
157
+ # as a first-class flag so agents treat the claim as disputed, not merely
158
+ # high/low probability.
159
+ contested: bool = False
160
+
161
+ def __post_init__(self):
162
+ if self.evidence is None:
163
+ self.evidence = EpEvidence()
164
+
165
+
166
+ @dataclass
167
+ class SearchResult:
168
+ id: str
169
+ content: str
170
+ point_kind: str
171
+ scores: SearchScores | None = None
172
+ match_source: Literal["fts", "vector", "structural", "rrf", "tfidf"] = "rrf"
173
+ ep: EpBreakdown | None = None
174
+ relationships: list[dict] = field(default_factory=list) # SDK compat (sdk.py passes it; non-point = empty)
175
+ # #125 capture metadata (document entity_type) — optional, empty for non-docs
176
+ topics: list = field(default_factory=list)
177
+ summary: str = ""
178
+ session_id: str = ""
179
+ event_id: str = ""
180
+ source_path: str = "" # #167: file path for agent to open/search
181
+
182
+ def to_dict(self) -> dict:
183
+ """Convert to JSON-safe dict for API responses."""
184
+ d = {
185
+ "id": self.id,
186
+ "content": self.content,
187
+ "point_kind": self.point_kind,
188
+ "match_source": self.match_source,
189
+ "relationships": self.relationships,
190
+ "topics": self.topics,
191
+ "summary": self.summary,
192
+ "sessionId": self.session_id,
193
+ "eventId": self.event_id,
194
+ "sourcePath": self.source_path,
195
+ # Backward-compat aliases (Phase 0 migration from old search() API).
196
+ # IMPORTANT: "similarity" was cosine (0-1) in Phase 0; now it's the
197
+ # RRF fusion score (rank-based, typically 0.01-0.05). Clients that
198
+ # threshold on similarity must recalibrate. (#23)
199
+ "similarity": self.scores.rrf if self.scores else 0.0,
200
+ "snippet": self.content[:200] if len(self.content) > 200 else self.content,
201
+ }
202
+ if self.scores:
203
+ d["scores"] = asdict(self.scores)
204
+ if self.ep and self.ep.evidence is not None:
205
+ d["ep"] = asdict(self.ep)
206
+ return d
207
+
208
+
209
+ # ── Query classification ────────────────────────────────────────────────────
210
+
211
+ def classify_query(
212
+ query: str | None,
213
+ kind: str | None,
214
+ ) -> dict[str, bool]:
215
+ """Determine which retrieval strategies to activate.
216
+
217
+ - No text query → structural only (kind-filtered)
218
+ - Text query present → all available strategies (FTS + vector + structural)
219
+ """
220
+ if not query or not query.strip():
221
+ return {"fts": False, "vector": False, "structural": True}
222
+ return {"fts": True, "vector": True, "structural": True}
223
+
224
+
225
+ # ── FalkorDB query runners ──────────────────────────────────────────────────
226
+
227
+ def run_fts_query(
228
+ graph, query: str, entity_type: str = "point", limit: int = 20, timeout_ms: int = 500
229
+ ) -> list[tuple[str, float]]:
230
+ """Run full-text search via FalkorDB FTS index.
231
+
232
+ Falls back gracefully if index doesn't exist or query fails.
233
+ entity_type: 'point' (default), 'event', 'subject', 'document', 'object',
234
+ 'source', or 'operator'. Document FTS searches the _searchText index
235
+ (#125) which concatenates title+summary+topics.
236
+ Returns n.url for source (canonical key, #448), n.eventId for event,
237
+ n.id for all other entity types.
238
+
239
+ Note: the connection-level `timeout` is passed straight to the FalkorDB
240
+ driver (Graph.query(timeout=...)) so a slow query is killed server-side,
241
+ not merely observed. The post-hoc check below remains as a safety net
242
+ for drivers that ignore the timeout. (#249) The per-strategy circuit
243
+ breaker additionally short-circuits after consecutive slow/failed
244
+ queries so a wedged DB stops eating caller latency.
245
+ """
246
+ if entity_type == "operator":
247
+ # Operators are Points with is_operator=true — match label via CONTAINS
248
+ if not _breaker_allow("fts"):
249
+ logger.warning("FTS circuit breaker OPEN — skipping FTS strategy")
250
+ return []
251
+ try:
252
+ start = time.monotonic()
253
+ cypher = (
254
+ "MATCH (n:Point) "
255
+ "WHERE n.is_operator = true AND toLower(n.label) CONTAINS toLower($query) "
256
+ "RETURN n.id, 1.0 AS score "
257
+ "ORDER BY score DESC "
258
+ "LIMIT $limit"
259
+ )
260
+ rows = graph.query(
261
+ cypher, params={"query": query, "limit": limit}, timeout=timeout_ms
262
+ ).result_set
263
+ elapsed = (time.monotonic() - start) * 1000
264
+ if elapsed > timeout_ms:
265
+ # #561: post-hoc latency warning only — a driver that ignored
266
+ # the timeout returned rows; keep them (real hangs are killed
267
+ # server-side by the driver-level timeout, surfacing as an
268
+ # exception → breaker failure below).
269
+ logger.warning("FTS query exceeded timeout: %.0fms > %dms", elapsed, timeout_ms)
270
+ _breaker_record("fts", True)
271
+ return [(row[0], float(row[1])) for row in rows]
272
+ except Exception as e:
273
+ logger.warning("Operator FTS query failed: %s", e)
274
+ _breaker_record("fts", False)
275
+ return []
276
+ if not _breaker_allow("fts"):
277
+ logger.warning("FTS circuit breaker OPEN — skipping FTS strategy")
278
+ return []
279
+ label = entity_type.capitalize() # point→Point, event→Event, subject→Subject
280
+ # #448: three-way id_field — source→url (canonical key, #149),
281
+ # event→eventId, else→id
282
+ if entity_type == "source":
283
+ id_field = "url"
284
+ elif entity_type == "event":
285
+ id_field = "eventId"
286
+ else:
287
+ id_field = "id"
288
+ try:
289
+ start = time.monotonic()
290
+ cypher = (
291
+ f"CALL db.idx.fulltext.queryNodes('{label}', $query) "
292
+ "YIELD node, score "
293
+ f"RETURN node.{id_field}, score "
294
+ "ORDER BY score DESC "
295
+ "LIMIT $limit"
296
+ )
297
+ rows = graph.query(
298
+ cypher, params={"query": query, "limit": limit}, timeout=timeout_ms
299
+ ).result_set
300
+ # Post-hoc timeout check (see docstring for rationale) — #561: log
301
+ # latency, return the results (the driver-level timeout is the real
302
+ # hang-killer; results received = normal completion for the breaker).
303
+ elapsed = (time.monotonic() - start) * 1000
304
+ if elapsed > timeout_ms:
305
+ logger.warning("FTS query exceeded timeout: %.0fms > %dms", elapsed, timeout_ms)
306
+ _breaker_record("fts", True)
307
+ return [(row[0], float(row[1])) for row in rows]
308
+ except Exception as e:
309
+ msg = str(e).lower()
310
+ if "index" in msg or "not found" in msg or "does not exist" in msg:
311
+ # Benign — expected in embedded FalkorDBLite (no FTS index) and for
312
+ # labels without an index. Degrades quietly; does NOT count toward
313
+ # tripping the breaker (a healthy deployment with one index-less
314
+ # label must not disable FTS for all labels). (#249 review P1-1)
315
+ logger.info("FTS index not available — skipping FTS strategy")
316
+ _breaker_record("fts", True)
317
+ else:
318
+ logger.warning("FTS query failed: %s", e)
319
+ _breaker_record("fts", False)
320
+ return []
321
+
322
+
323
+ def run_vector_query(
324
+ graph, query_vec: list[float], limit: int = 20, timeout_ms: int = 500,
325
+ is_embedded: bool = True, entity_type: str = "point",
326
+ ) -> list[tuple[str, float]]:
327
+ """Run vector similarity search via FalkorDB vector index.
328
+
329
+ query_vec must be a 384-dim embedding matching the index dimension.
330
+
331
+ In Docker/server mode (is_embedded=False), uses the HNSW vector index
332
+ via CALL db.idx.vector.queryNodes. Falls back to brute-force
333
+ vec.euclideanDistance if the index is unavailable (embedded mode,
334
+ old FalkorDB, or index creation failed).
335
+
336
+ entity_type: 'point' (default), 'event', 'subject', 'document', 'object',
337
+ 'source', or 'operator'. The vector index is queried against the label
338
+ matching the entity_type (Event/Subject/Document/Object/...), and results
339
+ return the entity's id field: url for source (canonical key, #448),
340
+ eventId for event, id for all other entity types.
341
+ Operators are Points with is_operator=true — they query the Point label.
342
+ (#172)
343
+
344
+ Note: the connection-level `timeout` is passed straight to the FalkorDB
345
+ driver (Graph.query(timeout=...)) so a slow query is killed server-side.
346
+ The post-hoc check remains as a safety net for drivers that ignore the
347
+ timeout, and the per-strategy circuit breaker short-circuits after
348
+ consecutive slow/failed queries. (#249)
349
+ """
350
+ if not query_vec:
351
+ return []
352
+ if not _breaker_allow("vector"):
353
+ logger.warning("Vector circuit breaker OPEN — skipping vector strategy")
354
+ return []
355
+
356
+ # Operators are Points with is_operator=true — match the Point label
357
+ # (consistent with run_fts_query / run_structural_query). (#172)
358
+ label = "Point" if entity_type == "operator" else entity_type.capitalize()
359
+ # #448: three-way id_field — source→url (canonical key, #149),
360
+ # event→eventId, else→id
361
+ if entity_type == "source":
362
+ id_field = "url"
363
+ elif entity_type == "event":
364
+ id_field = "eventId"
365
+ else:
366
+ id_field = "id"
367
+
368
+ # Docker/server mode → try index-accelerated vector search (#7777)
369
+ if not is_embedded:
370
+ try:
371
+ start = time.monotonic()
372
+ cypher = (
373
+ f"CALL db.idx.vector.queryNodes('{label}', 'embedding', $query_vec, $limit) "
374
+ "YIELD node "
375
+ f"RETURN node.{id_field} "
376
+ "LIMIT $limit"
377
+ )
378
+ rows = graph.query(
379
+ cypher, params={"query_vec": query_vec, "limit": limit}, timeout=timeout_ms
380
+ ).result_set
381
+ elapsed = (time.monotonic() - start) * 1000
382
+ if elapsed > timeout_ms:
383
+ # #561: latency warning only — keep the rows.
384
+ logger.warning("Vector query exceeded timeout: %.0fms > %dms", elapsed, timeout_ms)
385
+ _breaker_record("vector", True)
386
+ # Index results are ranked by similarity; assign rank-based scores.
387
+ # RRF fusion uses rank not absolute scores; single-strategy mode
388
+ # gets reasonable descending ordering.
389
+ total = len(rows)
390
+ return [(row[0], 1.0 - (i / max(total, 1))) for i, row in enumerate(rows)]
391
+ except Exception as e:
392
+ msg = str(e).lower()
393
+ if "index" in msg or "not found" in msg or "does not exist" in msg:
394
+ logger.info("Vector index not available — falling back to brute-force")
395
+ else:
396
+ logger.warning("Vector index query failed, falling back to brute-force: %s", e)
397
+ # Fall through to brute-force below — the OUTCOME is recorded by
398
+ # whichever path finishes (success or the brute-force except), so
399
+ # one logical query counts at most once. (#249 review P1-2)
400
+
401
+ # Brute-force (embedded mode or index query failed)
402
+ try:
403
+ start = time.monotonic()
404
+ # #244: vec.euclideanDistance rejects plain-list query params
405
+ # ("expected Null or Vectorf32 but was List") in embedded FalkorDBLite
406
+ # and whenever the HNSW index is unavailable — wrap the param in
407
+ # vecf32() so vector search actually runs. Stored embeddings must be
408
+ # vecf32-encoded too (a single plain-list node poisons the whole
409
+ # MATCH — see _upsert_event / session indexers).
410
+ cypher = (
411
+ f"MATCH (n:{label}) "
412
+ "WHERE n.embedding IS NOT NULL "
413
+ "WITH vecf32($query_vec) AS _qv, n "
414
+ "WITH n, vec.euclideanDistance(n.embedding, _qv) AS distance "
415
+ "WHERE distance IS NOT NULL "
416
+ f"RETURN n.{id_field}, 1.0 / (1.0 + distance) AS score "
417
+ "ORDER BY score DESC "
418
+ "LIMIT $limit"
419
+ )
420
+ rows = graph.query(
421
+ cypher, params={"query_vec": query_vec, "limit": limit}, timeout=timeout_ms
422
+ ).result_set
423
+ elapsed = (time.monotonic() - start) * 1000
424
+ if elapsed > timeout_ms:
425
+ # #561: latency warning only — return the results.
426
+ logger.warning("Vector query exceeded timeout: %.0fms > %dms", elapsed, timeout_ms)
427
+ _breaker_record("vector", True)
428
+ return [(row[0], float(row[1])) for row in rows]
429
+ except Exception as e:
430
+ msg = str(e).lower()
431
+ if "index" in msg or "not found" in msg or "does not exist" in msg:
432
+ logger.info("Vector index not available — skipping vector strategy")
433
+ _breaker_record("vector", True)
434
+ elif "embedding" in msg and "null" in msg:
435
+ logger.info("No Points with embeddings — skipping vector strategy")
436
+ _breaker_record("vector", True)
437
+ else:
438
+ logger.warning("Vector query failed: %s", e)
439
+ _breaker_record("vector", False)
440
+ return []
441
+
442
+
443
+ def run_structural_query(
444
+ graph, kind: str | None,
445
+ entity_type: str = "point", limit: int = 20, timeout_ms: int = 500
446
+ ) -> list[tuple[str, float]]:
447
+ """Run structural/kind query via range indexes.
448
+
449
+ entity_type: 'point' (filters on pointKind), 'event' (eventKind),
450
+ 'subject' (subjectKind), 'operator' (op_type, Point nodes with is_operator=true),
451
+ 'source' (sourceKind), 'document' (documentKind), 'object' (objectKind).
452
+ Returns matching entities with a score of 1.0 (exact match) or 0.5 (partial match).
453
+
454
+ #249: the driver-level timeout is passed through so a wedged DB cannot
455
+ hang the structural strategy (the third leg of the degradation chain);
456
+ the per-strategy breaker short-circuits after consecutive failures.
457
+ """
458
+ if entity_type == "operator":
459
+ # Operators are Points with is_operator=true, kind=op_type
460
+ label_str = "Point"
461
+ kind_field = "op_type"
462
+ elif entity_type == "source":
463
+ label_str = "Source"
464
+ kind_field = "sourceKind"
465
+ elif entity_type == "document":
466
+ label_str = "Document"
467
+ kind_field = "documentKind"
468
+ elif entity_type == "object":
469
+ label_str = "Object"
470
+ kind_field = "objectKind"
471
+ else:
472
+ label_str = entity_type.capitalize()
473
+ kind_field = {"point": "pointKind", "event": "eventKind", "subject": "subjectKind"}[entity_type]
474
+ if entity_type == "source":
475
+ id_field = "url" # #149: Source canonical key is url, not id
476
+ elif entity_type == "event":
477
+ id_field = "eventId"
478
+ else:
479
+ id_field = "id"
480
+ if not _breaker_allow("structural"):
481
+ logger.warning("Structural circuit breaker OPEN — skipping structural strategy")
482
+ return []
483
+ try:
484
+ conditions = []
485
+ params = {}
486
+ if entity_type == "operator":
487
+ conditions.append("n.is_operator = true")
488
+ if kind:
489
+ conditions.append(f"n.{kind_field} = $kind")
490
+ params["kind"] = kind
491
+
492
+ if not conditions:
493
+ # No filters — caller should use full-scan path instead. Normal
494
+ # completion: record success so a HALF_OPEN probe never latches.
495
+ _breaker_record("structural", True)
496
+ return []
497
+
498
+ where_clause = " AND ".join(conditions)
499
+ cypher = (
500
+ f"MATCH (n:{label_str}) "
501
+ f"WHERE {where_clause} "
502
+ f"RETURN n.{id_field} "
503
+ f"LIMIT $limit"
504
+ )
505
+ params["limit"] = limit
506
+ rows = graph.query(cypher, params=params, timeout=timeout_ms).result_set
507
+
508
+ # Score: 1.0 if kind matched, 0.5 for no-kind broad scan
509
+ results = []
510
+ for row in rows:
511
+ pid = row[0]
512
+ match_score = 1.0 if kind else 0.5
513
+ results.append((pid, match_score))
514
+ _breaker_record("structural", True)
515
+ return results
516
+ except Exception as e:
517
+ msg = str(e).lower()
518
+ if "index" in msg or "not found" in msg or "does not exist" in msg:
519
+ logger.info("Structural index not available — skipping structural strategy")
520
+ _breaker_record("structural", True)
521
+ else:
522
+ logger.warning("Structural query failed: %s", e)
523
+ _breaker_record("structural", False)
524
+ return []
525
+
526
+
527
+ # ── RRF fusion ───────────────────────────────────────────────────────────────
528
+
529
+ def rrf_fusion(
530
+ ranked_lists: list[list[tuple[str, float]]],
531
+ k: int = 60,
532
+ ) -> dict[str, float]:
533
+ """Reciprocal Rank Fusion — combine multiple ranked lists.
534
+
535
+ Formula: RRF(d) = Σ 1/(k + rank_i(d))
536
+
537
+ Args:
538
+ ranked_lists: List of strategies, each is [(id, score), ...] ranked desc
539
+ k: RRF constant (default 60 from Cormack et al. 2009)
540
+
541
+ Returns:
542
+ {id: combined_rrf_score} sorted by score descending
543
+ """
544
+ scores: dict[str, float] = {}
545
+ for ranked in ranked_lists:
546
+ for rank, (pid, _score) in enumerate(ranked):
547
+ rrf_score = 1.0 / (k + rank + 1)
548
+ scores[pid] = scores.get(pid, 0.0) + rrf_score
549
+ return dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
550
+
551
+
552
+ # ── Degradation chain ────────────────────────────────────────────────────────
553
+
554
+ def degradation_chain(
555
+ graph,
556
+ query: str | None,
557
+ kind: str | None,
558
+ query_vec: list[float] | None,
559
+ strategies: dict[str, bool],
560
+ entity_type: str = "point",
561
+ limit: int = 20,
562
+ is_embedded: bool = True,
563
+ expanded_kinds=None, # accepted for SDK compat; kind expansion is post-retrieval (sdk.py)
564
+ ) -> dict[str, list[tuple[str, float]]]:
565
+ """Run retrieval strategies in parallel with per-strategy degradation.
566
+
567
+ Each strategy wraps in try/except → on failure, skip and log.
568
+ Supports partial failure: one strategy down, others continue.
569
+ Strategies run in parallel via ThreadPoolExecutor (P0 fix: #7780).
570
+
571
+ is_embedded: True for embedded/redislite mode (brute-force vector),
572
+ False for Docker/server mode (HNSW index-accelerated).
573
+ entity_type: 'point' (default), 'event', 'subject', 'document', 'object',
574
+ 'source', or 'operator' — forwarded to each retrieval
575
+ strategy to query the correct entity label/id field. (#172)
576
+
577
+ Returns:
578
+ {strategy_name: [(id, score), ...]} — only strategies that succeeded
579
+ """
580
+ import concurrent.futures
581
+
582
+ results: dict[str, list[tuple[str, float]]] = {}
583
+ futures: dict[concurrent.futures.Future, str] = {}
584
+
585
+ with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
586
+ # Submit all enabled strategies in parallel
587
+ if strategies.get("fts") and query:
588
+ futures[executor.submit(
589
+ run_fts_query, graph, query, entity_type=entity_type, limit=limit
590
+ )] = "fts"
591
+
592
+ if strategies.get("vector") and query_vec:
593
+ futures[executor.submit(
594
+ run_vector_query, graph, query_vec, limit=limit, is_embedded=is_embedded,
595
+ entity_type=entity_type,
596
+ )] = "vector"
597
+
598
+ if strategies.get("structural"):
599
+ futures[executor.submit(
600
+ run_structural_query, graph, kind, entity_type=entity_type, limit=limit
601
+ )] = "structural"
602
+
603
+ # Collect results with 500ms total timeout across all strategies.
604
+ # as_completed(timeout=0.5) raises TimeoutError if any future
605
+ # hasn't completed within 500ms from the start of iteration.
606
+ try:
607
+ for future in concurrent.futures.as_completed(futures, timeout=0.5):
608
+ strategy_name = futures[future]
609
+ strategy_results = future.result() # already done — no timeout needed
610
+ if strategy_results:
611
+ results[strategy_name] = strategy_results
612
+ else:
613
+ logger.info("%s strategy returned no results — degraded", strategy_name)
614
+ except concurrent.futures.TimeoutError:
615
+ logger.warning(
616
+ "Strategies timed out (500ms) — collected %d/%d, cancelling remaining",
617
+ len(results), len(futures),
618
+ )
619
+ for f in futures:
620
+ f.cancel()
621
+ except Exception as e:
622
+ logger.warning("Strategy execution failed: %s — degraded", e)
623
+
624
+ return results
625
+
626
+
627
+ # ── EP annotation ────────────────────────────────────────────────────────────
628
+
629
+ # Variance threshold above which a claim's posterior is considered contested.
630
+ # Must match TortoiseEP.get_contested_claims (tortoise/ep.py).
631
+ CONTESTED_VARIANCE_THRESHOLD = 0.04
632
+
633
+
634
+ def _beta_variance(alpha: float, beta: float) -> float:
635
+ """Variance of the Beta(α, β) posterior: αβ/((α+β)²(α+β+1)).
636
+
637
+ Max is 1/12 ≈ 0.0833 at α=β=1 (uninformative prior). Same formula as
638
+ TortoiseEP.get_contested_claims.
639
+ """
640
+ s = alpha + beta
641
+ if s <= 0:
642
+ return 0.0
643
+ return (alpha * beta) / (s * s * (s + 1))
644
+
645
+
646
+ def annotate_ep_batch(graph, point_ids: list[str]) -> dict[str, EpBreakdown]:
647
+ """Fetch EP confidence breakdown for a batch of Point IDs.
648
+
649
+ Single Cypher query — NOT N+1. Returns EpBreakdown per Point ID.
650
+ Points with no EP data get EpBreakdown with confidence_mean=0.0, contention=0.0.
651
+ variance/contested are computed from the PERSISTED ep_alpha/ep_beta
652
+ (posterior stability), not from edge ratios.
653
+ """
654
+ if not point_ids:
655
+ return {}
656
+
657
+ try:
658
+ cypher = (
659
+ "MATCH (n:Point) "
660
+ "WHERE n.id IN $ids "
661
+ "OPTIONAL MATCH (n)<-[r:IMPL]-(:Point) "
662
+ "WITH n, count(r) AS impl_count "
663
+ "OPTIONAL MATCH (n)<-[r2:NAND]-(:Point) "
664
+ "WITH n, impl_count, count(r2) AS nand_count "
665
+ "RETURN n.id, impl_count, nand_count, "
666
+ " CASE WHEN impl_count + nand_count > 0 "
667
+ " THEN toFloat(nand_count) / (impl_count + nand_count) "
668
+ " ELSE 0.0 "
669
+ " END AS contention, "
670
+ " coalesce(n.ep_alpha, 1.0) AS alpha, coalesce(n.ep_beta, 1.0) AS beta, "
671
+ " n.ep_alpha IS NOT NULL AS has_ep "
672
+ )
673
+ rows = graph.query(cypher, params={"ids": point_ids}).result_set
674
+
675
+ breakdowns: dict[str, EpBreakdown] = {}
676
+ for row in rows:
677
+ pid, impl, nand, contention, alpha, beta, has_ep = row[0], int(row[1]), int(row[2]), float(row[3]), float(row[4]), float(row[5]), row[6]
678
+ total = impl + nand
679
+ confidence_mean = impl / total if total > 0 else 0.0
680
+ variance = _beta_variance(alpha, beta)
681
+ breakdowns[pid] = EpBreakdown(
682
+ confidence_mean=confidence_mean,
683
+ evidence=EpEvidence(impl_count=impl, nand_count=nand, total=total),
684
+ contention=contention,
685
+ variance=round(variance, 6),
686
+ # Contested only when EP actually ran: an uncalibrated point
687
+ # (no persisted α/β → defaults to 1/1 → v=1/12) is NOT
688
+ # contested, it's unmeasured.
689
+ contested=bool(has_ep) and variance > CONTESTED_VARIANCE_THRESHOLD,
690
+ )
691
+
692
+ # Fill in defaults for IDs with no edges
693
+ for pid in point_ids:
694
+ if pid not in breakdowns:
695
+ breakdowns[pid] = EpBreakdown(
696
+ confidence_mean=0.0,
697
+ evidence=EpEvidence(impl_count=0, nand_count=0, total=0),
698
+ contention=0.0,
699
+ )
700
+
701
+ return breakdowns
702
+ except Exception as e:
703
+ logger.warning("EP batch annotation failed: %s", e)
704
+ return {}
705
+
706
+
707
+ def get_relationships(graph, point_ids: list[str]) -> dict[str, list[dict]]:
708
+ """Fetch operator-edge relationships for a batch of Point IDs.
709
+
710
+ Single Cypher query — NOT N+1. Returns dict mapping point_id → list of
711
+ relationship dicts with {predicate, mechanism, related_id, related_kind,
712
+ related_content, direction, operator_id}.
713
+
714
+ Points with no operator edges get an empty list.
715
+ """
716
+ if not point_ids:
717
+ return {}
718
+
719
+ rels: dict[str, list[dict]] = {pid: [] for pid in point_ids}
720
+
721
+ try:
722
+ cypher = (
723
+ "MATCH (n:Point) WHERE n.id IN $ids "
724
+ "MATCH (n)-[r:IMPL|NAND|hasPart]-(op:Point {is_operator:true}) "
725
+ "MATCH (op)-[r2:IMPL|NAND|hasPart]-(other:Point) "
726
+ "WHERE other.id <> n.id "
727
+ " AND (other.is_operator IS NULL OR other.is_operator = false) "
728
+ "RETURN n.id, op.op_type AS mechanism, "
729
+ " coalesce(op.label, '') AS predicate, "
730
+ " op.id AS operator_id, other.id AS related_id, "
731
+ " other.pointKind AS related_kind, "
732
+ " other.content AS related_content, "
733
+ " r.idx AS n_idx, r2.idx AS other_idx"
734
+ )
735
+ rows = graph.query(cypher, params={"ids": point_ids}).result_set
736
+
737
+ for row in rows:
738
+ pid = row[0]
739
+ mechanism = row[1] or "IMPL"
740
+ predicate = row[2]
741
+ operator_id = row[3]
742
+ related_id = row[4]
743
+ related_kind = row[5] or ""
744
+ related_content = row[6] or ""
745
+ n_idx = row[7] if len(row) > 7 else None
746
+ other_idx = row[8] if len(row) > 8 else None
747
+
748
+ # Determine direction: idx=0 = source, idx>0 = target.
749
+ # Our point is source → relationship is outgoing.
750
+ # Our point is target + other is source → relationship is incoming.
751
+ if n_idx is not None and n_idx == 0:
752
+ direction = "outgoing"
753
+ else:
754
+ direction = "incoming"
755
+
756
+ rel_entry = {
757
+ "predicate": predicate if predicate else "",
758
+ "mechanism": mechanism,
759
+ "related_id": related_id,
760
+ "related_kind": related_kind,
761
+ "related_content": related_content[:200] if related_content else "",
762
+ "direction": direction,
763
+ "operator_id": operator_id,
764
+ }
765
+ if pid in rels:
766
+ rels[pid].append(rel_entry)
767
+ except Exception:
768
+ logger.warning("Relationship query failed", exc_info=True)
769
+
770
+ return rels
771
+
772
+
773
+ # ── TF-IDF fallback (in-memory, from embeddings.py) ─────────────────────────
774
+
775
+ # ── Relationship / Traversal filters (#7846) ──────────────────────────────────
776
+
777
+ def filter_by_relationship(
778
+ graph,
779
+ point_ids: list[str],
780
+ predicate: str,
781
+ target_id: str,
782
+ entity_type: str = "point",
783
+ id_field: str = "id",
784
+ ) -> list[str]:
785
+ """Post-filter: keep only points connected to target_id via operator with label=predicate.
786
+
787
+ Operators are middle entities — Product→(op:contains)→Feature = 2 graph hops.
788
+ Traversal: point <-[IMPL]-(op {label:predicate})-[IMPL]-> target.
789
+ Returns filtered list of point IDs (subset of input).
790
+ """
791
+ if not point_ids or not predicate or not target_id:
792
+ return []
793
+ # Relationship filters only make sense for Point-backed entities — the chain
794
+ # always traverses operator edges, which only connect Points. Bail early
795
+ # with a warning instead of silently returning empty for unsupported types.
796
+ if entity_type not in ("point", "operator"):
797
+ logger.warning("Relationship filters not supported for entity_type=%s", entity_type)
798
+ return []
799
+ try:
800
+ # Operators are Points with is_operator=true — no Operator label exists (#148).
801
+ # Map both point and operator to the Point label, mirroring
802
+ # run_fts_query / run_structural_query label logic.
803
+ label = "Point"
804
+ is_operator_clause = " AND n.is_operator = true" if entity_type == "operator" else ""
805
+ cypher = (
806
+ f"MATCH (n:{label}) WHERE n.{id_field} IN $ids{is_operator_clause} "
807
+ f"MATCH (n)<-[r1:hasPart|IMPL|NAND]-(op:Point {{is_operator:true, label:$pred}})"
808
+ f"-[r2:hasPart|IMPL|NAND]->(t:{label} {{{id_field}: $tid}}) "
809
+ f"RETURN DISTINCT n.{id_field}"
810
+ )
811
+ rows = graph.query(
812
+ cypher,
813
+ params={"ids": point_ids, "pred": predicate, "tid": target_id},
814
+ ).result_set
815
+ return [row[0] for row in rows]
816
+ except Exception:
817
+ logger.warning("Relationship filter failed — returning empty", exc_info=True)
818
+ return []
819
+
820
+
821
+ def filter_by_traversal_predicate(
822
+ graph,
823
+ point_ids: list[str],
824
+ predicate: str,
825
+ entity_type: str = "point",
826
+ id_field: str = "id",
827
+ ) -> list[str]:
828
+ """Post-filter: keep only points that participate in ANY operator with label=predicate.
829
+
830
+ Points are matched if they are either the source or target of an operator
831
+ carrying the given predicate label. Returns filtered list of point IDs.
832
+ """
833
+ if not point_ids or not predicate:
834
+ return []
835
+ # Traversal predicate filters only make sense for Point-backed entities —
836
+ # the chain always traverses operator edges, which only connect Points.
837
+ # Bail early with a warning instead of silently returning empty for
838
+ # unsupported types.
839
+ if entity_type not in ("point", "operator"):
840
+ logger.warning(
841
+ "Traversal predicate filters not supported for entity_type=%s", entity_type
842
+ )
843
+ return []
844
+ try:
845
+ # Operators are Points with is_operator=true — no Operator label exists (#148).
846
+ # Map both point and operator to the Point label, mirroring
847
+ # run_fts_query / run_structural_query label logic.
848
+ label = "Point"
849
+ is_operator_clause = " AND n.is_operator = true" if entity_type == "operator" else ""
850
+ cypher = (
851
+ f"MATCH (n:{label}) WHERE n.{id_field} IN $ids{is_operator_clause} "
852
+ f"MATCH (n)<-[r:hasPart|IMPL|NAND]-(op:Point {{is_operator:true, label:$pred}}) "
853
+ f"RETURN DISTINCT n.{id_field}"
854
+ )
855
+ rows = graph.query(
856
+ cypher,
857
+ params={"ids": point_ids, "pred": predicate},
858
+ ).result_set
859
+ return [row[0] for row in rows]
860
+ except Exception:
861
+ logger.warning("Traversal predicate filter failed — returning empty", exc_info=True)
862
+ return []
863
+
864
+
865
+ def fallback_tfidf(query: str, points: list[dict], limit: int = 10) -> list[dict]:
866
+ """Last-resort TF-IDF fallback when all FalkorDB strategies fail.
867
+
868
+ points should be dicts with at least 'id', 'content', 'pointKind'.
869
+ """
870
+ try:
871
+ from tortoise.embeddings import search_points
872
+ meta = {p["id"]: p for p in points if p.get("id")}
873
+ results = search_points(query, points, threshold=0.0, limit=limit)
874
+ return [
875
+ SearchResult(
876
+ id=r["id"],
877
+ content=r["content"],
878
+ point_kind=meta.get(r["id"], {}).get("pointKind", ""),
879
+ scores=SearchScores(fts=None, vector=None, structural=None, rrf=r["similarity"]),
880
+ match_source="tfidf",
881
+ ep=None,
882
+ ).to_dict()
883
+ for r in results
884
+ ]
885
+ except Exception as e:
886
+ logger.error("TF-IDF fallback failed: %s", e)
887
+ return []