tokensafe 1.4.11 → 1.4.14

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.
@@ -5,7 +5,9 @@ and triggers confirmation to prevent infinite token drain loops.
5
5
 
6
6
  import os
7
7
  import json
8
+ import time
8
9
  import hashlib
10
+ from contextlib import contextmanager
9
11
  from typing import Dict, Any, Tuple
10
12
 
11
13
  class LoopDetector:
@@ -13,6 +15,7 @@ class LoopDetector:
13
15
 
14
16
  STATE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "loop_state.json")
15
17
  MAX_IDENTICAL_REPEATS = 3
18
+ SESSION_TTL_SECONDS = 48 * 3600 # prune sessions idle for more than 2 days
16
19
 
17
20
  @classmethod
18
21
  def _get_call_signature(cls, tool_name: str, args: Dict[str, Any]) -> str:
@@ -20,6 +23,54 @@ class LoopDetector:
20
23
  args_str = json.dumps(args, sort_keys=True, default=str)
21
24
  return hashlib.sha256(f"{tool_name}:{args_str}".encode("utf-8")).hexdigest()[:16]
22
25
 
26
+ @classmethod
27
+ @contextmanager
28
+ def _locked_state(cls):
29
+ """
30
+ Exclusive read-modify-write guard for the shared state file.
31
+ Hooks for parallel tool calls run as concurrent processes; without the lock
32
+ their increments overwrote each other and identical calls went undetected.
33
+ Uses fcntl on POSIX and degrades to lock-free (best effort) elsewhere.
34
+ """
35
+ os.makedirs(os.path.dirname(cls.STATE_FILE), exist_ok=True)
36
+ lock_path = cls.STATE_FILE + ".lock"
37
+ handle = open(lock_path, "w")
38
+ locked = False
39
+ try:
40
+ try:
41
+ import fcntl
42
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
43
+ locked = True
44
+ except ImportError:
45
+ pass
46
+ yield
47
+ finally:
48
+ try:
49
+ if locked:
50
+ import fcntl
51
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
52
+ except Exception:
53
+ pass
54
+ handle.close()
55
+
56
+ @classmethod
57
+ def _load_state(cls) -> Dict[str, Any]:
58
+ if os.path.exists(cls.STATE_FILE):
59
+ try:
60
+ with open(cls.STATE_FILE, "r", encoding="utf-8") as f:
61
+ return json.load(f)
62
+ except Exception:
63
+ return {}
64
+ return {}
65
+
66
+ @classmethod
67
+ def _save_state(cls, state: Dict[str, Any]):
68
+ try:
69
+ with open(cls.STATE_FILE, "w", encoding="utf-8") as f:
70
+ json.dump(state, f)
71
+ except Exception:
72
+ pass
73
+
23
74
  @classmethod
24
75
  def check_loop(cls, conversation_id: str, tool_name: str, args: Dict[str, Any]) -> Tuple[bool, int, str]:
