Clear the execution result cache to free memory, reset cache statistics, and ensure fresh executions for testing or debugging.
Overview
Clearing the cache is useful when:
- Cache has grown too large and you need to free memory
- You want to reset cache statistics
- Testing code changes that should bypass cache
- Debugging cache-related issues
- Starting fresh after code modifications
Clearing the cache will remove all cached execution results. Subsequent executions will be cache misses until new entries are created.
Clearing Cache
Clear all cached execution results:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Get cache stats before clearing
before = sandbox.cache.stats()
before_cache = before['cache']
print(f"Before clearing: Size={before_cache['size']}, Hits={before_cache['total_hits']}")
# Clear the cache
result = sandbox.cache.clear()
print(f"Result: {result['message']}")
# Get cache stats after clearing
after = sandbox.cache.stats()
after_cache = after['cache']
print(f"After clearing: Size={after_cache['size']}, Hits={after_cache['total_hits']}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({
template: 'code-interpreter'
});
// Get cache stats before clearing
const before = await sandbox.cache.stats();
const beforeCache = before.cache;
console.log(`Before clearing: Size=${beforeCache.size}, Hits=${beforeCache.total_hits}`);
// Clear the cache
const result = await sandbox.cache.clear();
console.log(`Result: ${result.message}`);
// Get cache stats after clearing
const after = await sandbox.cache.stats();
const afterCache = after.cache;
console.log(`After clearing: Size=${afterCache.size}, Hits=${afterCache.total_hits}`);
await sandbox.kill();
Cache Clear Response
The cache clear operation returns a confirmation:
{
"message": "Cache cleared successfully",
"timestamp": "2025-01-27T19:49:28Z"
}
Field Descriptions
message: Confirmation message
timestamp: Timestamp when the cache was cleared
Use Cases
Freeing Memory
Clear cache when it consumes too much memory:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Check cache size
stats = sandbox.cache.stats()
cache_data = stats['cache']
cache_size = cache_data['size']
max_size = cache_data['max_size']
# Clear if cache is too large (80% of max)
CACHE_SIZE_THRESHOLD = max_size * 0.8
if cache_size > CACHE_SIZE_THRESHOLD:
print(f"Cache size ({cache_size}) exceeds threshold ({CACHE_SIZE_THRESHOLD})")
result = sandbox.cache.clear()
print(f"Cache cleared: {result['message']}")
else:
print(f"Cache size ({cache_size}) is within acceptable range")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({
template: 'code-interpreter'
});
// Check cache size
const stats = await sandbox.cache.stats();
const cacheData = stats.cache;
const cacheSize = cacheData.size;
const maxSize = cacheData.max_size;
// Clear if cache is too large (80% of max)
const CACHE_SIZE_THRESHOLD = maxSize * 0.8;
if (cacheSize > CACHE_SIZE_THRESHOLD) {
console.log(`Cache size (${cacheSize}) exceeds threshold (${CACHE_SIZE_THRESHOLD})`);
const result = await sandbox.cache.clear();
console.log(`Cache cleared: ${result.message}`);
} else {
console.log(`Cache size (${cacheSize}) is within acceptable range`);
}
await sandbox.kill();
Resetting for Testing
Clear cache before running tests to ensure fresh executions:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Clear cache before testing
print("Clearing cache for fresh test execution...")
sandbox.cache.clear()
# Run test code (will be cache miss)
result = sandbox.run_code("""
import time
start = time.time()
# Simulate some computation
sum(range(100000))
end = time.time()
print(f"Execution time: {end - start:.3f}s")
""")
print("Test completed with fresh execution")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({
template: 'code-interpreter'
});
// Clear cache before testing
console.log('Clearing cache for fresh test execution...');
await sandbox.cache.clear();
// Run test code (will be cache miss)
const result = await sandbox.runCode(`
import time
start = time.time()
# Simulate some computation
sum(range(100000))
end = time.time()
print(f"Execution time: {end - start:.3f}s")
`);
console.log('Test completed with fresh execution');
await sandbox.kill();
Periodic Cache Maintenance
Clear cache periodically to prevent unbounded growth:
from hopx_ai import Sandbox
import time
sandbox = Sandbox.create(template="code-interpreter")
# Run some code to generate cache entries
for i in range(20):
sandbox.run_code(f"print('Execution {i}')")
time.sleep(0.1)
# Check cache stats
stats = sandbox.cache.stats()
cache_data = stats['cache']
print(f"Cache size: {cache_data['size']}")
print(f"Cache hits: {cache_data['total_hits']}")
# Clear cache periodically (e.g., if size > 80% of max)
if cache_data['size'] > cache_data['max_size'] * 0.8:
print("Clearing cache due to high size...")
result = sandbox.cache.clear()
print(f"Cleared: {result['message']}")
# Verify cache is cleared
after_stats = sandbox.cache.stats()
after_cache = after_stats['cache']
print(f"Cache size after clear: {after_cache['size']}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({
template: 'code-interpreter'
});
// Run some code to generate cache entries
for (let i = 0; i < 20; i++) {
await sandbox.runCode(`print('Execution ${i}')`);
await new Promise(resolve => setTimeout(resolve, 100));
}
// Check cache stats
const stats = await sandbox.cache.stats();
const cacheData = stats.cache;
console.log(`Cache size: ${cacheData.size}`);
console.log(`Cache hits: ${cacheData.total_hits}`);
// Clear cache periodically (e.g., if size > 80% of max)
if (cacheData.size > cacheData.max_size * 0.8) {
console.log('Clearing cache due to high size...');
const result = await sandbox.cache.clear();
console.log(`Cleared: ${result.message}`);
// Verify cache is cleared
const afterStats = await sandbox.cache.stats();
const afterCache = afterStats.cache;
console.log(`Cache size after clear: ${afterCache.size}`);
}
await sandbox.kill();
Best Practices
Monitor cache size before clearing. Only clear when necessary to avoid losing beneficial cached results.
Clear cache before testing to ensure code changes are properly tested without cache interference.
Clearing cache affects performance. After clearing, all executions will be cache misses until new entries are created.
Set up periodic cache maintenance if you have long-running sandboxes with many executions.
API Reference
Python SDK
sandbox.cache.clear(*, timeout=None) - Clear execution cache
JavaScript SDK
sandbox.cache.clear() - Clear execution cache
API Endpoint
- POST
/cache/clear - Clear execution result cache
Next Steps