Socratic Performance
Performance monitoring and caching utilities for AI systems.
Features
- QueryProfiler: Database query profiling and performance monitoring with support for sync and async functions
- TTLCache: Time-based function result caching decorator with thread-safe cache management
- Performance Analytics: Track slow queries, get performance summaries, and analyze bottlenecks
- Cache Statistics: Monitor cache hits, misses, and hit rates
Installation
pip install socratic-performance
Quick Start
Query Profiling
Track database query performance with automatic slow query detection:
from socratic_performance import QueryProfiler
profiler = QueryProfiler(slow_query_threshold_ms=100)
@profiler.profile("get_user")
async def load_user(user_id: str):
# Your async database query here
return await db.get(User, user_id)
# Execute the function
user = await load_user("user_123")
# Get statistics
stats = profiler.get_stats()
print(f"get_user avg time: {stats['get_user']['avg_time_ms']:.2f}ms")
# Get slowest queries
slowest = profiler.get_slowest_queries(limit=5)
for query in slowest:
print(f"{query['name']}: {query['avg_time_ms']:.1f}ms")
TTL Caching
Cache expensive function results with automatic expiration:
from socratic_performance import cached
@cached(ttl_minutes=5)
def expensive_computation(project_id: str) -> dict:
# Simulate expensive operation
return analyze_project(project_id)
result1 = expensive_computation("proj_123") # Computed (slow)
result2 = expensive_computation("proj_123") # Cached (fast)
# Check cache statistics
stats = expensive_computation.cache_stats()
print(f"Cache hit rate: {stats['hit_rate']}")
API Reference
QueryProfiler
Initialization
profiler = QueryProfiler(slow_query_threshold_ms=100.0)
Parameters:
slow_query_threshold_ms(float): Threshold above which queries are considered slow (default: 100ms)
Decorator Usage
@profiler.profile("query_name")
async def my_query():
pass
@profiler.profile("custom_threshold", slow_query_threshold_ms=50)
def fast_query():
pass
Manual Tracking
start = time.time()
try:
result = perform_operation()
duration = time.time() - start
profiler.manual_track("operation", duration)
except Exception:
duration = time.time() - start
profiler.manual_track("operation", duration, error=True)
raise
Statistics Methods
# Get all statistics
stats = profiler.get_stats()
# Get slow queries (with slow executions)
slow_queries = profiler.get_slow_queries(min_slow_count=1)
# Get slowest queries (by average time)
slowest = profiler.get_slowest_queries(limit=10)
# Print summary
profiler.print_summary(limit=5)
# Reset statistics
profiler.reset_stats() # Reset all
profiler.reset_stats("specific_query") # Reset one
TTLCache
Decorator Usage
cache = TTLCache(ttl_minutes=5)
@cache
def expensive_operation(x, y):
return x + y
Factory Function
from socratic_performance import cached
@cached(ttl_minutes=10)
def my_function(param):
return expensive_operation(param)
Cache Management
# Clear cache
my_function.cache_clear()
# Get statistics
stats = my_function.cache_stats()
# Returns: {'hits': 5, 'misses': 3, 'total_calls': 8, 'hit_rate': '62.5%', ...}
# Get human-readable info
info = my_function.cache_info()
# Returns: "Cache: 3 entries, 62.5% hit rate, TTL: 10 minutes"
TTLCache Methods
cache = TTLCache(ttl_minutes=5)
# Clean up expired entries
removed_count = cache.cleanup_expired()
# Reset statistics only (keep cache)
cache.reset_stats()
# Clear all cache
cache.clear()
Examples
See the examples/ directory for complete examples:
- 01_query_profiling.py - Query profiling with decorators, manual tracking, async functions
- 02_ttl_cache.py - TTL cache usage, multiple functions, kwargs handling
Run examples:
python examples/01_query_profiling.py
python examples/02_ttl_cache.py
Global Profiler
Access a global profiler instance without managing your own:
from socratic_performance import get_profiler, profile_query
@profile_query("operation_name")
async def my_operation():
pass
# Get global profiler
profiler = get_profiler()
stats = profiler.get_stats()
Best Practices
Query Profiling
- Set appropriate thresholds: Tune
slow_query_threshold_msbased on your performance requirements - Use meaningful names: Give queries descriptive names for easy identification
- Review slow queries regularly: Use
get_slow_queries()andget_slowest_queries()to identify bottlenecks - Print summaries: Use
print_summary()to log performance reports
TTL Caching
- Choose appropriate TTLs: Balance freshness vs. performance
- Monitor hit rates: Check
cache_stats()to ensure caching is effective - Handle unhashable arguments: The cache gracefully skips caching for unhashable arguments
- Clean up expired entries: Call
cleanup_expired()periodically for long-running processes
Architecture
QueryProfiler provides low-overhead query performance tracking:
- Works with both sync and async functions
- Configurable slow query thresholds
- Automatic error tracking
- Minimal performance impact
TTLCache implements thread-safe result caching:
- Automatic expiration after TTL
- Thread-safe operations using RLock
- Graceful handling of unhashable arguments
- Detailed cache statistics
License
MIT
Contributing
Contributions welcome! Please ensure tests pass and code is formatted with black.
pytest tests/
black .
Origin
This package comes from the Socrates research prototype, which is not maintained as a product. Status: alpha. Written by Efthimios Angelopoulos with AI coding assistants (Claude Code); I design, review and test it. Contact: Hermes_creative@proton.me.
Use This Package Standalone:
pip install socratic-performance
Or As Part of Socrates Platform:
pip install socrates-ai # Includes 37+ modules + all 11 packages
Integration Example:
See the Socrates ECOSYSTEM.md for detailed integration examples showing how to use socratic-performance with other Socratic packages.
Related packages you might use together:
More Information:
- ���� Full Socrates Documentation
- ������� Complete Architecture Guide
- ���� Socrates Discussions
Metadata
Release files for socratic-performance 0.2.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| socratic_performance-0.2.3.tar.gz | 23.9 kB | Without provenance | Details for socratic_performance-0.2.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| socratic_performance-0.2.3-py3-none-any.whl | Python 3 | none | any | Details for socratic_performance-0.2.3-py3-none-any.whl |
Total release size: 40.3 kB
Release files / socratic_performance-0.2.3.tar.gz
| Download URL | socratic_performance-0.2.3.tar.gz |
|---|---|
| Size | 23.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1c7236f7996d5edf7e2cd5efb89ede7d5cf2fb7de77d3cf4cead612ae17dd5a2
|
|
BLAKE2b-256 checksum How to use checksums |
bf37cef9fcd6f39cc446aec780145f95626647898765de8772b158b451ec827a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
pyupload/1 (stdlib)
|
Release files / socratic_performance-0.2.3-py3-none-any.whl
| Download URL | socratic_performance-0.2.3-py3-none-any.whl |
|---|---|
| Size | 16.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2658e6dec8b03df48e2bec0219920b10ccf529879b2014edbf0bf6b0d4549b04
|
|
BLAKE2b-256 checksum How to use checksums |
5c993f221adb12f43451db0ea7c2268e652389eaf22a329b94f12a1711d38505
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
pyupload/1 (stdlib)
|
Security for socratic-performance 0.2.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.