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
tortoise/ep.py ADDED
@@ -0,0 +1,534 @@
1
+ """EP (Expectation Propagation) belief propagation for Tortoise.
2
+
3
+ Uses Beta messages in natural parameter space. Moment projection
4
+ via Gauss-Jacobi quadrature on [0,1]². Batch I/O eliminates
5
+ FalkorDBLite SQLite concurrent-write crashes (#6761).
6
+
7
+ See: tortoise/research/reflection-agentic-systems/ep-implementation-plan.md
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import random
13
+
14
+ from .quadrature import tilted_moments, moments_to_beta, phi_nand, phi_impl
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class TortoiseEP:
20
+ """EP belief propagation on Tortoise factor graphs.
21
+
22
+ Operates on the FalkorProjection's graph. Uses batch I/O:
23
+ loads all affected data into Python dicts at the start of each
24
+ iteration, computes factor updates in Python, flushes writes at end.
25
+
26
+ Parameters:
27
+ projection: FalkorProjection instance (provides .g and ._neighbors)
28
+ damping: message damping factor, 0 < λ ≤ 1
29
+ n_quad: Gauss-Jacobi points per dimension (8 = 0.03% error at
30
+ w=50; at w=100 the n_quad=8 error is ~7% — use n_quad=16 for
31
+ w≥100, which recovers to <0.002% error)
32
+ max_iter: hard cap on EP outer iterations
33
+ tol: convergence threshold (max relative change in α,β)
34
+ """
35
+
36
+ def __init__(self, projection, *, damping=0.5, n_quad=8,
37
+ max_iter=50, tol=1e-3, evidence=None):
38
+ self.proj = projection
39
+ self.g = projection.g
40
+ self.damping = damping
41
+ self.n_quad = n_quad
42
+ self.max_iter = max_iter
43
+ self.tol = tol
44
+ # Fixed evidence priors: {claim_id: (alpha, beta)}
45
+ self._evidence = dict(evidence) if evidence else {}
46
+
47
+ # ── Batch I/O cache (#6761) ──────────────────────────────────
48
+
49
+ def _load_cache(self, affected_claims: set[str]):
50
+ """Load all node params and edge messages into Python dicts."""
51
+ self._node_cache: dict[str, tuple[float, float]] = {}
52
+ self._msg_cache: dict[tuple[str, str, str], tuple[float, float]] = {}
53
+
54
+ if affected_claims:
55
+ rows = self.g.query(
56
+ "MATCH (n:Point) WHERE n.id IN $ids "
57
+ "RETURN n.id, coalesce(n.ep_alpha,1.0), coalesce(n.ep_beta,1.0)",
58
+ params={"ids": list(affected_claims)},
59
+ ).result_set
60
+ for cid, a, b in rows:
61
+ self._node_cache[cid] = (float(a), float(b))
62
+
63
+ for rel in ("IMPL", "NAND"):
64
+ rows = self.g.query(
65
+ f"MATCH (o:Point)-[r:{rel}]->(c:Point) "
66
+ "WHERE c.id IN $ids "
67
+ "RETURN o.id, c.id, coalesce(r.msg_alpha,0.0), coalesce(r.msg_beta,0.0)",
68
+ params={"ids": list(affected_claims)},
69
+ ).result_set
70
+ for oid, cid, ma, mb in rows:
71
+ self._msg_cache[(oid, cid, rel)] = (float(ma), float(mb))
72
+
73
+ def _flush_cache(self):
74
+ """Write all cached data back to FalkorDB in batch.
75
+
76
+ Attribute-safe (#330): caches may be absent (never loaded, or removed
77
+ by the per-run lifecycle) — flush whatever is present.
78
+ """
79
+ if getattr(self, "_node_cache", None):
80
+ params_list = [
81
+ {"id": cid, "a": a, "b": b,
82
+ "c": round(a/(a+b), 4) if (a + b) > 0 else 0.5}
83
+ for cid, (a, b) in self._node_cache.items()
84
+ ]
85
+ self.g.query(
86
+ "UNWIND $params AS p "
87
+ "MATCH (n:Point {id: p.id}) "
88
+ "SET n.ep_alpha = p.a, n.ep_beta = p.b, n.confidence = p.c",
89
+ params={"params": params_list},
90
+ )
91
+
92
+ if getattr(self, "_msg_cache", None):
93
+ for rel in ("IMPL", "NAND"):
94
+ params_list = [
95
+ {"oid": oid, "cid": cid, "a": ma, "b": mb}
96
+ for (oid, cid, r), (ma, mb) in self._msg_cache.items()
97
+ if r == rel
98
+ ]
99
+ if params_list:
100
+ self.g.query(
101
+ f"UNWIND $params AS p "
102
+ f"MATCH (o:Point {{id: p.oid}})-[r:{rel}]->(c:Point {{id: p.cid}}) "
103
+ "SET r.msg_alpha = p.a, r.msg_beta = p.b",
104
+ params={"params": params_list},
105
+ )
106
+
107
+ def _clear_caches(self) -> None:
108
+ """Remove the batch caches so post-run reads hit the graph (#330)."""
109
+ for _attr in ("_node_cache", "_msg_cache"):
110
+ if hasattr(self, _attr):
111
+ delattr(self, _attr)
112
+
113
+ # ── Cached read/write ────────────────────────────────────────
114
+
115
+ def _read_node(self, node_id: str) -> tuple[float, float]:
116
+ # #330: capture once — a concurrent run() may delattr the cache between
117
+ # the hasattr check and the read (TOCTOU); a local None falls through
118
+ # to the graph instead of raising AttributeError.
119
+ _cache = getattr(self, '_node_cache', None)
120
+ if _cache is not None and node_id in _cache:
121
+ return _cache[node_id]
122
+ rows = self.g.query(
123
+ "MATCH (n:Point {id:$id}) "
124
+ "RETURN coalesce(n.ep_alpha, 1.0), coalesce(n.ep_beta, 1.0)",
125
+ params={"id": node_id},
126
+ ).result_set
127
+ return (float(rows[0][0]), float(rows[0][1])) if rows else (1.0, 1.0)
128
+
129
+ def _write_node(self, node_id: str, alpha: float, beta: float) -> None:
130
+ _cache = getattr(self, '_node_cache', None)
131
+ if _cache is not None:
132
+ _cache[node_id] = (alpha, beta)
133
+ return
134
+ # #330: guard degenerate (0,0) params — uniform fallback instead of ZDE
135
+ mean = round(alpha / (alpha + beta), 4) if (alpha + beta) > 0 else 0.5
136
+ self.g.query(
137
+ "MATCH (n:Point {id:$id}) "
138
+ "SET n.ep_alpha=$a, n.ep_beta=$b, n.confidence=$c",
139
+ params={"id": node_id, "a": alpha, "b": beta, "c": mean},
140
+ )
141
+
142
+ def _read_message(self, op_id: str, claim_id: str,
143
+ rel_type: str = "IMPL") -> tuple[float, float]:
144
+ key = (op_id, claim_id, rel_type)
145
+ _cache = getattr(self, '_msg_cache', None)
146
+ if _cache is not None and key in _cache:
147
+ return _cache[key]
148
+ rows = self.g.query(
149
+ f"MATCH (o:Point {{id:$oid}})-[r:{rel_type}]->(c:Point {{id:$cid}}) "
150
+ "RETURN coalesce(r.msg_alpha, 0.0), coalesce(r.msg_beta, 0.0)",
151
+ params={"oid": op_id, "cid": claim_id},
152
+ ).result_set
153
+ return (float(rows[0][0]), float(rows[0][1])) if rows else (0.0, 0.0)
154
+
155
+ def _write_message(self, op_id: str, claim_id: str,
156
+ msg_alpha: float, msg_beta: float,
157
+ rel_type: str = "IMPL") -> None:
158
+ key = (op_id, claim_id, rel_type)
159
+ _cache = getattr(self, '_msg_cache', None)
160
+ if _cache is not None:
161
+ _cache[key] = (msg_alpha, msg_beta)
162
+ return
163
+ self.g.query(
164
+ f"MATCH (o:Point {{id:$oid}})-[r:{rel_type}]->(c:Point {{id:$cid}}) "
165
+ "SET r.msg_alpha=$a, r.msg_beta=$b",
166
+ params={"oid": op_id, "cid": claim_id, "a": msg_alpha, "b": msg_beta},
167
+ )
168
+
169
+ # ── Natural parameter helpers ─────────────────────────────────
170
+
171
+ @staticmethod
172
+ def _natural_from_beta(alpha: float, beta: float) -> tuple[float, float]:
173
+ return (alpha - 1, beta - 1)
174
+
175
+ @staticmethod
176
+ def _beta_from_natural(eta1: float, eta2: float) -> tuple[float, float]:
177
+ return (max(eta1 + 1, 0.01), max(eta2 + 1, 0.01))
178
+
179
+ def _posterior_natural(self, claim_id: str) -> tuple[float, float]:
180
+ alpha, beta = self._read_node(claim_id)
181
+ return self._natural_from_beta(alpha, beta)
182
+
183
+
184
+ def _cavity_natural(self, claim_id: str, op_id: str,
185
+ rel_type: str) -> tuple[float, float]:
186
+ post_eta1, post_eta2 = self._posterior_natural(claim_id)
187
+ msg_eta1, msg_eta2 = self._read_message(op_id, claim_id, rel_type)
188
+ return (post_eta1 - msg_eta1, post_eta2 - msg_eta2)
189
+
190
+ # ── Single-factor EP update ───────────────────────────────────
191
+
192
+ def _is_strong(self, claim_id: str, threshold: float = 0.85) -> bool:
193
+ """True if the claim's current belief is at/above the given threshold.
194
+
195
+ Used for bidirectional IMPL back-message semantics (#86): a target that
196
+ is still strong (>= threshold) keeps the source's support unchanged; a
197
+ weakened target triggers a reduction signal to the source.
198
+ """
199
+ _cache = getattr(self, "_node_cache", None)
200
+ if _cache is not None and claim_id in _cache:
201
+ a, b = _cache[claim_id]
202
+ mean = a / (a + b) if (a + b) > 0 else 0.5
203
+ return mean >= threshold
204
+ rows = self.g.query(
205
+ "MATCH (n:Point {id:$id}) RETURN n.ep_alpha, n.ep_beta",
206
+ params={"id": claim_id},
207
+ ).result_set
208
+ if not rows or rows[0][0] is None:
209
+ return False
210
+ a, b = float(rows[0][0]), float(rows[0][1])
211
+ # #330: guard degenerate (0,0) params (cache path already guards)
212
+ return a / (a + b) >= threshold if (a + b) > 0 else False
213
+
214
+ def _update_factor(self, op_id: str, op_type: str,
215
+ input_ids: list[str], weight: float = 1.0,
216
+ label: str | None = None,
217
+ direction: str = "bidirectional") -> None:
218
+ if len(input_ids) < 2:
219
+ return
220
+ if len(input_ids) > 2:
221
+ return self._update_nary_factor(op_id, op_type, input_ids, weight, label, direction)
222
+
223
+ id_a, id_b = input_ids
224
+
225
+ cav_eta_a = self._cavity_natural(id_a, op_id, op_type)
226
+ cav_eta_b = self._cavity_natural(id_b, op_id, op_type)
227
+ alpha_a, beta_a = self._beta_from_natural(*cav_eta_a)
228
+ alpha_b, beta_b = self._beta_from_natural(*cav_eta_b)
229
+
230
+ phi = phi_nand if op_type == "NAND" else phi_impl
231
+ mom_a, mom_b = tilted_moments(
232
+ alpha_a, beta_a, alpha_b, beta_b, weight, phi, self.n_quad
233
+ )
234
+
235
+ new_alpha_a, new_beta_a = moments_to_beta(*mom_a)
236
+ new_alpha_b, new_beta_b = moments_to_beta(*mom_b)
237
+ new_eta_a = self._natural_from_beta(new_alpha_a, new_beta_a)
238
+ new_eta_b = self._natural_from_beta(new_alpha_b, new_beta_b)
239
+
240
+ raw_eta_a = (new_eta_a[0] - cav_eta_a[0], new_eta_a[1] - cav_eta_a[1])
241
+ raw_eta_b = (new_eta_b[0] - cav_eta_b[0], new_eta_b[1] - cav_eta_b[1])
242
+
243
+ # Determine if this operator is bidirectional.
244
+ # Direction is an explicit operator flag (ONTOLOGY v3.1 §3.1, §8).
245
+ # Default and missing → bidirectional.
246
+ bidirectional = (direction == "bidirectional")
247
+
248
+ # For bidirectional IMPL, the back-message to the source must
249
+ # carry the TARGET's state as a reduction signal — if the target is
250
+ # weakened (by NAND or low evidence), the source must be pulled DOWN,
251
+ # not given a weak positive agreement push. Recompute the back-message
252
+ # with NAND-style coupling (contradiction) when the target is below its
253
+ # cavity prior, so bidirectional operators propagate damage upward (#86).
254
+ if (op_type == "IMPL" and bidirectional and not self._is_strong(id_b)):
255
+ mom_bk, _ = tilted_moments(
256
+ alpha_a, beta_a, alpha_b, beta_b, weight, phi_nand, self.n_quad
257
+ )
258
+ new_a_bk, new_b_bk = moments_to_beta(*mom_bk)
259
+ new_eta_a = self._natural_from_beta(new_a_bk, new_b_bk)
260
+ raw_eta_a = (new_eta_a[0] - cav_eta_a[0], new_eta_a[1] - cav_eta_a[1])
261
+
262
+ # Proportional boost: breaks EP fixed-point symmetry that forces
263
+ # messages to near-zero for unevidenced targets. Fades as evidence
264
+ # accumulates: Beta(1,1)=7× boost, Beta(4,4)=1.5×, Beta(10,10)=1×.
265
+ alpha_a, beta_a = self._beta_from_natural(*cav_eta_a)
266
+ alpha_b, beta_b = self._beta_from_natural(*cav_eta_b)
267
+ boost_a = 1.0 + 2.0 / max(alpha_a + beta_a - 1.0, 1.0)
268
+ boost_b = 1.0 + 2.0 / max(alpha_b + beta_b - 1.0, 1.0)
269
+ raw_eta_a = (raw_eta_a[0] * boost_a, raw_eta_a[1] * boost_a)
270
+ raw_eta_b = (raw_eta_b[0] * boost_b, raw_eta_b[1] * boost_b)
271
+
272
+ d = self.damping
273
+ old_eta_a = self._read_message(op_id, id_a, op_type)
274
+ old_eta_b = self._read_message(op_id, id_b, op_type)
275
+
276
+ damped_a = (d * raw_eta_a[0] + (1 - d) * old_eta_a[0],
277
+ d * raw_eta_a[1] + (1 - d) * old_eta_a[1])
278
+ damped_b = (d * raw_eta_b[0] + (1 - d) * old_eta_b[0],
279
+ d * raw_eta_b[1] + (1 - d) * old_eta_b[1])
280
+
281
+ damped_a = (max(min(damped_a[0], 1000), -1000),
282
+ max(min(damped_a[1], 1000), -1000))
283
+ damped_b = (max(min(damped_b[0], 1000), -1000),
284
+ max(min(damped_b[1], 1000), -1000))
285
+
286
+ self._write_message(op_id, id_b, *damped_b, op_type)
287
+ if bidirectional:
288
+ self._write_message(op_id, id_a, *damped_a, op_type)
289
+
290
+ def _update_nary_factor(self, op_id: str, op_type: str,
291
+ input_ids: list[str], weight: float = 1.0,
292
+ label: str | None = None,
293
+ direction: str = "bidirectional") -> None:
294
+ # input_ids are sorted by idx (source=0, targets=1..N).
295
+ # For IMPL: only create source→target pairs (skip target↔target).
296
+ # For NAND: create all pairwise combinations (full mutual contradiction).
297
+ if op_type == "IMPL" and len(input_ids) >= 2:
298
+ # Source is input_ids[0] (idx=0). Targets are input_ids[1:].
299
+ for j in range(1, len(input_ids)):
300
+ self._update_factor(op_id, op_type,
301
+ [input_ids[0], input_ids[j]], weight, label, direction)
302
+ else:
303
+ for i in range(len(input_ids)):
304
+ for j in range(i + 1, len(input_ids)):
305
+ self._update_factor(op_id, op_type,
306
+ [input_ids[i], input_ids[j]], weight, label, direction)
307
+
308
+ def _update_claim_posterior(self, claim_id: str,
309
+ run_evidence: dict | None = None) -> None:
310
+ # Start from evidence prior in natural parameter space.
311
+ # #330: consume the run-scoped evidence (constructor + run-level),
312
+ # never the instance dict directly.
313
+ ev = (run_evidence or self._evidence).get(claim_id)
314
+ if ev:
315
+ total_eta1, total_eta2 = ev[0] - 1.0, ev[1] - 1.0
316
+ else:
317
+ total_eta1, total_eta2 = 0.0, 0.0
318
+ if hasattr(self, '_msg_cache'):
319
+ for (oid, cid, rel), (ma, mb) in self._msg_cache.items():
320
+ if cid == claim_id:
321
+ total_eta1 += ma
322
+ total_eta2 += mb
323
+ else:
324
+ for rel in ("IMPL", "NAND"):
325
+ rows = self.g.query(
326
+ f"MATCH (o:Point)-[r:{rel}]->(c:Point {{id:$cid}}) "
327
+ "RETURN coalesce(r.msg_alpha,0.0), coalesce(r.msg_beta,0.0)",
328
+ params={"cid": claim_id},
329
+ ).result_set
330
+ for ma, mb in rows:
331
+ total_eta1 += float(ma)
332
+ total_eta2 += float(mb)
333
+ alpha, beta = self._beta_from_natural(total_eta1, total_eta2)
334
+ self._write_node(claim_id, alpha, beta)
335
+
336
+ # ── Affected subgraph extraction ──────────────────────────────
337
+
338
+ def _affected_claims(self, operator_ids: list[str],
339
+ max_hops: int = 2) -> set[str]:
340
+ affected: set[str] = set()
341
+ for op_id in operator_ids:
342
+ rows = self.g.query(
343
+ "MATCH (o:Point {id:$oid})-[r:IMPL|NAND]->(c:Point) "
344
+ "RETURN DISTINCT c.id",
345
+ params={"oid": op_id},
346
+ ).result_set
347
+ affected.update(r[0] for r in rows)
348
+
349
+ if max_hops > 0 and affected:
350
+ frontier = list(affected)
351
+ for _ in range(max_hops):
352
+ new_frontier: list[str] = []
353
+ for claim_id in frontier:
354
+ for nid in self.proj._neighbors(claim_id):
355
+ if nid not in affected:
356
+ affected.add(nid)
357
+ new_frontier.append(nid)
358
+ frontier = new_frontier
359
+ if not frontier:
360
+ break
361
+ return affected
362
+
363
+ def _affected_factors(self, affected_claims: set[str]
364
+ ) -> list[tuple[str, str, list[str], float, str | None, str]]:
365
+ factors: list[tuple[str, str, list[str], float, str | None, str]] = []
366
+ seen: set[str] = set()
367
+ for claim_id in affected_claims:
368
+ for rel in ("IMPL", "NAND"):
369
+ rows = self.g.query(
370
+ f"MATCH (o:Point)-[r:{rel}]->(c:Point {{id:$cid}}) "
371
+ "RETURN o.id, o.op_type, o.label, o.direction",
372
+ params={"cid": claim_id},
373
+ ).result_set
374
+ for op_id, op_type, label, direction in rows:
375
+ # Defensive: pre-migration operators without direction default to bidirectional
376
+ if direction is None:
377
+ direction = "bidirectional"
378
+ logger.warning(
379
+ "Operator %s has no direction property — defaulting to 'bidirectional'. "
380
+ "Run graph-scripts/migrate_direction.py to backfill.",
381
+ op_id,
382
+ )
383
+ if op_id not in seen:
384
+ seen.add(op_id)
385
+ # ORDER BY r.idx ensures source (idx=0) comes first.
386
+ # This is required for directional IMPL: id_a = source,
387
+ # id_b = target so that back-messages are correctly skipped.
388
+ input_rows = self.g.query(
389
+ "MATCH (o:Point {id:$oid})-[r:IMPL|NAND]->(c:Point) "
390
+ "RETURN c.id "
391
+ "ORDER BY coalesce(r.idx, 0)",
392
+ params={"oid": op_id},
393
+ ).result_set
394
+ input_ids = [r[0] for r in input_rows]
395
+ from .weights import compute_operator_weight
396
+ weight = compute_operator_weight(self.proj, op_id)
397
+ factors.append((op_id, op_type, input_ids, weight, label, direction))
398
+ return factors
399
+
400
+ # ── Calibration ──────────────────────────────────────────────
401
+
402
+ @staticmethod
403
+ def confidence_to_prior(confidence: float, k: float = 2.0,
404
+ uniform_threshold: float = 0.05) -> tuple[float, float]:
405
+ """Convert extractor confidence (0-1) to Beta(α, β) prior.
406
+
407
+ Extractor confidence 0.8 → Beta(1+0.8k, 1+0.2k).
408
+ Confidence near 0.5 → Beta(1,1) uniform (no information).
409
+
410
+ Args:
411
+ confidence: extractor confidence in [0, 1]
412
+ k: evidence strength multiplier (default 2 = mild prior)
413
+ uniform_threshold: |c-0.5| < threshold → uniform prior
414
+ """
415
+ if abs(confidence - 0.5) < uniform_threshold:
416
+ return (1.0, 1.0)
417
+ return (1.0 + confidence * k, 1.0 + (1.0 - confidence) * k)
418
+
419
+ # ── Public API ────────────────────────────────────────────────
420
+
421
+ def compute_confidence(self, claim_id: str) -> dict:
422
+ a, b = self._read_node(claim_id)
423
+ total = a + b
424
+ if total <= 0:
425
+ # #330: degenerate stored params (0,0) — uniform Beta(1,1) fallback
426
+ # instead of ZeroDivisionError.
427
+ return {"mean": 0.5, "variance": 1/12,
428
+ "alpha": a, "beta": b, "effective_n": 0}
429
+ return {
430
+ "mean": a / total,
431
+ "variance": (a * b) / (total * total * (total + 1)),
432
+ "alpha": a, "beta": b, "effective_n": total,
433
+ }
434
+
435
+ def get_contested_claims(self, variance_threshold: float = 0.04) -> list[dict]:
436
+ rows = self.g.query(
437
+ "MATCH (n:Point) "
438
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
439
+ "WITH n, coalesce(n.ep_alpha,1.0) AS a, coalesce(n.ep_beta,1.0) AS b "
440
+ "WITH n, a, b, (a*b)/((a+b)*(a+b)*(a+b+1)) AS v "
441
+ "WHERE v > $t RETURN n.id, n.content, a, b, v ORDER BY v DESC",
442
+ params={"t": variance_threshold},
443
+ ).result_set
444
+ return [{"id": r[0], "content": r[1], "alpha": r[2],
445
+ "beta": r[3], "variance": r[4]} for r in rows]
446
+
447
+ def run(self, operator_ids: list[str], max_hops: int = 2,
448
+ evidence: dict[str, tuple[float, float]] | None = None
449
+ ) -> tuple[int, bool]:
450
+ """Run EP to convergence. Batch I/O avoids SQLite crashes (#6761).
451
+
452
+ Args:
453
+ operator_ids: operator node IDs to include
454
+ max_hops: how far to extend the affected subgraph
455
+ evidence: optional {claim_id: (alpha, beta)} priors —
456
+ merged with any evidence set at construction time.
457
+ Evidence set at run() overrides per-claim.
458
+ """
459
+ # Run-level evidence is CALL-SCOPED (#330): merge into a local dict so
460
+ # self._evidence is never mutated by run() — otherwise a later run()
461
+ # without evidence would re-apply (and re-write to the graph) stale
462
+ # run-level priors. Constructor evidence still applies every run.
463
+ run_evidence = dict(self._evidence)
464
+ if evidence:
465
+ run_evidence.update(evidence)
466
+
467
+ # Cache lifecycle (#330): _node_cache/_msg_cache are a per-run working
468
+ # set. Remove them at entry (before the evidence pre-write and the
469
+ # early returns) so a run that exits early never leaves stale cache
470
+ # behind for public reads (_read_node/_write_node fall through to the
471
+ # graph when the attribute is absent).
472
+ for _attr in ("_node_cache", "_msg_cache"):
473
+ if hasattr(self, _attr):
474
+ delattr(self, _attr)
475
+
476
+ # Apply evidence priors to graph before EP iterations.
477
+ # ponytail: direct graph write so evidence is visible even
478
+ # when there are no operators / affected claims.
479
+ if run_evidence:
480
+ params_list = [
481
+ {"id": cid, "a": a, "b": b}
482
+ for cid, (a, b) in run_evidence.items()
483
+ ]
484
+ self.g.query(
485
+ "UNWIND $params AS p "
486
+ "MATCH (n:Point {id: p.id}) "
487
+ "SET n.ep_alpha = p.a, n.ep_beta = p.b",
488
+ params={"params": params_list},
489
+ )
490
+
491
+ affected = self._affected_claims(operator_ids, max_hops)
492
+ if not affected:
493
+ return 0, True
494
+
495
+ factors = self._affected_factors(affected)
496
+ if not factors:
497
+ return 0, True
498
+
499
+ # Load once from graph, then run entirely in memory.
500
+ # Only flush final results at the end — eliminates per-iteration I/O.
501
+ self._load_cache(affected)
502
+
503
+ for iteration in range(self.max_iter):
504
+ # Re-load only on iteration 0 (already loaded above)
505
+ # Subsequent iterations use in-memory cache updated by _write_node/_write_message
506
+
507
+ prev = {cid: self._node_cache.get(cid, (1.0, 1.0))
508
+ for cid in affected}
509
+
510
+ random.shuffle(factors)
511
+ for op_id, op_type, input_ids, weight, label, direction in factors:
512
+ self._update_factor(op_id, op_type, input_ids, weight, label, direction)
513
+
514
+ for cid in affected:
515
+ self._update_claim_posterior(cid, run_evidence)
516
+
517
+ max_change = 0.0
518
+ for cid in affected:
519
+ new_a, new_b = self._node_cache.get(cid, (1.0, 1.0))
520
+ old_a, old_b = prev.get(cid, (1.0, 1.0))
521
+ change = max(
522
+ abs(new_a - old_a) / max(old_a, 1e-6),
523
+ abs(new_b - old_b) / max(old_b, 1e-6),
524
+ )
525
+ max_change = max(max_change, change)
526
+
527
+ if max_change < self.tol:
528
+ self._flush_cache()
529
+ self._clear_caches()
530
+ return iteration + 1, True
531
+
532
+ self._flush_cache()
533
+ self._clear_caches()
534
+ return self.max_iter, False
tortoise/exceptions.py ADDED
@@ -0,0 +1,16 @@
1
+ """Tortoise SDK exceptions."""
2
+
3
+
4
+ class CalibrationError(Exception):
5
+ """Raised when require_calibration=True and the graph is uncalibrated."""
6
+ pass
7
+
8
+
9
+ class ControlPlaneError(ValueError):
10
+ """Registry operation failed — duplicate, not found, invalid role, etc."""
11
+ pass
12
+
13
+
14
+ class AuditLogError(RuntimeError):
15
+ """Fatal audit log failure — Postgres unreachable and fallback exhausted."""
16
+ pass