25
76
  """
@@ -30,37 +81,33 @@ class LoopDetector:
30
81
  return False, 0, ""
31
82
 
32
83
  signature = cls._get_call_signature(tool_name, args)
33
- state = {}
34
84
 
35
- if os.path.exists(cls.STATE_FILE):
36
- try:
37
- with open(cls.STATE_FILE, "r", encoding="utf-8") as f:
38
- state = json.load(f)
39
- except Exception:
40
- state = {}
85
+ with cls._locked_state():
86
+ state = cls._load_state()
41
87
 
42
- session_state = state.get(conversation_id, {
43
- "last_sig": "",
44
- "repeat_count": 0,
45
- "tool_name": ""
46
- })
88
+ # Prune stale sessions so the state file cannot grow unboundedly
89
+ now = time.time()
90
+ stale = [cid for cid, s in state.items()
91
+ if not isinstance(s, dict) or (now - float(s.get("updated", 0))) > cls.SESSION_TTL_SECONDS]
92
+ for cid in stale:
93
+ state.pop(cid, None)
47
94
 
48
- if session_state.get("last_sig") == signature:
49
- session_state["repeat_count"] = session_state.get("repeat_count", 0) + 1
50
- else:
51
- session_state["last_sig"] = signature
52
- session_state["repeat_count"] = 1
53
- session_state["tool_name"] = tool_name
95
+ session_state = state.get(conversation_id, {
96
+ "last_sig": "",
97
+ "repeat_count": 0,
98
+ "tool_name": ""
99
+ })
54
100
 
55
- state[conversation_id] = session_state
101
+ if session_state.get("last_sig") == signature:
102
+ session_state["repeat_count"] = session_state.get("repeat_count", 0) + 1
103
+ else:
104
+ session_state["last_sig"] = signature
105
+ session_state["repeat_count"] = 1
106
+ session_state["tool_name"] = tool_name
107
+ session_state["updated"] = now
56
108
 
57
- # Save state
58
- try:
59
- os.makedirs(os.path.dirname(cls.STATE_FILE), exist_ok=True)
60
- with open(cls.STATE_FILE, "w", encoding="utf-8") as f:
61
- json.dump(state, f)
62
- except Exception:
63
- pass
109
+ state[conversation_id] = session_state
110
+ cls._save_state(state)
64
111
 
65
112
  repeats = session_state["repeat_count"]
66
113
  if repeats >= cls.MAX_IDENTICAL_REPEATS:
package/src/mcp_server.py CHANGED
@@ -6,11 +6,13 @@ Exposes tools for smart file reading, dependency prefetching, prompt compression
6
6
 
7
7
  import sys
8
8
  import os
9
+ import stat
9
10
  import time
10
11
  import json
12
+ import threading
11
13
  import traceback
12
14
  import fnmatch
13
- from typing import Tuple, Optional
15
+ from typing import List, Tuple, Optional
14
16
 
15
17
  # Ensure project root in sys.path
16
18
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -33,7 +35,7 @@ from src.scoped_search import ScopedSearch
33
35
 
34
36
  SERVER_INFO = {
35
37
  "name": "tokensafe-mcp",
36
- "version": "1.4.11"
38
+ "version": "1.4.14"
37
39
  }
38
40
 
39
41
  TOOLS = [
@@ -322,17 +324,111 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
322
324
 
323
325
  return None, "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory (e.g. project_path='/path/to/project')."
324
326
 
327
+ MCP_TOOL_TIMEOUT = float(os.environ.get("TOKENSAFE_MCP_TIMEOUT", "8.0"))
328
+
329
+
330
+ def _fallback_error(tool_name: str, reason: str) -> dict:
331
+ """Returns a non-blocking, actionable error telling the AI model to try another approach."""
332
+ clean_reason = (reason or "unknown error").strip()
333
+ return {
334
+ "isError": True,
335
+ "content": [{
336
+ "type": "text",
337
+ "text": (
338
+ f"⚠️ TokenSafe MCP tool '{tool_name}' could not complete ({clean_reason}). "
339
+ "Try an alternative approach instead of repeating this exact call: "
340
+ "narrow the target 'path'/'project_path' or 'depth', inspect a specific file with 'smart_read_file', "
341
+ "or fall back to standard 'read_file' / bounded 'run_command'."
342
+ )
343
+ }]
344
+ }
345
+
346
+
347
+ class _NoOpTracker:
348
+ """Fallback metrics tracker if SQLite DB is temporarily unavailable or locked."""
349
+ db_path = ""
350
+ def record_event(self, *args, **kwargs):
351
+ return 0
352
+ def get_summary(self, *args, **kwargs):
353
+ return {}
354
+ def get_last_event(self, *args, **kwargs):
355
+ return None
356
+
357
+
358
+ class _SafeTrackerProxy:
359
+ """Wraps MetricsTracker so transient SQLite errors never interrupt MCP tool output."""
360
+ def __init__(self, inner):
361
+ self._inner = inner
362
+ self.db_path = getattr(inner, "db_path", "")
363
+
364
+ def record_event(self, *args, **kwargs):
365
+ try:
366
+ return self._inner.record_event(*args, **kwargs)
367
+ except Exception:
368
+ return 0
369
+
370
+ def __getattr__(self, name):
371
+ return getattr(self._inner, name)
372
+
373
+
374
+ def _get_safe_tracker():
375
+ try:
376
+ return _SafeTrackerProxy(MetricsTracker())
377
+ except Exception:
378
+ return _NoOpTracker()
379
+
380
+
325
381
  def handle_tool_call(name: str, args: dict) -> dict:
326
- tracker = MetricsTracker()
382
+ if args is None or not isinstance(args, dict):
383
+ args = {}
384
+ try:
385
+ result = _dispatch_tool_call(name, args)
386
+ # Populate the Subagent Firewall dedup cache with what we actually returned,
387
+ # so repeated reads of the same file within a session can be served from cache.
388
+ if name == "smart_read_file" and isinstance(result, dict) and not result.get("isError"):
389
+ content_parts = result.get("content") or []
390
+ text_out = "".join(p.get("text", "") for p in content_parts if isinstance(p, dict))
391
+ if text_out:
392
+ try:
393
+ AgentFirewall.record_cache(
394
+ session_id="mcp_session",
395
+ file_path=args.get("path", ""),
396
+ content=text_out,
397
+ symbol=(args.get("symbol") or "").strip(),
398
+ tracker=_get_safe_tracker()
399
+ )
400
+ except Exception:
401
+ pass
402
+ return result
403
+ except Exception as e:
404
+ return _fallback_error(name, f"{type(e).__name__}: {str(e)}")
405
+
406
+
407
+ def _dispatch_tool_call(name: str, args: dict) -> dict:
408
+ tracker = _get_safe_tracker()
327
409
 
328
410
  if name == "smart_read_file":
329
411
  path = args.get("path", "")
330
412
  symbol = args.get("symbol", "")
331
413
  start_line = args.get("start_line")
332
414
  end_line = args.get("end_line")
415
+ # Clamp explicit line ranges to sane bounds so bad indices can never produce
416
+ # empty output or negative-index slicing artifacts.
417
+ try:
418
+ if start_line is not None:
419
+ start_line = max(1, int(start_line))
420
+ if end_line is not None:
421
+ end_line = int(end_line)
422
+ except (TypeError, ValueError):
423
+ return _fallback_error("smart_read_file", "start_line/end_line must be integers")
333
424
 
334
425
  if not path or not os.path.exists(path):
335
426
  return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
427
+ try:
428
+ if not stat.S_ISREG(os.stat(path).st_mode):
429
+ return _fallback_error("smart_read_file", f"path is not a regular file: {path}")
430
+ except OSError as e:
431
+ return _fallback_error("smart_read_file", f"cannot stat path: {e}")
336
432
 
337
433
  # Check Subagent Firewall dedup cache
338
434
  is_hit, cached_text, saved_dedup = AgentFirewall.check_cache("mcp_session", path, symbol=symbol or "", tracker=tracker)
@@ -351,6 +447,9 @@ def handle_tool_call(name: str, args: dict) -> dict:
351
447
  if start_line is not None and end_line is not None:
352
448
  with open(path, "r", encoding="utf-8", errors="replace") as f:
353
449
  lines = f.readlines()
450
+ end_line = min(end_line, len(lines))
451
+ if start_line > end_line:
452
+ return _fallback_error("smart_read_file", f"start_line {start_line} is beyond end of file ({len(lines)} lines)")
354
453
  content = "".join(lines[start_line - 1 : end_line])
355
454
  return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
356
455
 
@@ -572,9 +671,9 @@ def handle_tool_call(name: str, args: dict) -> dict:
572
671
  return {"content": [{"type": "text", "text": surface_md}]}
573
672
 
574
673
  elif name == "list_dir":
575
- path = args.get("path", "")
674
+ path = args.get("path") or args.get("project_path") or args.get("directory") or args.get("root_dir") or ""
576
675
  if not path:
577
- return {"isError": True, "content": [{"type": "text", "text": "Error: 'path' argument is required for list_dir."}]}
676
+ return _fallback_error("list_dir", "missing required 'path' argument")
578
677
 
579
678
  # Resolve path relative to current working directory or absolute
580
679
  abs_path = os.path.abspath(path)
@@ -601,7 +700,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
601
700
  elif name == "scoped_search":
602
701
  query = args.get("query", "")
603
702
  if not query:
604
- return {"isError": True, "content": [{"type": "text", "text": "Error: 'query' argument is required for scoped_search."}]}
703
+ return _fallback_error("scoped_search", "missing required 'query' argument")
605
704
 
606
705
  scope = args.get("scope", "all")
607
706
  raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
@@ -612,10 +711,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
612
711
  else:
613
712
  resolved_path, err = _resolve_project_root(args)
614
713
  if err or not resolved_path:
615
- return {
616
- "isError": True,
617
- "content": [{"type": "text", "text": err or "Error: Invalid or unspecified project_path."}]
618
- }
714
+ return _fallback_error("scoped_search", err or "unspecified project_path")
619
715
  target_path = resolved_path
620
716
 
621
717
  max_res = args.get("max_results", 25)
@@ -632,7 +728,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
632
728
  )
633
729
  md_text = res["markdown"]
634
730
  if not res.get("success", True):
635
- return {"isError": True, "content": [{"type": "text", "text": md_text}]}
731
+ return _fallback_error("scoped_search", md_text)
636
732
 
637
733
  res_tokens = count_tokens(md_text)
638
734
  est_orig = max(1500, res_tokens * 8)
@@ -645,12 +741,58 @@ def handle_tool_call(name: str, args: dict) -> dict:
645
741
  )
646
742
  return {"content": [{"type": "text", "text": md_text}]}
647
743
 
648
- return {"isError": True, "content": [{"type": "text", "text": f"Unknown tool: {name}"}]}
744
+ return _fallback_error(name, f"unknown tool '{name}'")
745
+
746
+
747
+ def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
748
+ """Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
749
+ box = {"result": None, "error": None}
750
+
751
+ def _runner():
752
+ try:
753
+ box["result"] = handle_tool_call(tool_name, tool_args)
754
+ except Exception as exc:
755
+ box["error"] = f"{type(exc).__name__}: {str(exc)}"
756
+
757
+ worker = threading.Thread(target=_runner, daemon=True)
758
+ worker.start()
759
+ worker.join(timeout=timeout)
760
+
761
+ if worker.is_alive():
762
+ return _fallback_error(tool_name, f"execution exceeded {timeout:.1f}s timeout")
763
+ if box["error"] is not None:
764
+ return _fallback_error(tool_name, box["error"])
765
+ if box["result"] is None:
766
+ return _fallback_error(tool_name, "empty result returned")
767
+ return box["result"]
768
+
769
+
770
+ def _get_watched_mtimes() -> Tuple[Optional[float], ...]:
771
+ """Returns mtimes for core server/package files and the update reload marker."""
772
+ watched_paths = (
773
+ os.path.abspath(__file__),
774
+ os.path.join(BASE_DIR, "package.json"),
775
+ os.path.join(BASE_DIR, "data", ".mcp_reload"),
776
+ )
777
+ mtimes: List[Optional[float]] = []
778
+ for p in watched_paths:
779
+ try:
780
+ mtimes.append(os.path.getmtime(p))
781
+ except OSError:
782
+ mtimes.append(None)
783
+ return tuple(mtimes)
784
+
649
785
 
