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,744 @@
1
+ """Embedded redislite orphan reaper.
2
+
3
+ Finds orphaned redis-server processes spawned by redislite embedded mode and
4
+ classifies them for safe cleanup (issue #176, plan Child 1).
5
+
6
+ Classification (dual-signal):
7
+ - socket NOT under tempfile.gettempdir() -> protected (path-based)
8
+ - registry has named db_filename -> protected (path-based)
9
+ - old-format registry (no db_filename) + .db file -> protected
10
+ - unknown old-format dirname pattern -> protected (WARNING)
11
+ - tempdir socket + uptime < MIN_UPTIME -> protected (boot cooldown)
12
+ - tempdir socket + uptime >= MIN_UPTIME + no db_filename + no .db -> candidate
13
+
14
+ NEVER_KILL: anything classified protected (stable singleton, path-based
15
+ servers, boot-cooldown servers, unknown patterns). Only candidates may be
16
+ reaped, and only after liveness + CLIENT LIST verification (see reap()).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import logging
22
+ import os
23
+ import re
24
+ import shutil
25
+ import socket
26
+ import subprocess
27
+ import tempfile
28
+ import time
29
+ from pathlib import Path
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ MIN_UPTIME_DEFAULT = 30
34
+ PROBE_TIMEOUT = 2.0 # seconds for raw socket probes
35
+ _AUTOGEN_DIRNAME = re.compile(r"^(redislite_|tmp)[a-zA-Z0-9_]+$")
36
+
37
+
38
+ def _parse_min_uptime() -> int:
39
+ """Parse TORTOISE_REAPER_MIN_UPTIME (float-safe, shared by CLI + discover).
40
+
41
+ - float strings (e.g. "30.5") parsed as float then truncated
42
+ - negative -> 0 (with warning)
43
+ - non-numeric / empty -> default 30 (with warning)
44
+ - huge (> 3600) -> accepted with warning
45
+ """
46
+ raw = os.environ.get("TORTOISE_REAPER_MIN_UPTIME", "")
47
+ if raw == "":
48
+ return MIN_UPTIME_DEFAULT
49
+ try:
50
+ val = int(float(raw)) # float-safe: "30.5" -> 30
51
+ except (ValueError, TypeError):
52
+ logger.warning(
53
+ "TORTOISE_REAPER_MIN_UPTIME=%r not numeric — using default %s",
54
+ raw, MIN_UPTIME_DEFAULT)
55
+ return MIN_UPTIME_DEFAULT
56
+ if val < 0:
57
+ logger.warning(
58
+ "TORTOISE_REAPER_MIN_UPTIME=%r negative — treating as 0", raw)
59
+ return 0
60
+ if val > 3600:
61
+ logger.warning(
62
+ "TORTOISE_REAPER_MIN_UPTIME=%r > 3600 — unusually large", raw)
63
+ return val
64
+
65
+
66
+ def _real_gettempdir() -> str:
67
+ return os.path.realpath(tempfile.gettempdir())
68
+
69
+
70
+ def _registry_for(socket_dir: str) -> dict | None:
71
+ """Read the redislite registry for a socket dir.
72
+
73
+ redislite writes the `.settings` JSON registry at the DB dir (user path
74
+ for path-based servers — NOT in the socket tempdir). The socket tempdir
75
+ always contains `redis.config` with `dbfilename` + `dir`, which is the
76
+ authoritative discriminator. Prefer redis.config (always present next
77
+ to the socket); fall back to a *.settings file if present.
78
+
79
+ Returns dict or None. Never raises — per-file error isolation.
80
+ """
81
+ config = _read_redis_config(socket_dir)
82
+ if config is not None:
83
+ return config
84
+ for p in Path(socket_dir).glob("*.settings"):
85
+ try:
86
+ return json.loads(p.read_text())
87
+ except (json.JSONDecodeError, OSError, PermissionError, UnicodeDecodeError):
88
+ logger.warning("corrupt settings file skipped: %s", p)
89
+ return None
90
+ return None
91
+
92
+
93
+ def _read_redis_config(socket_dir: str) -> dict | None:
94
+ """Parse redis.config (next to the socket) for dbfilename + dir.
95
+
96
+ redis.config lines: `dbfilename 'redis.db'` / `dir '/path'` /
97
+ `unixsocket '...'` / `pidfile '...'`.
98
+ """
99
+ cfg_path = os.path.join(socket_dir, "redis.config")
100
+ if not os.path.exists(cfg_path):
101
+ return None
102
+ try:
103
+ content = Path(cfg_path).read_text()
104
+ except (OSError, PermissionError, UnicodeDecodeError):
105
+ logger.warning("unreadable redis.config skipped: %s", cfg_path)
106
+ return None
107
+ result = {}
108
+ for line in content.splitlines():
109
+ line = line.strip()
110
+ if not line or line.startswith("#"):
111
+ continue
112
+ parts = line.split(None, 1)
113
+ if len(parts) != 2:
114
+ continue
115
+ key, val = parts[0], parts[1].strip().strip("'\"")
116
+ result[key] = val
117
+ if not result:
118
+ return None
119
+ return result
120
+
121
+
122
+ def _uptime_seconds(pid: int) -> float | None:
123
+ """Return process uptime in seconds, or None if the PID is not alive.
124
+
125
+ macOS: ps -o etime gives [[dd-]hh:]mm:ss; Linux /proc/<pid>/stat is
126
+ preferred but ps -o etime works on both.
127
+ """
128
+ try:
129
+ out = subprocess.run(
130
+ ["ps", "-o", "etime=", "-p", str(pid)],
131
+ capture_output=True, text=True, timeout=2,
132
+ )
133
+ except (subprocess.TimeoutExpired, OSError):
134
+ return None
135
+ etime = out.stdout.strip()
136
+ if not etime:
137
+ return None
138
+ return _parse_etime(etime)
139
+
140
+
141
+ def _parse_etime(etime: str) -> float:
142
+ """Parse ps etime '[[dd-]hh:]mm:ss' into seconds."""
143
+ etime = etime.strip()
144
+ days = 0
145
+ if "-" in etime:
146
+ days_part, etime = etime.split("-", 1)
147
+ days = int(days_part)
148
+ parts = [int(x) for x in etime.split(":")]
149
+ if len(parts) == 3: # hh:mm:ss
150
+ hours, minutes, seconds = parts
151
+ elif len(parts) == 2: # mm:ss
152
+ hours, minutes, seconds = 0, parts[0], parts[1]
153
+ else:
154
+ return 0.0
155
+ return days * 86400 + hours * 3600 + minutes * 60 + seconds
156
+
157
+
158
+ def _pid_alive(pid: int) -> bool:
159
+ try:
160
+ os.kill(pid, 0)
161
+ return True
162
+ except (ProcessLookupError, PermissionError):
163
+ return False
164
+ except OSError:
165
+ return False
166
+
167
+
168
+ def _derive_real_pid(socket_path: str, pidfile_pid: int | None = None) -> int | None:
169
+ """Derive the real redis-server PID for a live socket.
170
+
171
+ Strategy:
172
+ 1. If pidfile_pid is alive AND lsof confirms it owns the socket ->
173
+ pidfile_pid is authoritative (normal case).
174
+ 2. Otherwise scan redis-server processes via lsof and check which one
175
+ has the socket path in its cmdline (respawned case).
176
+ Returns None if undeterminable (caller treats as undetermined).
177
+ """
178
+ if pidfile_pid and _pid_alive(pidfile_pid) and _process_has_socket(pidfile_pid, socket_path):
179
+ return pidfile_pid
180
+ # Scan redis-server processes for the socket owner
181
+ if sys_platform() == "linux":
182
+ return _derive_real_pid_linux(socket_path)
183
+ return _derive_real_pid_macos(socket_path)
184
+
185
+
186
+ def _process_has_socket(pid: int, socket_path: str) -> bool:
187
+ """True if the process has the given unix socket open (lsof)."""
188
+ try:
189
+ out = subprocess.run(
190
+ ["lsof", "-Fp", "-a", "-p", str(pid), "-U"],
191
+ capture_output=True, text=True, timeout=2,
192
+ )
193
+ except (subprocess.TimeoutExpired, OSError):
194
+ return False
195
+ # -Fp prints 'p<pid>' entries; presence means it has unix sockets open.
196
+ # Additionally verify cmdline contains the socket path for certainty.
197
+ return f"p{pid}" in out.stdout
198
+
199
+
200
+ def sys_platform() -> str:
201
+ import sys
202
+ return sys.platform
203
+
204
+
205
+ def _derive_real_pid_linux(socket_path: str) -> int | None:
206
+ try:
207
+ ino = os.stat(socket_path).st_ino
208
+ except OSError:
209
+ return None
210
+ for fd in Path("/proc").glob("*/fd/*"):
211
+ try:
212
+ if os.stat(fd).st_ino == ino:
213
+ pid = int(fd.parts[2])
214
+ if _pid_alive(pid):
215
+ return pid
216
+ except (OSError, ValueError):
217
+ continue
218
+ return None
219
+
220
+
221
+ def _derive_real_pid_macos(socket_path: str) -> int | None:
222
+ """Find the redis-server PID owning a socket via lsof + cmdline check.
223
+
224
+ lsof -c redis-server lists all redis-servers; we pick the one whose
225
+ cmdline contains our target socket path.
226
+ """
227
+ try:
228
+ out = subprocess.run(
229
+ ["lsof", "-Fp", "-c", "redis-server"],
230
+ capture_output=True, text=True, timeout=2,
231
+ )
232
+ except (subprocess.TimeoutExpired, OSError):
233
+ return None
234
+ for line in out.stdout.splitlines():
235
+ if not line.startswith("p"):
236
+ continue
237
+ try:
238
+ pid = int(line[1:])
239
+ except ValueError:
240
+ continue
241
+ if not _pid_alive(pid):
242
+ continue
243
+ if socket_path in _cmdline(pid):
244
+ return pid
245
+ return None
246
+
247
+
248
+ def _cmdline(pid: int) -> str:
249
+ try:
250
+ out = subprocess.run(
251
+ ["ps", "-o", "command=", "-p", str(pid)],
252
+ capture_output=True, text=True, timeout=2,
253
+ )
254
+ return out.stdout
255
+ except (subprocess.TimeoutExpired, OSError):
256
+ return ""
257
+
258
+
259
+ def _probe_socket(socket_path: str) -> str:
260
+ """Raw unix-socket connect probe (never redis-py — can't spawn).
261
+
262
+ Returns 'dead' (ECONNREFUSED / no listener), 'alive' (accepts), or
263
+ 'undetermined' (timeout / error).
264
+ """
265
+ try:
266
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
267
+ s.settimeout(PROBE_TIMEOUT)
268
+ try:
269
+ s.connect(socket_path)
270
+ return "alive"
271
+ except (ConnectionRefusedError, FileNotFoundError):
272
+ return "dead"
273
+ except socket.timeout:
274
+ return "undetermined"
275
+ except OSError:
276
+ return "undetermined"
277
+ finally:
278
+ s.close()
279
+ except OSError:
280
+ return "undetermined"
281
+
282
+
283
+ def _client_list(socket_path: str) -> list[dict]:
284
+ """CLIENT LIST over the unix socket using a raw RESP connection.
285
+
286
+ Uses redislite's own client (which is a redis client) via subprocess-free
287
+ approach: we shell to redis-cli if available, else parse via raw RESP.
288
+ Returns list of client dicts; empty on failure.
289
+ """
290
+ # Prefer redis-cli (no python redis dependency, no spawn risk).
291
+ try:
292
+ out = subprocess.run(
293
+ ["redis-cli", "-s", socket_path, "CLIENT", "LIST"],
294
+ capture_output=True, text=True, timeout=PROBE_TIMEOUT,
295
+ )
296
+ if out.returncode == 0 and out.stdout.strip():
297
+ return _parse_client_list(out.stdout)
298
+ except (subprocess.TimeoutExpired, OSError):
299
+ pass
300
+ # Fallback: raw RESP via the redislite client API (execute_command).
301
+ try:
302
+ from redislite.falkordb_client import FalkorDB
303
+ db = FalkorDB(unix_socket_path=socket_path)
304
+ try:
305
+ raw = db.execute_command("CLIENT", "LIST")
306
+ return _parse_client_list(raw if isinstance(raw, str) else "")
307
+ finally:
308
+ try:
309
+ db.close()
310
+ except Exception:
311
+ pass
312
+ except Exception:
313
+ return []
314
+ return []
315
+
316
+
317
+ def _parse_client_list(raw: str) -> list[dict]:
318
+ clients = []
319
+ for line in raw.splitlines():
320
+ if not line.strip():
321
+ continue
322
+ entry = {}
323
+ for kv in line.split():
324
+ if "=" in kv:
325
+ k, v = kv.split("=", 1)
326
+ entry[k] = v
327
+ clients.append(entry)
328
+ return clients
329
+
330
+
331
+ def _active_client_count(socket_path: str) -> int:
332
+ """Count non-reaper clients (SKIPME semantics).
333
+
334
+ Our probing connection (redis-cli) is the freshly-created one with
335
+ age ~0 and idle ~0. Any connection with age >= 2s is a pre-existing
336
+ real client. Named clients are also real users regardless of age.
337
+ """
338
+ clients = _client_list(socket_path)
339
+ count = 0
340
+ for c in clients:
341
+ if c.get("name"):
342
+ count += 1
343
+ continue
344
+ try:
345
+ age = int(c.get("age", 0))
346
+ except ValueError:
347
+ age = 0
348
+ if age >= 2:
349
+ count += 1
350
+ return count
351
+
352
+
353
+ def discover() -> list[dict]:
354
+ """Scan tempdir for redislite orphans; return classified records.
355
+
356
+ Each record: {pid, socket_path, dbdir, client_count, uptime,
357
+ classification, settings}.
358
+ """
359
+ results = []
360
+ tmpdir = _real_gettempdir()
361
+
362
+ try:
363
+ entries = list(os.scandir(tmpdir))
364
+ except (PermissionError, OSError) as e:
365
+ logger.warning("permission denied scanning tempdir %s: %s", tmpdir, e)
366
+ return results
367
+
368
+ for entry in entries:
369
+ if not entry.is_dir():
370
+ continue
371
+ try:
372
+ socket_path = os.path.join(entry.path, "redis.socket")
373
+ if not os.path.exists(socket_path):
374
+ continue
375
+ record = _classify_dir(entry.path, socket_path)
376
+ if record is not None:
377
+ results.append(record)
378
+ except PermissionError:
379
+ logger.warning("permission denied dir skipped: %s", entry.path)
380
+ continue
381
+ except OSError:
382
+ logger.warning("dir skipped (OSError): %s", entry.path)
383
+ continue
384
+ return results
385
+
386
+
387
+ def _classify_dir(dbdir: str, socket_path: str) -> dict | None:
388
+ """Classify a single candidate dir. Returns record or None (skip)."""
389
+ registry = _registry_for(dbdir)
390
+ dbdir_real = os.path.realpath(dbdir)
391
+ socket_real = os.path.realpath(socket_path)
392
+ tmpdir_real = _real_gettempdir()
393
+
394
+ classification = _classify(socket_real, dbdir_real, tmpdir_real, registry)
395
+ pid = None
396
+ if registry and registry.get("pidfile"):
397
+ try:
398
+ pid = int(Path(registry["pidfile"]).read_text().strip())
399
+ except (OSError, ValueError):
400
+ pid = None
401
+
402
+ uptime = _uptime_seconds(pid) if pid else None
403
+ client_count = 0
404
+ if classification == "candidate" and pid and _pid_alive(pid):
405
+ client_count = _active_client_count(socket_real)
406
+
407
+ return {
408
+ "pid": pid,
409
+ "socket_path": socket_real,
410
+ "dbdir": dbdir_real,
411
+ "client_count": client_count,
412
+ "uptime": uptime,
413
+ "classification": classification,
414
+ "settings": registry,
415
+ }
416
+
417
+
418
+ def _classify(socket_real: str, dbdir_real: str, tmpdir_real: str,
419
+ registry: dict | None) -> str:
420
+ """Dual-signal classification (plan Task 1).
421
+
422
+ Signal 1 — registry dbdir: path-based servers register a USER directory
423
+ (e.g. /tmp, /Users/...); no-path servers register an auto-generated
424
+ tempdir (tmpXXXX under TMPDIR).
425
+ Signal 2 — registry dbfilename: path-based -> user filename
426
+ (e.g. pathbased_reaper_test.db); no-path -> the generic 'redis.db'.
427
+ Both signals must agree for 'candidate'.
428
+
429
+ Note: redislite ALWAYS places the unix socket in a tempdir (even for
430
+ path-based servers), so socket location alone is insufficient — the
431
+ registry is the authoritative source.
432
+ """
433
+ # No registry at all -> cannot confirm path-based; treat conservatively
434
+ # via dirname pattern + .db-file presence (old-format fallback).
435
+ if registry is None:
436
+ if _dir_has_db_file(dbdir_real):
437
+ return "protected"
438
+ basename = os.path.basename(dbdir_real)
439
+ if not _AUTOGEN_DIRNAME.match(basename):
440
+ logger.warning(
441
+ "unrecognized dir pattern, treating as protected: %s", dbdir_real)
442
+ return "protected"
443
+ # auto-generated dirname, no .db file -> could be a no-path server
444
+ return _cooldown_check(registry)
445
+
446
+ # Signal 1: registry 'dir' is a USER dir (not auto tempdir) -> path-based.
447
+ reg_dbdir = registry.get("dir", registry.get("dbdir", ""))
448
+ reg_dbdir_real = os.path.realpath(reg_dbdir) if reg_dbdir else ""
449
+ is_autogen_dbdir = bool(
450
+ reg_dbdir_real
451
+ and reg_dbdir_real.startswith(tmpdir_real)
452
+ and _AUTOGEN_DIRNAME.match(os.path.basename(reg_dbdir_real))
453
+ )
454
+ if not is_autogen_dbdir and reg_dbdir_real:
455
+ if reg_dbdir_real.startswith(tmpdir_real):
456
+ logger.warning(
457
+ "unrecognized dir pattern, treating as protected: %s", reg_dbdir_real)
458
+ return "protected"
459
+
460
+ # Signal 2: dbfilename is the generic 'redis.db' (no-path) vs user name.
461
+ db_filename = registry.get("dbfilename", "")
462
+ if db_filename and db_filename != "redis.db":
463
+ return "protected"
464
+
465
+ # Old-format registry (no dbfilename field): .db file present -> protected.
466
+ if "dbfilename" in registry and registry.get("dbfilename") is None:
467
+ if _dir_has_db_file(dbdir_real):
468
+ return "protected"
469
+ basename = os.path.basename(dbdir_real)
470
+ if not _AUTOGEN_DIRNAME.match(basename):
471
+ logger.warning(
472
+ "unrecognized dir pattern, treating as protected: %s", dbdir_real)
473
+ return "protected"
474
+
475
+ return _cooldown_check(registry)
476
+
477
+
478
+ def _cooldown_check(registry: dict | None) -> str:
479
+ """Boot-cooldown: fresh servers (uptime < MIN_UPTIME) are protected."""
480
+ pid = None
481
+ if registry and registry.get("pidfile"):
482
+ try:
483
+ pid = int(Path(registry["pidfile"]).read_text().strip())
484
+ except (OSError, ValueError):
485
+ pid = None
486
+ uptime = _uptime_seconds(pid) if pid else 0.0
487
+ min_uptime = _parse_min_uptime()
488
+ if uptime is not None and uptime < min_uptime:
489
+ return "protected"
490
+ return "candidate"
491
+
492
+
493
+ def _dir_has_db_file(dbdir: str) -> bool:
494
+ try:
495
+ for p in Path(dbdir).glob("*.db"):
496
+ return True
497
+ except OSError:
498
+ pass
499
+ return False
500
+
501
+
502
+ # ── Phase 1 / Phase 2 discovery helpers (plan Task 2) ───────────────
503
+
504
+ def phase1_probe(record: dict) -> dict:
505
+ """Ordered discovery: resolve stale-PID sockets via raw probe FIRST.
506
+
507
+ Returns record with updated classification:
508
+ - stale_PID + probe dead -> 'stale_socket' (removable)
509
+ - stale_PID + probe alive -> live, real PID derived
510
+ - stale_PID + probe undetermined -> 'undetermined'
511
+ - pid alive -> unchanged
512
+ """
513
+ if record.get("pid") and _pid_alive(record["pid"]):
514
+ return record
515
+ if not record.get("socket_path"):
516
+ return record
517
+ probe = _probe_socket(record["socket_path"])
518
+ if probe == "dead":
519
+ record["classification"] = "stale_socket"
520
+ elif probe == "alive":
521
+ real_pid = _derive_real_pid(record["socket_path"], record.get("pid"))
522
+ if real_pid:
523
+ record["pid"] = real_pid
524
+ record["classification"] = record.get("classification")
525
+ else:
526
+ record["classification"] = "undetermined"
527
+ else: # undetermined
528
+ record["classification"] = "undetermined"
529
+ return record
530
+
531
+
532
+ def reap(records: list[dict], dry_run: bool = True, batch_size: int | None = None,
533
+ sigterm_timeout: float = 10.0) -> list[dict]:
534
+ """Reap candidate records safely (plan Task 2). Returns acted-upon list.
535
+
536
+ Only 'candidate' records are killed, and only after CLIENT LIST shows 0
537
+ active clients (double-checked). Path-based / protected / stale_socket /
538
+ undetermined records are NEVER killed here.
539
+ """
540
+ acted = []
541
+ killed = 0
542
+ for record in records:
543
+ if batch_size is not None and killed >= batch_size:
544
+ break
545
+ classification = record.get("classification")
546
+ if classification != "candidate":
547
+ if classification in ("protected", "stale_socket", "undetermined"):
548
+ logger.warning(
549
+ "skipping path-based/non-candidate server: %s",
550
+ record.get("socket_path"))
551
+ continue
552
+
553
+ # Liveness-first: never kill a dead PID's leftovers via connect.
554
+ if not record.get("pid") or not _pid_alive(record["pid"]):
555
+ logger.warning("dead socket connect failure, skipping: %s",
556
+ record.get("socket_path"))
557
+ continue
558
+
559
+ # Double-check CLIENT LIST (before+after).
560
+ clients_before = _active_client_count(record["socket_path"])
561
+ if clients_before > 0:
562
+ logger.info("server has %d active client(s), skipping: %s",
563
+ clients_before, record["socket_path"])
564
+ continue
565
+ clients_after = _active_client_count(record["socket_path"])
566
+ if clients_after > 0:
567
+ logger.info("server gained a client between checks, skipping: %s",
568
+ record["socket_path"])
569
+ continue
570
+
571
+ if dry_run:
572
+ logger.warning("[DRY-RUN] would kill PID %s (%s)",
573
+ record["pid"], record["socket_path"])
574
+ acted.append(record)
575
+ continue
576
+
577
+ _kill(record["pid"], sigterm_timeout)
578
+ _cleanup_tempdir(record.get("dbdir"))
579
+ logger.warning("killed orphan PID %s (%s)",
580
+ record["pid"], record["socket_path"])
581
+ acted.append(record)
582
+ killed += 1
583
+ return acted
584
+
585
+
586
+ def _kill(pid: int, sigterm_timeout: float) -> None:
587
+ import signal
588
+ try:
589
+ os.kill(pid, signal.SIGTERM)
590
+ except ProcessLookupError:
591
+ return
592
+ deadline = time.time() + sigterm_timeout
593
+ while time.time() < deadline:
594
+ if not _pid_alive(pid):
595
+ return
596
+ time.sleep(0.2)
597
+ try:
598
+ os.kill(pid, signal.SIGKILL)
599
+ except ProcessLookupError:
600
+ pass
601
+
602
+
603
+ def _cleanup_tempdir(dbdir: str | None) -> None:
604
+ if not dbdir:
605
+ return
606
+ try:
607
+ shutil.rmtree(dbdir, ignore_errors=True)
608
+ except OSError:
609
+ logger.warning("could not remove tempdir %s", dbdir)
610
+
611
+
612
+ # ── CLI + singleton lock + timeout (plan Task 3) ────────────────────
613
+
614
+ _LOCK_PATH = os.path.join(
615
+ os.path.expanduser("~"), ".tortoise", ".reaper.lock")
616
+ TIMEOUT_DEFAULT = 120
617
+
618
+
619
+ class _ReaperLock:
620
+ """fcntl-based exclusive lock; auto-released on process exit (incl. SIGKILL)."""
621
+
622
+ def __init__(self, path: str = _LOCK_PATH):
623
+ self.path = path
624
+ self._fh = None
625
+
626
+ def acquire(self) -> bool:
627
+ import fcntl
628
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
629
+ self._fh = open(self.path, "a")
630
+ try:
631
+ fcntl.flock(self._fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
632
+ self._fh.seek(0)
633
+ self._fh.truncate()
634
+ self._fh.write(str(os.getpid()))
635
+ self._fh.flush()
636
+ return True
637
+ except OSError:
638
+ self._fh.close()
639
+ self._fh = None
640
+ return False
641
+
642
+ def release(self) -> None:
643
+ import fcntl
644
+ if self._fh:
645
+ try:
646
+ fcntl.flock(self._fh, fcntl.LOCK_UN)
647
+ except OSError:
648
+ pass
649
+ self._fh.close()
650
+ self._fh = None
651
+
652
+
653
+ def _parse_timeout(cli_value: str | None) -> int:
654
+ """Timeout resolution: CLI --timeout > TORTOISE_REAPER_TIMEOUT env > 120."""
655
+ if cli_value is not None:
656
+ try:
657
+ return int(float(cli_value))
658
+ except ValueError:
659
+ logger.warning("invalid --timeout %r — using default", cli_value)
660
+ env = os.environ.get("TORTOISE_REAPER_TIMEOUT", "")
661
+ if env:
662
+ try:
663
+ return int(float(env))
664
+ except ValueError:
665
+ logger.warning(
666
+ "TORTOISE_REAPER_TIMEOUT=%r invalid — using default", env)
667
+ return TIMEOUT_DEFAULT
668
+
669
+
670
+ def _run_sweep(dry_run: bool, batch_size: int | None) -> list[dict]:
671
+ """Discover + classify + reap; return acted-upon records."""
672
+ records = discover()
673
+ candidates = [r for r in records if r["classification"] == "candidate"]
674
+ # Phase 1: resolve stale-PID records via probe before any kill
675
+ resolved = [phase1_probe(r) for r in candidates]
676
+ return reap(resolved, dry_run=dry_run, batch_size=batch_size)
677
+
678
+
679
+ def main(argv: list[str] | None = None) -> int:
680
+ import argparse
681
+ import json as _json
682
+ import signal
683
+ import sys
684
+
685
+ logging.basicConfig(level=logging.INFO,
686
+ format="%(levelname)s %(message)s")
687
+
688
+ parser = argparse.ArgumentParser(
689
+ prog="tortoise.embedded_reaper",
690
+ description="Reap orphaned redislite redis-server processes "
691
+ "(issue #176).",
692
+ )
693
+ parser.add_argument("--no-dry-run", action="store_true",
694
+ help="Actually kill orphans (default is dry-run)")
695
+ parser.add_argument("--batch-size", type=int, default=None,
696
+ help="Limit kills per run")
697
+ parser.add_argument("--json", action="store_true",
698
+ help="Machine-readable JSON output")
699
+ parser.add_argument("--timeout", type=str, default=None,
700
+ help=f"Sweep timeout in seconds (default "
701
+ f"{TIMEOUT_DEFAULT}; env TORTOISE_REAPER_TIMEOUT)")
702
+ args = parser.parse_args(argv)
703
+
704
+ timeout = _parse_timeout(args.timeout)
705
+
706
+ # Singleton lock: second concurrent instance exits 0 with message.
707
+ lock = _ReaperLock()
708
+ if not lock.acquire():
709
+ logger.warning("reaper already running (PID %s)",
710
+ _lock_holder_pid())
711
+ return 0
712
+
713
+ def _alarm_handler(signum, frame):
714
+ logger.error("reaper timeout (%ss) exceeded — aborting sweep", timeout)
715
+ sys.exit(1)
716
+
717
+ try:
718
+ signal.signal(signal.SIGALRM, _alarm_handler)
719
+ signal.alarm(timeout)
720
+ acted = _run_sweep(dry_run=not args.no_dry_run,
721
+ batch_size=args.batch_size)
722
+ signal.alarm(0)
723
+ finally:
724
+ lock.release()
725
+
726
+ if args.json:
727
+ print(_json.dumps([
728
+ {"pid": r.get("pid"), "socket_path": r.get("socket_path"),
729
+ "classification": r.get("classification")}
730
+ for r in acted
731
+ ]))
732
+ return 0
733
+
734
+
735
+ def _lock_holder_pid() -> str:
736
+ try:
737
+ with open(_LOCK_PATH) as fh:
738
+ return fh.read().strip() or "unknown"
739
+ except OSError:
740
+ return "unknown"
741
+
742
+
743
+ if __name__ == "__main__":
744
+ raise SystemExit(main())