debug-agent-py 0.3.0__tar.gz → 0.5.0__tar.gz
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.
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/PKG-INFO +50 -6
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/README.md +49 -5
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/pyproject.toml +1 -1
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/__init__.py +12 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/cache_inspector.py +224 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/error_tracking.py +205 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/fastapi_ext.py +226 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/fd_inspector.py +150 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/health_inspector.py +124 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/http_client_inspector.py +230 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/logging_inspector.py +194 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/metrics_inspector.py +102 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/scheduler_inspector.py +227 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/security_inspector.py +251 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/warnings_inspector.py +85 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/websocket_inspector.py +225 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/PKG-INFO +50 -6
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/SOURCES.txt +12 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/setup.cfg +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/__init__.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/chat_session.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/config.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/context_compressor.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/engine.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/async_tasks.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/celery.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/database.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/django.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/flask_ext.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/framework.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/http_tracker.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/jinja2.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/memory.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/modules.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/redis.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/runtime.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/signals.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/system.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/threads.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/llm_client.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/middleware.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/system_prompt_builder.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/tool_registry.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/web/__init__.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent/web/chat_page.py +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/dependency_links.txt +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/requires.txt +0 -0
- {debug_agent_py-0.3.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: debug-agent-py
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: AI-powered runtime debugging agent for Python web applications
|
|
5
5
|
Author-email: ggcode <noreply@ggcode.dev>
|
|
6
6
|
License: MIT
|
|
@@ -52,10 +52,10 @@ Requires-Dist: pytest; extra == "dev"
|
|
|
52
52
|
# Python Debug Agent
|
|
53
53
|
|
|
54
54
|
[](https://pypi.org/project/debug-agent-py/)
|
|
55
|
-

|
|
56
|
+

|
|
57
57
|
|
|
58
|
-
An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **
|
|
58
|
+
An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **68 diagnostic tools across 24 inspectors**.
|
|
59
59
|
|
|
60
60
|
## Quick Start
|
|
61
61
|
|
|
@@ -99,11 +99,11 @@ http://localhost:8000/agent
|
|
|
99
99
|
- **Context compression** — automatically summarizes old conversation when token limit is approached
|
|
100
100
|
- **Dark-themed chat UI** with full markdown rendering (tables, code blocks, lists)
|
|
101
101
|
- **Max tool rounds** (25) with forced final summary when limit is reached
|
|
102
|
-
- **
|
|
102
|
+
- **68 diagnostic tools** across **24 inspectors**
|
|
103
103
|
- Works with Flask, FastAPI, and Django
|
|
104
104
|
- Zero external dependencies (no Datadog, no Grafana, no APM)
|
|
105
105
|
|
|
106
|
-
## Inspectors & Tools (
|
|
106
|
+
## Inspectors & Tools (68)
|
|
107
107
|
|
|
108
108
|
### Memory Inspector
|
|
109
109
|
| Tool | Description |
|
|
@@ -220,6 +220,50 @@ http://localhost:8000/agent
|
|
|
220
220
|
| `get_wsgi_info` | WSGI server details (Gunicorn/uWSGI workers, config) |
|
|
221
221
|
| `get_asgi_apps` | List ASGI application scope and middleware chain |
|
|
222
222
|
|
|
223
|
+
### Logging Inspector
|
|
224
|
+
| Tool | Description |
|
|
225
|
+
|------|-------------|
|
|
226
|
+
| `get_logging_tree` | Python logging module logger hierarchy and levels |
|
|
227
|
+
| `get_recent_logs` | Recent log entries from the built-in ring buffer |
|
|
228
|
+
| `get_logging_config` | Current logging configuration (handlers, formatters, levels) |
|
|
229
|
+
| `set_log_level` | Dynamically set the log level for a named logger |
|
|
230
|
+
|
|
231
|
+
### Cache Inspector
|
|
232
|
+
| Tool | Description |
|
|
233
|
+
|------|-------------|
|
|
234
|
+
| `get_cache_info` | Stats for registered caches (hit rate, miss count, key count) |
|
|
235
|
+
| `get_cache_keys` | List keys from a registered cache with optional prefix filter |
|
|
236
|
+
| `clear_cache` | Clear all entries from a registered cache |
|
|
237
|
+
|
|
238
|
+
### Outbound HTTP Inspector
|
|
239
|
+
| Tool | Description |
|
|
240
|
+
|------|-------------|
|
|
241
|
+
| `get_http_pool_stats` | HTTP client connection pool stats (connections, keepalive, timeouts) |
|
|
242
|
+
| `get_outbound_summary` | Aggregated outbound HTTP call stats (total, avg latency, error rate) |
|
|
243
|
+
|
|
244
|
+
### File Descriptor Inspector
|
|
245
|
+
| Tool | Description |
|
|
246
|
+
|------|-------------|
|
|
247
|
+
| `get_fd_count` | Current number of open file descriptors |
|
|
248
|
+
| `get_fd_limit` | File descriptor soft and hard limits (RLIMIT_NOFILE) |
|
|
249
|
+
| `get_fd_list` | List open file descriptors with type and details |
|
|
250
|
+
|
|
251
|
+
### Metrics Inspector
|
|
252
|
+
| Tool | Description |
|
|
253
|
+
|------|-------------|
|
|
254
|
+
| `get_registered_metrics` | List all registered metrics from prometheus_client |
|
|
255
|
+
| `get_metric_value` | Get current value of a specific metric by name |
|
|
256
|
+
|
|
257
|
+
### FastAPI Inspector
|
|
258
|
+
| Tool | Description |
|
|
259
|
+
|------|-------------|
|
|
260
|
+
| `get_fastapi_openapi` | List FastAPI routes, schemas, and OpenAPI spec details |
|
|
261
|
+
|
|
262
|
+
### Warnings Inspector
|
|
263
|
+
| Tool | Description |
|
|
264
|
+
|------|-------------|
|
|
265
|
+
| `get_warnings` | List captured Python warnings with category, message, and location |
|
|
266
|
+
|
|
223
267
|
## Custom Tools
|
|
224
268
|
|
|
225
269
|
```python
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# Python Debug Agent
|
|
2
2
|
|
|
3
3
|
[](https://pypi.org/project/debug-agent-py/)
|
|
4
|
-

|
|
5
|
+

|
|
6
6
|
|
|
7
|
-
An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **
|
|
7
|
+
An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **68 diagnostic tools across 24 inspectors**.
|
|
8
8
|
|
|
9
9
|
## Quick Start
|
|
10
10
|
|
|
@@ -48,11 +48,11 @@ http://localhost:8000/agent
|
|
|
48
48
|
- **Context compression** — automatically summarizes old conversation when token limit is approached
|
|
49
49
|
- **Dark-themed chat UI** with full markdown rendering (tables, code blocks, lists)
|
|
50
50
|
- **Max tool rounds** (25) with forced final summary when limit is reached
|
|
51
|
-
- **
|
|
51
|
+
- **68 diagnostic tools** across **24 inspectors**
|
|
52
52
|
- Works with Flask, FastAPI, and Django
|
|
53
53
|
- Zero external dependencies (no Datadog, no Grafana, no APM)
|
|
54
54
|
|
|
55
|
-
## Inspectors & Tools (
|
|
55
|
+
## Inspectors & Tools (68)
|
|
56
56
|
|
|
57
57
|
### Memory Inspector
|
|
58
58
|
| Tool | Description |
|
|
@@ -169,6 +169,50 @@ http://localhost:8000/agent
|
|
|
169
169
|
| `get_wsgi_info` | WSGI server details (Gunicorn/uWSGI workers, config) |
|
|
170
170
|
| `get_asgi_apps` | List ASGI application scope and middleware chain |
|
|
171
171
|
|
|
172
|
+
### Logging Inspector
|
|
173
|
+
| Tool | Description |
|
|
174
|
+
|------|-------------|
|
|
175
|
+
| `get_logging_tree` | Python logging module logger hierarchy and levels |
|
|
176
|
+
| `get_recent_logs` | Recent log entries from the built-in ring buffer |
|
|
177
|
+
| `get_logging_config` | Current logging configuration (handlers, formatters, levels) |
|
|
178
|
+
| `set_log_level` | Dynamically set the log level for a named logger |
|
|
179
|
+
|
|
180
|
+
### Cache Inspector
|
|
181
|
+
| Tool | Description |
|
|
182
|
+
|------|-------------|
|
|
183
|
+
| `get_cache_info` | Stats for registered caches (hit rate, miss count, key count) |
|
|
184
|
+
| `get_cache_keys` | List keys from a registered cache with optional prefix filter |
|
|
185
|
+
| `clear_cache` | Clear all entries from a registered cache |
|
|
186
|
+
|
|
187
|
+
### Outbound HTTP Inspector
|
|
188
|
+
| Tool | Description |
|
|
189
|
+
|------|-------------|
|
|
190
|
+
| `get_http_pool_stats` | HTTP client connection pool stats (connections, keepalive, timeouts) |
|
|
191
|
+
| `get_outbound_summary` | Aggregated outbound HTTP call stats (total, avg latency, error rate) |
|
|
192
|
+
|
|
193
|
+
### File Descriptor Inspector
|
|
194
|
+
| Tool | Description |
|
|
195
|
+
|------|-------------|
|
|
196
|
+
| `get_fd_count` | Current number of open file descriptors |
|
|
197
|
+
| `get_fd_limit` | File descriptor soft and hard limits (RLIMIT_NOFILE) |
|
|
198
|
+
| `get_fd_list` | List open file descriptors with type and details |
|
|
199
|
+
|
|
200
|
+
### Metrics Inspector
|
|
201
|
+
| Tool | Description |
|
|
202
|
+
|------|-------------|
|
|
203
|
+
| `get_registered_metrics` | List all registered metrics from prometheus_client |
|
|
204
|
+
| `get_metric_value` | Get current value of a specific metric by name |
|
|
205
|
+
|
|
206
|
+
### FastAPI Inspector
|
|
207
|
+
| Tool | Description |
|
|
208
|
+
|------|-------------|
|
|
209
|
+
| `get_fastapi_openapi` | List FastAPI routes, schemas, and OpenAPI spec details |
|
|
210
|
+
|
|
211
|
+
### Warnings Inspector
|
|
212
|
+
| Tool | Description |
|
|
213
|
+
|------|-------------|
|
|
214
|
+
| `get_warnings` | List captured Python warnings with category, message, and location |
|
|
215
|
+
|
|
172
216
|
## Custom Tools
|
|
173
217
|
|
|
174
218
|
```python
|
|
@@ -2,18 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
from debug_agent.inspectors import ( # noqa: F401
|
|
4
4
|
async_tasks,
|
|
5
|
+
cache_inspector,
|
|
5
6
|
celery,
|
|
6
7
|
database,
|
|
7
8
|
django,
|
|
9
|
+
error_tracking,
|
|
10
|
+
fastapi_ext,
|
|
11
|
+
fd_inspector,
|
|
8
12
|
flask_ext,
|
|
9
13
|
framework,
|
|
14
|
+
health_inspector,
|
|
15
|
+
http_client_inspector,
|
|
10
16
|
http_tracker,
|
|
11
17
|
jinja2,
|
|
18
|
+
logging_inspector,
|
|
12
19
|
memory,
|
|
20
|
+
metrics_inspector,
|
|
13
21
|
modules,
|
|
14
22
|
redis,
|
|
15
23
|
runtime,
|
|
24
|
+
scheduler_inspector,
|
|
25
|
+
security_inspector,
|
|
16
26
|
signals,
|
|
17
27
|
system,
|
|
18
28
|
threads,
|
|
29
|
+
warnings_inspector,
|
|
30
|
+
websocket_inspector,
|
|
19
31
|
)
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Cache inspector: stats and management for registered caches.
|
|
2
|
+
|
|
3
|
+
Register a cache at runtime so the inspector can reach it:
|
|
4
|
+
|
|
5
|
+
from debug_agent.inspectors.cache_inspector import register_cache
|
|
6
|
+
register_cache("my_cache", my_cache_obj)
|
|
7
|
+
|
|
8
|
+
Supports functools.lru_cache, cachetools caches, Django cache backends,
|
|
9
|
+
and custom cache objects.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from debug_agent.tool_registry import debug_tool, ToolParam
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# ─── Registration ────────────────────────────────────────────────────────────
|
|
20
|
+
|
|
21
|
+
_registered_caches: dict[str, Any] = {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def register_cache(name: str, cache_obj: Any) -> None:
|
|
25
|
+
"""Register a cache object under a name so the inspectors can find it."""
|
|
26
|
+
_registered_caches[name] = cache_obj
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# ─── Cache type detection ────────────────────────────────────────────────────
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _detect_type(cache_obj: Any) -> str:
|
|
33
|
+
"""Return a label describing the cache implementation."""
|
|
34
|
+
# functools.lru_cache / functools.cache wrappers expose cache_info()
|
|
35
|
+
if hasattr(cache_obj, "cache_info") and hasattr(cache_obj, "cache_clear"):
|
|
36
|
+
return "lru_cache"
|
|
37
|
+
|
|
38
|
+
# cachetools caches have __contains__ and __len__
|
|
39
|
+
cls_name = type(cache_obj).__module__ + "." + type(cache_obj).__qualname__
|
|
40
|
+
if "cachetools" in type(cache_obj).__module__:
|
|
41
|
+
return "cachetools"
|
|
42
|
+
|
|
43
|
+
# Django cache backends expose _cache attribute
|
|
44
|
+
if hasattr(cache_obj, "_cache"):
|
|
45
|
+
return "django"
|
|
46
|
+
|
|
47
|
+
# Generic mapping-like caches
|
|
48
|
+
if hasattr(cache_obj, "__contains__") and hasattr(cache_obj, "__len__"):
|
|
49
|
+
return "mapping"
|
|
50
|
+
|
|
51
|
+
# Custom caches with stats()/info() methods
|
|
52
|
+
if hasattr(cache_obj, "stats") or hasattr(cache_obj, "info"):
|
|
53
|
+
return "custom"
|
|
54
|
+
|
|
55
|
+
return "unknown"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ─── Tools ───────────────────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@debug_tool(
|
|
62
|
+
"get_cache_info",
|
|
63
|
+
"Get stats for registered caches (lru_cache, cachetools, django, custom)",
|
|
64
|
+
)
|
|
65
|
+
def get_cache_info(
|
|
66
|
+
name: str = ToolParam("Cache name (omit for all registered caches)", required=False),
|
|
67
|
+
) -> dict:
|
|
68
|
+
if name:
|
|
69
|
+
cache_obj = _registered_caches.get(name)
|
|
70
|
+
if cache_obj is None:
|
|
71
|
+
return {"error": f"No cache registered with name '{name}'"}
|
|
72
|
+
return _inspect_cache(name, cache_obj)
|
|
73
|
+
|
|
74
|
+
if not _registered_caches:
|
|
75
|
+
return {
|
|
76
|
+
"message": "No caches registered. Call register_cache(name, cache_obj) to register one.",
|
|
77
|
+
"registered_count": 0,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
result = []
|
|
81
|
+
for cache_name, cache_obj in _registered_caches.items():
|
|
82
|
+
try:
|
|
83
|
+
result.append(_inspect_cache(cache_name, cache_obj))
|
|
84
|
+
except Exception as exc:
|
|
85
|
+
result.append({"name": cache_name, "error": str(exc)})
|
|
86
|
+
|
|
87
|
+
return {"registered_count": len(result), "caches": result}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _inspect_cache(name: str, cache_obj: Any) -> dict[str, Any]:
|
|
91
|
+
cache_type = _detect_type(cache_obj)
|
|
92
|
+
info: dict[str, Any] = {"name": name, "type": cache_type}
|
|
93
|
+
|
|
94
|
+
# functools.lru_cache
|
|
95
|
+
if cache_type == "lru_cache":
|
|
96
|
+
try:
|
|
97
|
+
ci = cache_obj.cache_info()
|
|
98
|
+
info.update(
|
|
99
|
+
{
|
|
100
|
+
"hits": getattr(ci, "hits", None),
|
|
101
|
+
"misses": getattr(ci, "misses", None),
|
|
102
|
+
"maxsize": getattr(ci, "maxsize", None),
|
|
103
|
+
"current_size": getattr(ci, "currsize", None),
|
|
104
|
+
}
|
|
105
|
+
)
|
|
106
|
+
return info
|
|
107
|
+
except Exception as exc:
|
|
108
|
+
info["error"] = str(exc)
|
|
109
|
+
return info
|
|
110
|
+
|
|
111
|
+
# cachetools / generic mapping
|
|
112
|
+
if cache_type in ("cachetools", "mapping"):
|
|
113
|
+
try:
|
|
114
|
+
info["size"] = len(cache_obj)
|
|
115
|
+
except Exception:
|
|
116
|
+
info["size"] = None
|
|
117
|
+
info["maxsize"] = getattr(cache_obj, "maxsize", None)
|
|
118
|
+
return info
|
|
119
|
+
|
|
120
|
+
# django cache
|
|
121
|
+
if cache_type == "django":
|
|
122
|
+
try:
|
|
123
|
+
inner = getattr(cache_obj, "_cache", None)
|
|
124
|
+
if inner is not None and hasattr(inner, "__len__"):
|
|
125
|
+
info["size"] = len(inner)
|
|
126
|
+
else:
|
|
127
|
+
info["size"] = None
|
|
128
|
+
except Exception:
|
|
129
|
+
info["size"] = None
|
|
130
|
+
info["backend"] = type(cache_obj).__name__
|
|
131
|
+
return info
|
|
132
|
+
|
|
133
|
+
# custom: try stats(), info(), size
|
|
134
|
+
if cache_type == "custom":
|
|
135
|
+
for method in ("stats", "info"):
|
|
136
|
+
if hasattr(cache_obj, method):
|
|
137
|
+
try:
|
|
138
|
+
val = getattr(cache_obj, method)()
|
|
139
|
+
if isinstance(val, dict):
|
|
140
|
+
info.update(val)
|
|
141
|
+
else:
|
|
142
|
+
info[method] = val
|
|
143
|
+
except Exception:
|
|
144
|
+
pass
|
|
145
|
+
size = getattr(cache_obj, "size", None)
|
|
146
|
+
if size is not None:
|
|
147
|
+
info["size"] = size() if callable(size) else size
|
|
148
|
+
return info
|
|
149
|
+
|
|
150
|
+
return info
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@debug_tool(
|
|
154
|
+
"get_cache_keys",
|
|
155
|
+
"List keys in a registered cache with optional prefix filter",
|
|
156
|
+
)
|
|
157
|
+
def get_cache_keys(
|
|
158
|
+
name: str = ToolParam("Cache name"),
|
|
159
|
+
prefix: str = ToolParam("Optional key prefix to filter by", required=False),
|
|
160
|
+
) -> dict:
|
|
161
|
+
cache_obj = _registered_caches.get(name)
|
|
162
|
+
if cache_obj is None:
|
|
163
|
+
return {"error": f"No cache registered with name '{name}'"}
|
|
164
|
+
|
|
165
|
+
cache_type = _detect_type(cache_obj)
|
|
166
|
+
keys: list[Any] = []
|
|
167
|
+
|
|
168
|
+
try:
|
|
169
|
+
if cache_type == "lru_cache":
|
|
170
|
+
return {
|
|
171
|
+
"name": name,
|
|
172
|
+
"type": cache_type,
|
|
173
|
+
"message": "lru_cache does not expose its keys",
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
# Django locmem / cachetools / generic mapping
|
|
177
|
+
inner = cache_obj
|
|
178
|
+
if cache_type == "django":
|
|
179
|
+
inner = getattr(cache_obj, "_cache", cache_obj)
|
|
180
|
+
|
|
181
|
+
if hasattr(inner, "keys"):
|
|
182
|
+
keys = list(inner.keys())
|
|
183
|
+
elif hasattr(inner, "__iter__"):
|
|
184
|
+
keys = [k for k in inner]
|
|
185
|
+
except Exception as exc:
|
|
186
|
+
return {"error": f"Could not enumerate keys: {exc}"}
|
|
187
|
+
|
|
188
|
+
if prefix:
|
|
189
|
+
keys = [k for k in keys if str(k).startswith(prefix)]
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
"name": name,
|
|
193
|
+
"type": cache_type,
|
|
194
|
+
"total": len(keys),
|
|
195
|
+
"keys": keys[:500], # cap to avoid huge responses
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@debug_tool(
|
|
200
|
+
"clear_cache",
|
|
201
|
+
"Clear a registered cache (lru_cache: cache_clear, cachetools/django: clear)",
|
|
202
|
+
)
|
|
203
|
+
def clear_cache(
|
|
204
|
+
name: str = ToolParam("Cache name"),
|
|
205
|
+
) -> dict:
|
|
206
|
+
cache_obj = _registered_caches.get(name)
|
|
207
|
+
if cache_obj is None:
|
|
208
|
+
return {"error": f"No cache registered with name '{name}'"}
|
|
209
|
+
|
|
210
|
+
cache_type = _detect_type(cache_obj)
|
|
211
|
+
|
|
212
|
+
try:
|
|
213
|
+
if cache_type == "lru_cache":
|
|
214
|
+
cache_obj.cache_clear()
|
|
215
|
+
elif hasattr(cache_obj, "clear"):
|
|
216
|
+
cache_obj.clear()
|
|
217
|
+
else:
|
|
218
|
+
return {
|
|
219
|
+
"error": f"Cache '{name}' (type: {cache_type}) does not support clearing",
|
|
220
|
+
}
|
|
221
|
+
except Exception as exc:
|
|
222
|
+
return {"error": f"Failed to clear cache '{name}': {exc}"}
|
|
223
|
+
|
|
224
|
+
return {"name": name, "type": cache_type, "cleared": True}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Error tracking inspector: capture and analyse unhandled exceptions.
|
|
2
|
+
|
|
3
|
+
Installs a global ``sys.excepthook`` and provides helpers to hook into
|
|
4
|
+
Flask / WSGI for request-scoped errors. A ring buffer (max 50) keeps the
|
|
5
|
+
most recent exceptions for inspection.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import traceback as tb_mod
|
|
15
|
+
from collections import Counter, deque
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from debug_agent.tool_registry import debug_tool, ToolParam
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# ─── Ring buffer & state ──────────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
_MAX_BUFFER = 50
|
|
25
|
+
_error_buffer: deque = deque(maxlen=_MAX_BUFFER)
|
|
26
|
+
_buffer_lock = threading.Lock()
|
|
27
|
+
_original_excepthook = sys.excepthook
|
|
28
|
+
_installed = False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ─── Capture helpers ──────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def capture_error(
|
|
35
|
+
exc_type: type,
|
|
36
|
+
value: BaseException,
|
|
37
|
+
tb: Any,
|
|
38
|
+
request_path: str | None = None,
|
|
39
|
+
) -> None:
|
|
40
|
+
"""Append an exception to the ring buffer."""
|
|
41
|
+
entry = {
|
|
42
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
43
|
+
"epoch": time.time(),
|
|
44
|
+
"type": exc_type.__name__ if exc_type else "Unknown",
|
|
45
|
+
"message": str(value),
|
|
46
|
+
"traceback": "".join(tb_mod.format_exception(exc_type, value, tb)),
|
|
47
|
+
"request_path": request_path,
|
|
48
|
+
}
|
|
49
|
+
with _buffer_lock:
|
|
50
|
+
_error_buffer.append(entry)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _excepthook(exc_type, value, tb): # noqa: A002 (tb shadows stdlib name)
|
|
54
|
+
"""Replacement sys.excepthook that records the exception before delegating."""
|
|
55
|
+
capture_error(exc_type, value, tb)
|
|
56
|
+
_original_excepthook(exc_type, value, tb)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def install_error_hooks() -> None:
|
|
60
|
+
"""Install the global ``sys.excepthook`` override (idempotent)."""
|
|
61
|
+
global _installed
|
|
62
|
+
if _installed:
|
|
63
|
+
return
|
|
64
|
+
sys.excepthook = _excepthook
|
|
65
|
+
_installed = True
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def install_flask_error_handler(app: Any) -> None:
|
|
69
|
+
"""Register a catch-all Flask error handler that records exceptions."""
|
|
70
|
+
try:
|
|
71
|
+
from flask import request, jsonify # type: ignore
|
|
72
|
+
except ImportError:
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
@app.errorhandler(Exception)
|
|
76
|
+
def _capture_flask_error(e): # noqa: ANN202
|
|
77
|
+
capture_error(
|
|
78
|
+
type(e), e, e.__traceback__,
|
|
79
|
+
request_path=request.path if request else None,
|
|
80
|
+
)
|
|
81
|
+
# Re-raise so existing handlers / Flask defaults still apply
|
|
82
|
+
try:
|
|
83
|
+
return app.handle_exception(e)
|
|
84
|
+
except Exception:
|
|
85
|
+
return jsonify({"error": type(e).__name__, "message": str(e)}), 500
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def install_wsgi_middleware(app: Any) -> Any:
|
|
89
|
+
"""Wrap a WSGI app so unhandled exceptions are captured."""
|
|
90
|
+
|
|
91
|
+
def middleware(environ, start_response):
|
|
92
|
+
try:
|
|
93
|
+
return app(environ, start_response)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
capture_error(
|
|
96
|
+
type(exc), exc, exc.__traceback__,
|
|
97
|
+
request_path=environ.get("PATH_INFO"),
|
|
98
|
+
)
|
|
99
|
+
raise
|
|
100
|
+
|
|
101
|
+
return middleware
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# Auto-install the global excepthook on import
|
|
105
|
+
install_error_hooks()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ─── Tools ────────────────────────────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _get_all() -> list[dict]:
|
|
112
|
+
with _buffer_lock:
|
|
113
|
+
return list(_error_buffer)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@debug_tool(
|
|
117
|
+
"get_recent_errors",
|
|
118
|
+
"Get recent unhandled exceptions from the in-memory ring buffer (max 50)",
|
|
119
|
+
)
|
|
120
|
+
def get_recent_errors(
|
|
121
|
+
limit: int = ToolParam("Max results to return", required=False),
|
|
122
|
+
) -> dict:
|
|
123
|
+
errors = _get_all()
|
|
124
|
+
if limit:
|
|
125
|
+
errors = errors[-limit:]
|
|
126
|
+
return {
|
|
127
|
+
"total_captured": len(_error_buffer),
|
|
128
|
+
"buffer_max": _MAX_BUFFER,
|
|
129
|
+
"errors": list(reversed(errors)),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@debug_tool(
|
|
134
|
+
"get_error_stats",
|
|
135
|
+
"Get error statistics: total, rate per minute, top error types",
|
|
136
|
+
)
|
|
137
|
+
def get_error_stats() -> dict:
|
|
138
|
+
errors = _get_all()
|
|
139
|
+
if not errors:
|
|
140
|
+
return {"total": 0, "message": "No errors captured yet"}
|
|
141
|
+
|
|
142
|
+
now = time.time()
|
|
143
|
+
oldest = min(e["epoch"] for e in errors)
|
|
144
|
+
elapsed_minutes = max((now - oldest) / 60, 1 / 60) # avoid div-by-zero
|
|
145
|
+
|
|
146
|
+
type_counts = Counter(e["type"] for e in errors)
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
"total": len(errors),
|
|
150
|
+
"buffer_max": _MAX_BUFFER,
|
|
151
|
+
"rate_per_minute": round(len(errors) / elapsed_minutes, 2),
|
|
152
|
+
"time_window_minutes": round(elapsed_minutes, 1),
|
|
153
|
+
"top_error_types": type_counts.most_common(10),
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@debug_tool(
|
|
158
|
+
"get_error_patterns",
|
|
159
|
+
"Group similar errors by exception type and message pattern",
|
|
160
|
+
)
|
|
161
|
+
def get_error_patterns() -> dict:
|
|
162
|
+
errors = _get_all()
|
|
163
|
+
if not errors:
|
|
164
|
+
return {"patterns": [], "message": "No errors captured yet"}
|
|
165
|
+
|
|
166
|
+
def _normalise_message(msg: str) -> str:
|
|
167
|
+
"""Collapse variable parts of an error message for grouping."""
|
|
168
|
+
import re
|
|
169
|
+
# Replace IDs, numbers, hex, file paths, and quoted strings
|
|
170
|
+
msg = re.sub(r"\b[0-9a-f]{8,}\b", "<hex>", msg, flags=re.IGNORECASE)
|
|
171
|
+
msg = re.sub(r"\b\d+\b", "<N>", msg)
|
|
172
|
+
msg = re.sub(r"/[/^\s]+", "<path>", msg)
|
|
173
|
+
msg = re.sub(r"'[^']*'", "'<str>'", msg)
|
|
174
|
+
msg = re.sub(r'"[^"]*"', '"<str>"', msg)
|
|
175
|
+
return msg[:200]
|
|
176
|
+
|
|
177
|
+
groups: dict[str, dict[str, Any]] = {}
|
|
178
|
+
for err in errors:
|
|
179
|
+
pattern_key = f"{err['type']}: {_normalise_message(err['message'])}"
|
|
180
|
+
if pattern_key not in groups:
|
|
181
|
+
groups[pattern_key] = {
|
|
182
|
+
"pattern": pattern_key,
|
|
183
|
+
"count": 0,
|
|
184
|
+
"type": err["type"],
|
|
185
|
+
"example_message": err["message"],
|
|
186
|
+
"first_seen": err["timestamp"],
|
|
187
|
+
"last_seen": err["timestamp"],
|
|
188
|
+
"request_paths": set(),
|
|
189
|
+
}
|
|
190
|
+
g = groups[pattern_key]
|
|
191
|
+
g["count"] += 1
|
|
192
|
+
g["last_seen"] = err["timestamp"]
|
|
193
|
+
if err.get("request_path"):
|
|
194
|
+
g["request_paths"].add(err["request_path"])
|
|
195
|
+
|
|
196
|
+
# Sort by count desc and convert sets to lists
|
|
197
|
+
sorted_groups = sorted(groups.values(), key=lambda x: -x["count"])
|
|
198
|
+
for g in sorted_groups:
|
|
199
|
+
g["request_paths"] = sorted(g["request_paths"])
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
"pattern_count": len(sorted_groups),
|
|
203
|
+
"total_errors": len(errors),
|
|
204
|
+
"patterns": sorted_groups,
|
|
205
|
+
}
|