650
786
  def run_mcp_server():
651
- """Runs stdio JSON-RPC 2.0 loop."""
787
+ """Runs stdio JSON-RPC 2.0 loop with per-call timeout, resilient recovery & auto-reload on upgrade."""
788
+ initial_mtimes = _get_watched_mtimes()
789
+ auto_reload = os.environ.get("TOKENSAFE_MCP_AUTORELOAD", "1").strip().lower() not in ("0", "false", "no")
790
+
652
791
  while True:
653
- line = sys.stdin.readline()
792
+ try:
793
+ line = sys.stdin.readline()
794
+ except Exception:
795
+ break
654
796
  if not line:
655
797
  break
656
798
  line = line.strip()
@@ -666,6 +808,10 @@ def run_mcp_server():
666
808
  method = req.get("method")
667
809
  params = req.get("params", {})
668
810
 
811
+ # Notifications (no id, or notifications/*) must never receive JSON-RPC responses
812
+ if msg_id is None or (isinstance(method, str) and method.startswith("notifications/")):
813
+ continue
814
+
669
815
  response = {"jsonrpc": "2.0", "id": msg_id}
670
816
 
671
817
  if method == "initialize":
@@ -679,21 +825,15 @@ def run_mcp_server():
679
825
  "capabilities": {"tools": {}},
