web3-systemic-agent 1.0.2__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.
src/storage.py ADDED
@@ -0,0 +1,863 @@
1
+ """
2
+ SQLite Storage and Ledger Persistence for Web3 Condition-Action Trigger Agent.
3
+ Provides asynchronous evaluation records, structured error logs, telemetry tracking,
4
+ and aggregation metrics using aiosqlite with sensitive credential redaction.
5
+ """
6
+
7
+ import asyncio
8
+ from datetime import datetime, timezone
9
+ import json
10
+ import logging
11
+ import os
12
+ import re
13
+ import sys
14
+ import tempfile
15
+ from typing import Dict, Any, Optional, List
16
+
17
+ # Ensure module search paths support running directly or as a package
18
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
19
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
20
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
21
+ for _p in (_ROOT_DIR, _SRC_DIR):
22
+ if _p not in sys.path:
23
+ sys.path.insert(0, _p)
24
+
25
+ try:
26
+ import aiosqlite
27
+ import aiosqlite.core
28
+
29
+ # Patch aiosqlite worker thread so closed asyncio event loops do not raise unhandled RuntimeError
30
+ _orig_worker_thread = getattr(aiosqlite.core, "_connection_worker_thread", None)
31
+ if _orig_worker_thread is not None and not getattr(_orig_worker_thread, "_is_patched", False):
32
+ from aiosqlite.core import _STOP_RUNNING_SENTINEL, set_result, set_exception, LOG
33
+
34
+ def _safe_connection_worker_thread(tx):
35
+ while True:
36
+ future, function = tx.get()
37
+ result = None
38
+ try:
39
+ if LOG:
40
+ LOG.debug("executing %s", function)
41
+ result = function()
42
+
43
+ if future:
44
+ try:
45
+ loop = future.get_loop()
46
+ if not loop.is_closed():
47
+ loop.call_soon_threadsafe(set_result, future, result)
48
+ except (RuntimeError, AssertionError):
49
+ pass
50
+ if LOG:
51
+ LOG.debug("operation %s completed", function)
52
+
53
+ if result is _STOP_RUNNING_SENTINEL:
54
+ break
55
+
56
+ except BaseException as e: # noqa B036
57
+ if LOG:
58
+ LOG.debug("returning exception %s", e)
59
+ if future:
60
+ try:
61
+ loop = future.get_loop()
62
+ if not loop.is_closed():
63
+ loop.call_soon_threadsafe(set_exception, future, e)
64
+ except (RuntimeError, AssertionError):
65
+ pass
66
+ if result is _STOP_RUNNING_SENTINEL:
67
+ break
68
+
69
+ _safe_connection_worker_thread._is_patched = True
70
+ aiosqlite.core._connection_worker_thread = _safe_connection_worker_thread
71
+ except ImportError:
72
+ aiosqlite = None # type: ignore
73
+
74
+ try:
75
+ from src.schemas import ConditionRulePayload, FinalAgentResponse, PaymentReceipt
76
+ except ImportError:
77
+ from schemas import ConditionRulePayload, FinalAgentResponse, PaymentReceipt
78
+
79
+ logger = logging.getLogger(__name__)
80
+
81
+ SENSITIVE_KEY_SUBSTRINGS = (
82
+ "api_key",
83
+ "apikey",
84
+ "secret",
85
+ "password",
86
+ "token",
87
+ "private_key",
88
+ "authorization",
89
+ )
90
+
91
+ EXEMPT_KEYS = {
92
+ "input_tokens",
93
+ "output_tokens",
94
+ "prompt_tokens",
95
+ "completion_tokens",
96
+ "candidates_token_count",
97
+ "prompt_token_count",
98
+ }
99
+
100
+ API_KEY_REGEX = re.compile(r"(AIza[0-9A-Za-z_-]{20,}|sk-[0-9A-Za-z_-]{15,})")
101
+
102
+
103
+ def redact_secrets(obj: Any) -> Any:
104
+ """
105
+ Recursively redacts sensitive API keys, secrets, tokens, passwords, and private keys.
106
+ Exempts token metric counts. Scrubs regex-matched API keys from string values.
107
+ """
108
+ if isinstance(obj, dict):
109
+ redacted = {}
110
+ for k, v in obj.items():
111
+ k_lower = str(k).lower()
112
+ if k_lower not in EXEMPT_KEYS and any(s in k_lower for s in SENSITIVE_KEY_SUBSTRINGS):
113
+ redacted[k] = "***REDACTED***"
114
+ else:
115
+ redacted[k] = redact_secrets(v)
116
+ return redacted
117
+ elif isinstance(obj, list):
118
+ return [redact_secrets(item) for item in obj]
119
+ elif isinstance(obj, tuple):
120
+ return tuple(redact_secrets(item) for item in obj)
121
+ elif isinstance(obj, str):
122
+ return API_KEY_REGEX.sub("***REDACTED***", obj)
123
+ elif hasattr(obj, "model_dump") and callable(obj.model_dump):
124
+ return redact_secrets(obj.model_dump())
125
+ return obj
126
+
127
+
128
+ def get_default_db_path() -> str:
129
+ """
130
+ Resolves the SQLite database file path.
131
+ Uses LEDGER_DB_PATH if set; in pytest defaults to a per-process temp path;
132
+ otherwise defaults to data/agent.db at project root.
133
+ """
134
+ env_path = os.getenv("LEDGER_DB_PATH")
135
+ if env_path:
136
+ return env_path
137
+ if "pytest" in sys.modules:
138
+ return os.path.join(tempfile.gettempdir(), f"agent_pytest_{os.getpid()}.db")
139
+ return os.path.join(_ROOT_DIR, "data", "agent.db")
140
+
141
+
142
+ def is_valid_sqlite_path(path: Optional[str]) -> bool:
143
+ """
144
+ Validates whether a path is safe and accessible for SQLite connections.
145
+ Rejects invalid drive letters on Windows, directories, or paths with non-existent parent roots.
146
+ """
147
+ if not path or not isinstance(path, str):
148
+ return False
149
+ if path == ":memory:":
150
+ return True
151
+ try:
152
+ abs_path = os.path.abspath(path)
153
+ if os.path.isdir(abs_path):
154
+ return False
155
+ drive, _ = os.path.splitdrive(abs_path)
156
+ if drive:
157
+ drive_root = drive + "\\" if not drive.endswith(("\\", "/")) else drive
158
+ if not os.path.exists(drive_root):
159
+ return False
160
+ parent_dir = os.path.dirname(abs_path)
161
+ if parent_dir:
162
+ if os.path.exists(parent_dir):
163
+ if not os.path.isdir(parent_dir):
164
+ return False
165
+ if not os.access(parent_dir, os.W_OK):
166
+ return False
167
+ else:
168
+ ancestor = parent_dir
169
+ while ancestor and not os.path.exists(ancestor):
170
+ prev = os.path.dirname(ancestor)
171
+ if prev == ancestor:
172
+ break
173
+ ancestor = prev
174
+ if ancestor and os.path.exists(ancestor):
175
+ if not os.path.isdir(ancestor) or not os.access(ancestor, os.W_OK):
176
+ return False
177
+ else:
178
+ return False
179
+ return True
180
+ except Exception:
181
+ return False
182
+
183
+
184
+ class AgentStorage:
185
+ """
186
+ Asynchronous SQLite storage provider for evaluation telemetry and operational error logging.
187
+ Guarantees non-blocking, exception-safe persistence that never crashes callers.
188
+ """
189
+
190
+ def __init__(self, db_path: Optional[str] = None):
191
+ self.db_path = db_path or get_default_db_path()
192
+ self._initialized = False
193
+ self._lock = asyncio.Lock()
194
+
195
+ async def initialize(self) -> None:
196
+ """
197
+ Creates necessary parent directories and initializes SQLite tables and indices.
198
+ """
199
+ if self._initialized:
200
+ return
201
+
202
+ async with self._lock:
203
+ if self._initialized:
204
+ return
205
+
206
+ if aiosqlite is None:
207
+ logger.warning("aiosqlite is not available; AgentStorage will operate in no-op mode.")
208
+ self._initialized = True
209
+ return
210
+
211
+ if not is_valid_sqlite_path(self.db_path):
212
+ logger.warning(f"Invalid or unwritable SQLite path: {self.db_path}")
213
+ self._initialized = True
214
+ return
215
+
216
+ try:
217
+ if self.db_path != ":memory:":
218
+ parent_dir = os.path.dirname(os.path.abspath(self.db_path))
219
+ os.makedirs(parent_dir, exist_ok=True)
220
+
221
+ async with aiosqlite.connect(self.db_path) as db:
222
+ if self.db_path != ":memory:":
223
+ await db.execute("PRAGMA journal_mode=WAL")
224
+ await db.execute("PRAGMA synchronous=NORMAL")
225
+ await db.execute("PRAGMA busy_timeout=5000")
226
+
227
+ await db.execute(
228
+ """
229
+ CREATE TABLE IF NOT EXISTS evaluations (
230
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
231
+ created_at TEXT NOT NULL,
232
+ rule_id TEXT NOT NULL,
233
+ chain_id INTEGER NOT NULL,
234
+ job_id TEXT,
235
+ source TEXT NOT NULL,
236
+ stage1_passed INTEGER NOT NULL,
237
+ llm_invoked INTEGER NOT NULL,
238
+ decision TEXT,
239
+ risk_score REAL,
240
+ provider TEXT,
241
+ model TEXT,
242
+ cached INTEGER NOT NULL DEFAULT 0,
243
+ input_tokens INTEGER NOT NULL DEFAULT 0,
244
+ output_tokens INTEGER NOT NULL DEFAULT 0,
245
+ est_cost_usd REAL NOT NULL DEFAULT 0.0,
246
+ latency_ms REAL NOT NULL DEFAULT 0.0,
247
+ status TEXT NOT NULL,
248
+ request_json TEXT NOT NULL,
249
+ response_json TEXT NOT NULL
250
+ )
251
+ """
252
+ )
253
+ await db.execute(
254
+ "CREATE INDEX IF NOT EXISTS idx_evaluations_rule_id ON evaluations(rule_id)"
255
+ )
256
+ await db.execute(
257
+ "CREATE INDEX IF NOT EXISTS idx_evaluations_created_at ON evaluations(created_at)"
258
+ )
259
+
260
+ await db.execute(
261
+ """
262
+ CREATE TABLE IF NOT EXISTS error_log (
263
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
264
+ created_at TEXT NOT NULL,
265
+ stage TEXT NOT NULL,
266
+ rule_id TEXT,
267
+ job_id TEXT,
268
+ error_type TEXT NOT NULL,
269
+ message TEXT NOT NULL,
270
+ traceback TEXT,
271
+ context_json TEXT
272
+ )
273
+ """
274
+ )
275
+ await db.execute(
276
+ "CREATE INDEX IF NOT EXISTS idx_error_log_stage ON error_log(stage)"
277
+ )
278
+ await db.execute(
279
+ "CREATE INDEX IF NOT EXISTS idx_error_log_created_at ON error_log(created_at)"
280
+ )
281
+
282
+ await db.execute(
283
+ """
284
+ CREATE TABLE IF NOT EXISTS payments (
285
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
286
+ payment_id TEXT NOT NULL UNIQUE,
287
+ created_at TEXT NOT NULL,
288
+ payer_address TEXT NOT NULL,
289
+ pay_to_address TEXT NOT NULL,
290
+ amount_usdc REAL NOT NULL,
291
+ amount_atomic INTEGER NOT NULL,
292
+ network TEXT NOT NULL,
293
+ asset TEXT NOT NULL,
294
+ tx_hash TEXT NOT NULL,
295
+ endpoint TEXT NOT NULL,
296
+ rule_id TEXT,
297
+ job_id TEXT,
298
+ status TEXT NOT NULL DEFAULT 'SETTLED'
299
+ )
300
+ """
301
+ )
302
+ await db.execute(
303
+ "CREATE INDEX IF NOT EXISTS idx_payments_payer ON payments(payer_address)"
304
+ )
305
+ await db.execute(
306
+ "CREATE INDEX IF NOT EXISTS idx_payments_created_at ON payments(created_at)"
307
+ )
308
+ await db.commit()
309
+
310
+ self._initialized = True
311
+ except Exception as exc:
312
+ logger.warning(f"AgentStorage failed to initialize DB at {self.db_path}: {exc}")
313
+
314
+ async def record_evaluation(
315
+ self,
316
+ payload: ConditionRulePayload,
317
+ response: FinalAgentResponse,
318
+ source: str = "engine",
319
+ job_id: Optional[str] = None,
320
+ latency_ms: Optional[float] = None,
321
+ ) -> Optional[int]:
322
+ """
323
+ Records an evaluation lifecycle execution.
324
+ Safely captures telemetry and redacts credentials without raising exceptions.
325
+ """
326
+ try:
327
+ loop = asyncio.get_running_loop()
328
+ if loop.is_closed() or not loop.is_running():
329
+ return None
330
+ except RuntimeError:
331
+ return None
332
+
333
+ try:
334
+ if not is_valid_sqlite_path(self.db_path):
335
+ return None
336
+
337
+ if not self._initialized:
338
+ await self.initialize()
339
+
340
+ if aiosqlite is None:
341
+ return None
342
+
343
+ now = datetime.now(timezone.utc).isoformat()
344
+ chain_id_val = (
345
+ payload.chain_id.value
346
+ if hasattr(payload.chain_id, "value")
347
+ else int(payload.chain_id)
348
+ )
349
+
350
+ stage1_passed = 1 if response.deterministic_check.passed else 0
351
+ llm_invoked = 1 if response.llm_invoked else 0
352
+ sem = response.semantic_Evaluation
353
+
354
+ decision = sem.recommended_action if sem is not None else None
355
+ risk_score = float(sem.risk_score) if sem is not None else None
356
+ provider = getattr(sem, "provider", None) if sem is not None else None
357
+ model = getattr(sem, "model", None) if sem is not None else None
358
+ cached = 1 if (sem is not None and getattr(sem, "cached", False)) else 0
359
+ input_tokens = int(getattr(sem, "input_tokens", 0) or 0) if sem is not None else 0
360
+ output_tokens = int(getattr(sem, "output_tokens", 0) or 0) if sem is not None else 0
361
+ est_cost_usd = float(getattr(sem, "estimated_cost_usd", 0.0) or 0.0) if sem is not None else 0.0
362
+
363
+ eval_latency = latency_ms
364
+ if eval_latency is None and sem is not None:
365
+ eval_latency = getattr(sem, "latency_ms", 0.0)
366
+ eval_latency_ms = float(eval_latency or 0.0)
367
+
368
+ status = "error" if response.deterministic_check.error is not None else "ok"
369
+
370
+ req_dict = redact_secrets(payload.model_dump())
371
+ resp_dict = redact_secrets(response.model_dump())
372
+ request_json = json.dumps(req_dict, default=str)
373
+ response_json = json.dumps(resp_dict, default=str)
374
+
375
+ async with aiosqlite.connect(self.db_path) as db:
376
+ cursor = await db.execute(
377
+ """
378
+ INSERT INTO evaluations (
379
+ created_at, rule_id, chain_id, job_id, source,
380
+ stage1_passed, llm_invoked, decision, risk_score,
381
+ provider, model, cached, input_tokens, output_tokens,
382
+ est_cost_usd, latency_ms, status, request_json, response_json
383
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
384
+ """,
385
+ (
386
+ now,
387
+ payload.rule_id,
388
+ chain_id_val,
389
+ job_id,
390
+ source,
391
+ stage1_passed,
392
+ llm_invoked,
393
+ decision,
394
+ risk_score,
395
+ provider,
396
+ model,
397
+ cached,
398
+ input_tokens,
399
+ output_tokens,
400
+ est_cost_usd,
401
+ eval_latency_ms,
402
+ status,
403
+ request_json,
404
+ response_json,
405
+ ),
406
+ )
407
+ await db.commit()
408
+ return cursor.lastrowid
409
+ except Exception as exc:
410
+ logger.warning(f"AgentStorage failed to record evaluation in {self.db_path}: {exc}")
411
+ return None
412
+
413
+ async def log_error(
414
+ self,
415
+ stage: str,
416
+ error_type: str,
417
+ message: str,
418
+ rule_id: Optional[str] = None,
419
+ job_id: Optional[str] = None,
420
+ traceback_str: Optional[str] = None,
421
+ context: Optional[Dict[str, Any]] = None,
422
+ ) -> Optional[int]:
423
+ """
424
+ Records an operational or execution error.
425
+ Scrubs secrets from message, traceback, and context before saving.
426
+ """
427
+ try:
428
+ loop = asyncio.get_running_loop()
429
+ if loop.is_closed() or not loop.is_running():
430
+ return None
431
+ except RuntimeError:
432
+ return None
433
+
434
+ try:
435
+ if not is_valid_sqlite_path(self.db_path):
436
+ return None
437
+
438
+ if not self._initialized:
439
+ await self.initialize()
440
+
441
+ if aiosqlite is None:
442
+ return None
443
+
444
+ now = datetime.now(timezone.utc).isoformat()
445
+ redacted_message = str(redact_secrets(message)) if message is not None else ""
446
+ redacted_traceback = (
447
+ str(redact_secrets(traceback_str)) if traceback_str is not None else None
448
+ )
449
+ redacted_context = (
450
+ json.dumps(redact_secrets(context), default=str) if context is not None else None
451
+ )
452
+
453
+ async with aiosqlite.connect(self.db_path) as db:
454
+ cursor = await db.execute(
455
+ """
456
+ INSERT INTO error_log (
457
+ created_at, stage, rule_id, job_id, error_type, message, traceback, context_json
458
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
459
+ """,
460
+ (
461
+ now,
462
+ stage,
463
+ rule_id,
464
+ job_id,
465
+ error_type,
466
+ redacted_message,
467
+ redacted_traceback,
468
+ redacted_context,
469
+ ),
470
+ )
471
+ await db.commit()
472
+ return cursor.lastrowid
473
+ except Exception as exc:
474
+ logger.warning(f"AgentStorage failed to log error in {self.db_path}: {exc}")
475
+ return None
476
+
477
+ async def get_evaluations(
478
+ self, limit: int = 100, rule_id: Optional[str] = None
479
+ ) -> List[Dict[str, Any]]:
480
+ """
481
+ Retrieves recent evaluations with optional rule_id filtering.
482
+ """
483
+ try:
484
+ if not is_valid_sqlite_path(self.db_path):
485
+ return []
486
+
487
+ if not self._initialized:
488
+ await self.initialize()
489
+
490
+ if aiosqlite is None:
491
+ return []
492
+
493
+ async with aiosqlite.connect(self.db_path) as db:
494
+ db.row_factory = aiosqlite.Row
495
+ if rule_id:
496
+ cursor = await db.execute(
497
+ "SELECT * FROM evaluations WHERE rule_id = ? ORDER BY id DESC LIMIT ?",
498
+ (rule_id, limit),
499
+ )
500
+ else:
501
+ cursor = await db.execute(
502
+ "SELECT * FROM evaluations ORDER BY id DESC LIMIT ?",
503
+ (limit,),
504
+ )
505
+ rows = await cursor.fetchall()
506
+ return [dict(r) for r in rows]
507
+ except Exception as exc:
508
+ logger.warning(f"AgentStorage failed to get evaluations from {self.db_path}: {exc}")
509
+ return []
510
+
511
+ async def get_evaluations_by_rule(
512
+ self, rule_id: str, limit: int = 100
513
+ ) -> List[Dict[str, Any]]:
514
+ """
515
+ Retrieves recent evaluations matching a specific rule_id.
516
+ """
517
+ return await self.get_evaluations(limit=limit, rule_id=rule_id)
518
+
519
+ async def get_recent_feed_evaluations(self, limit: int = 20) -> List[Dict[str, Any]]:
520
+ """
521
+ Retrieves the most recent evaluations for the public security feed,
522
+ selecting feed-relevant columns safely and returning [] on failure.
523
+ """
524
+ try:
525
+ if not is_valid_sqlite_path(self.db_path):
526
+ return []
527
+
528
+ if not self._initialized:
529
+ await self.initialize()
530
+
531
+ if aiosqlite is None:
532
+ return []
533
+
534
+ safe_limit = max(1, int(limit))
535
+ async with aiosqlite.connect(self.db_path) as db:
536
+ db.row_factory = aiosqlite.Row
537
+ cursor = await db.execute(
538
+ """
539
+ SELECT id, created_at, rule_id, chain_id, source,
540
+ stage1_passed, llm_invoked, decision, risk_score,
541
+ latency_ms, status, request_json, response_json
542
+ FROM evaluations
543
+ ORDER BY id DESC
544
+ LIMIT ?
545
+ """,
546
+ (safe_limit,),
547
+ )
548
+ rows = await cursor.fetchall()
549
+ return [dict(r) for r in rows]
550
+ except Exception as exc:
551
+ logger.warning(f"AgentStorage failed to get recent feed evaluations from {self.db_path}: {exc}")
552
+ return []
553
+
554
+ async def get_errors(
555
+ self, limit: int = 100, stage: Optional[str] = None
556
+ ) -> List[Dict[str, Any]]:
557
+ """
558
+ Retrieves recent operational errors with optional stage filtering.
559
+ """
560
+ try:
561
+ if not is_valid_sqlite_path(self.db_path):
562
+ return []
563
+
564
+ if not self._initialized:
565
+ await self.initialize()
566
+
567
+ if aiosqlite is None:
568
+ return []
569
+
570
+ async with aiosqlite.connect(self.db_path) as db:
571
+ db.row_factory = aiosqlite.Row
572
+ if stage:
573
+ cursor = await db.execute(
574
+ "SELECT * FROM error_log WHERE stage = ? ORDER BY id DESC LIMIT ?",
575
+ (stage, limit),
576
+ )
577
+ else:
578
+ cursor = await db.execute(
579
+ "SELECT * FROM error_log ORDER BY id DESC LIMIT ?",
580
+ (limit,),
581
+ )
582
+ rows = await cursor.fetchall()
583
+ return [dict(r) for r in rows]
584
+ except Exception as exc:
585
+ logger.warning(f"AgentStorage failed to get errors from {self.db_path}: {exc}")
586
+ return []
587
+
588
+ async def record_payment(
589
+ self,
590
+ receipt: Any,
591
+ rule_id: Optional[str] = None,
592
+ job_id: Optional[str] = None,
593
+ status: str = "SETTLED",
594
+ ) -> Optional[int]:
595
+ """
596
+ Records an x402 payment settlement into the ledger.
597
+ Returns cursor.lastrowid on success, or None on failure or duplicate payment_id.
598
+ """
599
+ try:
600
+ loop = asyncio.get_running_loop()
601
+ if loop.is_closed() or not loop.is_running():
602
+ return None
603
+ except RuntimeError:
604
+ return None
605
+
606
+ try:
607
+ if not is_valid_sqlite_path(self.db_path):
608
+ return None
609
+
610
+ if not self._initialized:
611
+ await self.initialize()
612
+
613
+ if aiosqlite is None:
614
+ return None
615
+
616
+ payment_id = getattr(receipt, "payment_id", None) or (receipt.get("payment_id") if isinstance(receipt, dict) else None)
617
+ if not payment_id:
618
+ return None
619
+
620
+ payer_address = getattr(receipt, "payer_address", None) or (receipt.get("payer_address") if isinstance(receipt, dict) else None)
621
+ pay_to_address = getattr(receipt, "pay_to_address", None) or (receipt.get("pay_to_address") if isinstance(receipt, dict) else None)
622
+ amount_usdc = float(getattr(receipt, "amount_usdc", 0.0) if not isinstance(receipt, dict) else receipt.get("amount_usdc", 0.0))
623
+ amount_atomic = int(getattr(receipt, "amount_atomic", 0) if not isinstance(receipt, dict) else receipt.get("amount_atomic", 0))
624
+ network = getattr(receipt, "network", "eip155:84532") if not isinstance(receipt, dict) else receipt.get("network", "eip155:84532")
625
+ asset = getattr(receipt, "asset", "USDC") if not isinstance(receipt, dict) else receipt.get("asset", "USDC")
626
+ tx_hash = getattr(receipt, "tx_hash", "") if not isinstance(receipt, dict) else receipt.get("tx_hash", "")
627
+ endpoint = getattr(receipt, "endpoint", "") if not isinstance(receipt, dict) else receipt.get("endpoint", "")
628
+ created_at = (
629
+ getattr(receipt, "settled_at", None)
630
+ or (receipt.get("settled_at") if isinstance(receipt, dict) else None)
631
+ or datetime.now(timezone.utc).isoformat()
632
+ )
633
+
634
+ async with aiosqlite.connect(self.db_path) as db:
635
+ cursor = await db.execute(
636
+ """
637
+ INSERT INTO payments (
638
+ payment_id, created_at, payer_address, pay_to_address,
639
+ amount_usdc, amount_atomic, network, asset, tx_hash,
640
+ endpoint, rule_id, job_id, status
641
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
642
+ """,
643
+ (
644
+ str(payment_id),
645
+ str(created_at),
646
+ str(payer_address),
647
+ str(pay_to_address),
648
+ amount_usdc,
649
+ amount_atomic,
650
+ str(network),
651
+ str(asset),
652
+ str(tx_hash),
653
+ str(endpoint),
654
+ rule_id,
655
+ job_id,
656
+ status,
657
+ ),
658
+ )
659
+ await db.commit()
660
+ return cursor.lastrowid
661
+ except Exception as exc:
662
+ logger.warning(f"AgentStorage failed to record payment in {self.db_path}: {exc}")
663
+ return None
664
+
665
+ async def is_payment_settled(self, payment_id: str) -> bool:
666
+ """
667
+ Checks whether a payment with the specified payment_id already exists in the ledger.
668
+ Used to prevent payment replay attacks.
669
+ """
670
+ try:
671
+ if not is_valid_sqlite_path(self.db_path):
672
+ return False
673
+
674
+ if not self._initialized:
675
+ await self.initialize()
676
+
677
+ if aiosqlite is None:
678
+ return False
679
+
680
+ async with aiosqlite.connect(self.db_path) as db:
681
+ async with db.execute(
682
+ "SELECT 1 FROM payments WHERE payment_id = ? LIMIT 1",
683
+ (str(payment_id),),
684
+ ) as cursor:
685
+ row = await cursor.fetchone()
686
+ return row is not None
687
+ except Exception as exc:
688
+ logger.warning(f"AgentStorage failed to check settled payment in {self.db_path}: {exc}")
689
+ return False
690
+
691
+ async def get_payments(
692
+ self, limit: int = 100, payer_address: Optional[str] = None
693
+ ) -> List[Dict[str, Any]]:
694
+ """
695
+ Retrieves recent payments ordered by id DESC with optional payer_address filter.
696
+ """
697
+ try:
698
+ if not is_valid_sqlite_path(self.db_path):
699
+ return []
700
+
701
+ if not self._initialized:
702
+ await self.initialize()
703
+
704
+ if aiosqlite is None:
705
+ return []
706
+
707
+ async with aiosqlite.connect(self.db_path) as db:
708
+ db.row_factory = aiosqlite.Row
709
+ if payer_address:
710
+ cursor = await db.execute(
711
+ "SELECT * FROM payments WHERE payer_address = ? ORDER BY id DESC LIMIT ?",
712
+ (payer_address, limit),
713
+ )
714
+ else:
715
+ cursor = await db.execute(
716
+ "SELECT * FROM payments ORDER BY id DESC LIMIT ?",
717
+ (limit,),
718
+ )
719
+ rows = await cursor.fetchall()
720
+ return [dict(r) for r in rows]
721
+ except Exception as exc:
722
+ logger.warning(f"AgentStorage failed to get payments from {self.db_path}: {exc}")
723
+ return []
724
+
725
+ async def get_summary_metrics(self, target_price_usd: float = 0.01) -> Dict[str, Any]:
726
+ """
727
+ Aggregates operational metrics across all historical evaluations, error logs, and payments.
728
+ """
729
+ try:
730
+ if not is_valid_sqlite_path(self.db_path):
731
+ return {
732
+ "total_evaluations": 0,
733
+ "stage1_filter_rate_pct": 0.0,
734
+ "total_cost_usd": 0.0,
735
+ "avg_cost_per_eval_usd": 0.0,
736
+ "avg_cost_per_llm_call_usd": 0.0,
737
+ "max_cost_usd": 0.0,
738
+ "p95_cost_usd": 0.0,
739
+ "pct_under_target": 0.0,
740
+ "total_errors": 0,
741
+ "errors_by_stage": {},
742
+ "total_input_tokens": 0,
743
+ "total_output_tokens": 0,
744
+ "total_payments_settled": 0,
745
+ "total_revenue_usdc": 0.0,
746
+ "net_profit_usd": 0.0,
747
+ }
748
+
749
+ if not self._initialized:
750
+ await self.initialize()
751
+
752
+ if aiosqlite is None:
753
+ raise RuntimeError("aiosqlite is not available")
754
+
755
+ async with aiosqlite.connect(self.db_path) as db:
756
+ db.row_factory = aiosqlite.Row
757
+ async with db.execute(
758
+ "SELECT stage1_passed, llm_invoked, input_tokens, output_tokens, est_cost_usd FROM evaluations ORDER BY id ASC"
759
+ ) as cursor:
760
+ eval_rows = await cursor.fetchall()
761
+ async with db.execute(
762
+ "SELECT stage, COUNT(*) as count FROM error_log GROUP BY stage"
763
+ ) as cursor:
764
+ error_stage_rows = await cursor.fetchall()
765
+ async with db.execute("SELECT COUNT(*) as total FROM error_log") as cursor:
766
+ total_error_row = await cursor.fetchone()
767
+ async with db.execute(
768
+ "SELECT COUNT(*) as count, COALESCE(SUM(amount_usdc), 0.0) as revenue FROM payments WHERE status = 'SETTLED'"
769
+ ) as cursor:
770
+ pmt_row = await cursor.fetchone()
771
+
772
+ total_evaluations = len(eval_rows)
773
+ stage1_halted_count = sum(1 for r in eval_rows if r["llm_invoked"] == 0)
774
+ llm_invoked_count = sum(1 for r in eval_rows if r["llm_invoked"] == 1)
775
+ stage1_filter_rate_pct = (
776
+ round((stage1_halted_count / total_evaluations) * 100.0, 2)
777
+ if total_evaluations > 0
778
+ else 0.0
779
+ )
780
+
781
+ total_input_tokens = sum(int(r["input_tokens"] or 0) for r in eval_rows)
782
+ total_output_tokens = sum(int(r["output_tokens"] or 0) for r in eval_rows)
783
+ costs = [float(r["est_cost_usd"] or 0.0) for r in eval_rows]
784
+ total_cost_usd = round(sum(costs), 8)
785
+ avg_cost_per_eval_usd = (
786
+ round(total_cost_usd / total_evaluations, 8) if total_evaluations > 0 else 0.0
787
+ )
788
+
789
+ llm_costs = [
790
+ float(r["est_cost_usd"] or 0.0)
791
+ for r in eval_rows
792
+ if r["llm_invoked"] == 1
793
+ ]
794
+ avg_cost_per_llm_call_usd = (
795
+ round(sum(llm_costs) / len(llm_costs), 8) if llm_costs else 0.0
796
+ )
797
+
798
+ if costs:
799
+ sorted_costs = sorted(costs)
800
+ max_cost_usd = round(sorted_costs[-1], 8)
801
+ p95_index = int(0.95 * len(sorted_costs))
802
+ if p95_index >= len(sorted_costs):
803
+ p95_index = len(sorted_costs) - 1
804
+ p95_cost_usd = round(sorted_costs[p95_index], 8)
805
+ else:
806
+ max_cost_usd = 0.0
807
+ p95_cost_usd = 0.0
808
+
809
+ price_covers_max_cost = (
810
+ bool(target_price_usd > max_cost_usd) if total_evaluations > 0 else True
811
+ )
812
+
813
+ errors_by_stage = {r["stage"]: int(r["count"]) for r in error_stage_rows}
814
+ total_errors = int(total_error_row["total"] or 0) if total_error_row else 0
815
+
816
+ total_payments_settled = int(pmt_row["count"] or 0) if pmt_row else 0
817
+ total_revenue_usdc = round(float(pmt_row["revenue"] or 0.0), 6) if pmt_row else 0.0
818
+ net_profit_usd = round(total_revenue_usdc - total_cost_usd, 6)
819
+
820
+ return {
821
+ "total_evaluations": total_evaluations,
822
+ "stage1_halted_count": stage1_halted_count,
823
+ "stage1_filter_rate_pct": stage1_filter_rate_pct,
824
+ "stage1_Filter_rate_pct": stage1_filter_rate_pct,
825
+ "llm_invoked_count": llm_invoked_count,
826
+ "total_input_tokens": total_input_tokens,
827
+ "total_output_tokens": total_output_tokens,
828
+ "total_cost_usd": total_cost_usd,
829
+ "avg_cost_per_eval_usd": avg_cost_per_eval_usd,
830
+ "avg_cost_per_llm_call_usd": avg_cost_per_llm_call_usd,
831
+ "max_cost_usd": max_cost_usd,
832
+ "p95_cost_usd": p95_cost_usd,
833
+ "target_price_usd": float(target_price_usd),
834
+ "price_covers_max_cost": price_covers_max_cost,
835
+ "errors_by_stage": errors_by_stage,
836
+ "total_errors": total_errors,
837
+ "total_payments_settled": total_payments_settled,
838
+ "total_revenue_usdc": total_revenue_usdc,
839
+ "net_profit_usd": net_profit_usd,
840
+ }
841
+ except Exception as exc:
842
+ logger.warning(f"Error querying summary metrics from {self.db_path}: {exc}")
843
+ return {
844
+ "total_evaluations": 0,
845
+ "stage1_halted_count": 0,
846
+ "stage1_filter_rate_pct": 0.0,
847
+ "stage1_Filter_rate_pct": 0.0,
848
+ "llm_invoked_count": 0,
849
+ "total_input_tokens": 0,
850
+ "total_output_tokens": 0,
851
+ "total_cost_usd": 0.0,
852
+ "avg_cost_per_eval_usd": 0.0,
853
+ "avg_cost_per_llm_call_usd": 0.0,
854
+ "max_cost_usd": 0.0,
855
+ "p95_cost_usd": 0.0,
856
+ "target_price_usd": float(target_price_usd),
857
+ "price_covers_max_cost": True,
858
+ "errors_by_stage": {},
859
+ "total_errors": 0,
860
+ "total_payments_settled": 0,
861
+ "total_revenue_usdc": 0.0,
862
+ "net_profit_usd": 0.0,
863
+ }