680
826
  "serverInfo": SERVER_INFO
681
827
  }
682
- elif method == "notifications/initialized":
683
- continue
684
828
  elif method == "tools/list":
685
829
  response["result"] = {"tools": TOOLS}
686
830
  elif method == "tools/call":
687
831
  tool_name = params.get("name", "")
688
832
  tool_args = params.get("arguments", {})
689
833
  try:
690
- result = handle_tool_call(tool_name, tool_args)
691
- response["result"] = result
834
+ response["result"] = _execute_with_timeout(tool_name, tool_args)
692
835
  except Exception as e:
693
- response["result"] = {
694
- "isError": True,
695
- "content": [{"type": "text", "text": f"Error: {str(e)}\n{traceback.format_exc()}"}]
696
- }
836
+ response["result"] = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
697
837
  finally:
698
838
  try:
699
839
  from src.telemetry_sync import TelemetrySync
@@ -703,8 +843,17 @@ def run_mcp_server():
703
843
  else:
704
844
  response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
705
845
 
706
- sys.stdout.write(json.dumps(response) + "\n")
707
- sys.stdout.flush()
846
+ try:
847
+ sys.stdout.write(json.dumps(response) + "\n")
848
+ sys.stdout.flush()
849
+ except Exception:
850
+ break
851
+
852
+ # Safeguard: if TokenSafe files were upgraded on disk while running, exit cleanly
853
+ # immediately after sending the response so the host IDE respawns the new version.
854
+ if auto_reload and method == "tools/call":
855
+ if _get_watched_mtimes() != initial_mtimes:
856
+ break
708
857
 
709
858
  def main():
710
859
  run_mcp_server()
package/src/metrics.py CHANGED
@@ -6,12 +6,20 @@ Uses SQLite for persistent, fast, zero-dependency storage.
6
6
 
7
7
  import os
8
8
  import json
9
+ import time
9
10
  import sqlite3
11
+ import threading
10
12
  from contextlib import contextmanager
11
13
  from datetime import datetime, timedelta
12
14
  from typing import Dict, List, Optional, Any, Generator
13
15
 
14
16
  USD_PER_TOKEN = 1.50 / 1_000_000.0
17
+ _METRICS_INIT_LOCK = threading.Lock()
18
+ _INITIALIZED_METRICS_DBS: set = set()
19
+ # Retention / telemetry cadence is wall-clock based (marker file) rather than
20
+ # instance-based counters: lifecycle hooks construct a fresh MetricsTracker per
21
+ # invocation, so per-instance counters never reached the threshold in production.
22
+ _AUTOPRUNE_INTERVAL = float(os.environ.get("TOKENSAFE_AUTOPRUNE_INTERVAL", "3600"))
15
23
 
16
24
 
17
25
  class MetricsTracker:
@@ -26,7 +34,7 @@ class MetricsTracker:
26
34
  os.makedirs(data_dir, exist_ok=True)
27
35
  db_path = os.environ.get("TOKENSAFE_DB_PATH", os.path.join(data_dir, "metrics.db"))
28
36
 
29
- self.db_path = db_path
37
+ self.db_path = os.path.abspath(db_path)
30
38
  self.retention_days = int(os.environ.get("TOKENSAFE_RETENTION_DAYS", "30"))
31
39
  self.max_events = int(os.environ.get("TOKENSAFE_MAX_EVENTS", "5000"))
32
40
  self._event_counter = 0
@@ -34,61 +42,109 @@ class MetricsTracker:
34
42
 
35
43
  @contextmanager
36
44
  def _get_connection(self) -> Generator[sqlite3.Connection, None, None]:
37
- conn = sqlite3.connect(self.db_path)
45
+ conn = sqlite3.connect(self.db_path, timeout=5.0)
38
46
  conn.row_factory = sqlite3.Row
47
+ try:
48
+ conn.execute("PRAGMA busy_timeout=3000;")
49
+ except sqlite3.Error:
50
+ pass
39
51
  try:
40
52
  yield conn
41
53
  conn.commit()
42
54
  finally:
43
55
  conn.close()
44
56
 
57
+ @classmethod
58
+ def _maybe_autoprune(cls, db_path: str):
59
+ """
60
+ Wall-clock-gated retention + telemetry trigger, safe across short-lived
61
+ hook processes. A marker file records the last run; an O_EXCL claim file
62
+ prevents stampedes when several hooks fire concurrently.
63
+ """
64
+ marker = os.path.join(os.path.dirname(db_path) or ".", ".metrics_last_prune")
65
+ claim = marker + ".claim"
66
+ try:
67
+ if os.path.exists(marker) and (time.time() - os.path.getmtime(marker)) < _AUTOPRUNE_INTERVAL:
68
+ return
69
+ try:
70
+ fd = os.open(claim, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
71
+ os.close(fd)
72
+ except FileExistsError:
73
+ return # another process is pruning right now
74
+ try:
75
+ tracker = cls(db_path)
76
+ tracker.prune(days=tracker.retention_days, max_events=tracker.max_events, vacuum=False)
77
+ try:
78
+ from src.telemetry_sync import TelemetrySync
79
+ TelemetrySync.sync_background()
80
+ except Exception:
81
+ pass
82
+ finally:
83
+ try:
84
+ with open(marker, "w", encoding="utf-8") as f:
85
+ f.write(str(int(time.time())))
86
+ if os.path.exists(claim):
87
+ os.unlink(claim)
88
+ except Exception:
89
+ pass
90
+ except Exception:
91
+ pass
92
+
45
93
  def _init_db(self):
46
- with self._get_connection() as conn:
47
- cursor = conn.cursor()
48
- cursor.execute("""
49
- CREATE TABLE IF NOT EXISTS sessions (
50
- session_id TEXT PRIMARY KEY,
51
- created_at TEXT NOT NULL,
52
- last_updated TEXT NOT NULL,
53
- total_original_tokens INTEGER DEFAULT 0,
54
- total_optimized_tokens INTEGER DEFAULT 0,
55
- total_saved_tokens INTEGER DEFAULT 0,
56
- total_usd_saved REAL DEFAULT 0.0
57
- )
58
- """)
59
- cursor.execute("""
60
- CREATE TABLE IF NOT EXISTS events (
61
- id INTEGER PRIMARY KEY AUTOINCREMENT,
62
- session_id TEXT NOT NULL,
63
- timestamp TEXT NOT NULL,
64
- event_type TEXT NOT NULL,
65
- original_tokens INTEGER NOT NULL,
66
- optimized_tokens INTEGER NOT NULL,
67
- saved_tokens INTEGER NOT NULL,
68
- reduction_pct REAL NOT NULL,
69
- est_usd_saved REAL NOT NULL,
70
- details TEXT
71
- )
72
- """)
73
- cursor.execute("""
74
- CREATE TABLE IF NOT EXISTS lifetime_aggregates (
75
- id INTEGER PRIMARY KEY CHECK (id = 1),
76
- total_events INTEGER DEFAULT 0,
77
- total_original_tokens INTEGER DEFAULT 0,
78
- total_optimized_tokens INTEGER DEFAULT 0,
79
- total_saved_tokens INTEGER DEFAULT 0,
80
- total_usd_saved REAL DEFAULT 0.0,
81
- breakdown TEXT DEFAULT '{}'
82
- )
83
- """)
84
- cursor.execute("""
85
- INSERT OR IGNORE INTO lifetime_aggregates (
86
- id, total_events, total_original_tokens, total_optimized_tokens,
87
- total_saved_tokens, total_usd_saved, breakdown
88
- ) VALUES (1, 0, 0, 0, 0, 0.0, '{}')
89
- """)
90
- cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp)")
91
- cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_session_id ON events(session_id)")
94
+ with _METRICS_INIT_LOCK:
95
+ if self.db_path in _INITIALIZED_METRICS_DBS and os.path.exists(self.db_path) and os.path.getsize(self.db_path) > 0:
96
+ return
97
+ with self._get_connection() as conn:
98
+ cursor = conn.cursor()
99
+ try:
100
+ cursor.execute("PRAGMA journal_mode=WAL;")
101
+ except sqlite3.Error:
102
+ pass
103
+ cursor.execute("""
104
+ CREATE TABLE IF NOT EXISTS sessions (
105
+ session_id TEXT PRIMARY KEY,
106
+ created_at TEXT NOT NULL,
107
+ last_updated TEXT NOT NULL,
108
+ total_original_tokens INTEGER DEFAULT 0,
109
+ total_optimized_tokens INTEGER DEFAULT 0,
110
+ total_saved_tokens INTEGER DEFAULT 0,
111
+ total_usd_saved REAL DEFAULT 0.0
112
+ )
113
+ """)
114
+ cursor.execute("""
115
+ CREATE TABLE IF NOT EXISTS events (
116
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
117
+ session_id TEXT NOT NULL,
118
+ timestamp TEXT NOT NULL,
119
+ event_type TEXT NOT NULL,
120
+ original_tokens INTEGER NOT NULL,
121
+ optimized_tokens INTEGER NOT NULL,
122
+ saved_tokens INTEGER NOT NULL,
123
+ reduction_pct REAL NOT NULL,
124
+ est_usd_saved REAL NOT NULL,
125
+ details TEXT
126
+ )
127
+ """)
128
+ cursor.execute("""
129
+ CREATE TABLE IF NOT EXISTS lifetime_aggregates (
130
+ id INTEGER PRIMARY KEY CHECK (id = 1),
131
+ total_events INTEGER DEFAULT 0,
132
+ total_original_tokens INTEGER DEFAULT 0,
133
+ total_optimized_tokens INTEGER DEFAULT 0,
134
+ total_saved_tokens INTEGER DEFAULT 0,
135
+ total_usd_saved REAL DEFAULT 0.0,
136
+ breakdown TEXT DEFAULT '{}'
137
+ )
138
+ """)
139
+ cursor.execute("""
140
+ INSERT OR IGNORE INTO lifetime_aggregates (
141
+ id, total_events, total_original_tokens, total_optimized_tokens,
142
+ total_saved_tokens, total_usd_saved, breakdown
143
+ ) VALUES (1, 0, 0, 0, 0, 0.0, '{}')
144
+ """)
145
+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp)")
146
+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_session_id ON events(session_id)")
147
+ _INITIALIZED_METRICS_DBS.add(self.db_path)
92
148
 
93
149
  def record_event(
94
150
  self,
@@ -131,20 +187,8 @@ class MetricsTracker:
131
187
  """, (session_id, now_iso, now_iso, original_tokens,
132
188
  optimized_tokens, saved_tokens, est_usd))
133
189
 
134
- # Periodic amortized auto-retention check (every 100 events)
135
- self._event_counter += 1
136
- if self._event_counter % 20 == 0:
137
- try:
138
- from src.telemetry_sync import TelemetrySync
139
- TelemetrySync.sync_background()
140
- except Exception:
141
- pass
142
- if self._event_counter >= 100:
143
- self._event_counter = 0
144
- try:
145
- self.prune(days=self.retention_days, max_events=self.max_events, vacuum=False)
146
- except Exception:
147
- pass
190
+ # Wall-clock auto-retention (marker-file gated, cross-process safe)
191
+ self._maybe_autoprune(self.db_path)
148
192
 
149
193
  return {
150
194
  "saved_tokens": saved_tokens,
@@ -219,7 +263,9 @@ class MetricsTracker:
219
263
 
220
264
  def get_monthly_saved_tokens(self) -> int:
221
265
  """Returns total tokens saved in the trailing 30 days for quota calculations."""
222
- thirty_days_ago = (datetime.utcnow() - timedelta(days=30)).isoformat()
266
+ # Events are written with local-time now(); compute the cutoff the same way
267
+ # (previously utcnow vs now mixed naive clocks and skewed the quota window).
268
+ thirty_days_ago = (datetime.now() - timedelta(days=30)).isoformat()
223
269
  with self._get_connection() as conn:
224
270
  cursor = conn.cursor()
225
271
  cursor.execute("""