> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Clearing

> Clear sandbox execution result cache to free memory and reset cache statistics in HopX sandboxes. Remove cached execution results to free resources, force re-execution of code, or reset cache performance metrics. Essential for memory management and debugging. Includes Python and JavaScript SDK examples and REST API endpoints.

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

<Warning>
  Clearing the cache will remove all cached execution results. Subsequent executions will be cache misses until new entries are created.
</Warning>

## Clearing Cache

Clear all cached execution results:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    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();
    ```
  </Tab>
</Tabs>

## Cache Clear Response

The cache clear operation returns a confirmation:

```json theme={null}
{
  "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:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    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();
    ```
  </Tab>
</Tabs>

### Resetting for Testing

Clear cache before running tests to ensure fresh executions:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    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();
    ```
  </Tab>
</Tabs>

### Periodic Cache Maintenance

Clear cache periodically to prevent unbounded growth:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    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();
    ```
  </Tab>
</Tabs>

## Best Practices

<Tip>
  **Monitor cache size** before clearing. Only clear when necessary to avoid losing beneficial cached results.
</Tip>

<Tip>
  **Clear cache before testing** to ensure code changes are properly tested without cache interference.
</Tip>

<Warning>
  **Clearing cache affects performance**. After clearing, all executions will be cache misses until new entries are created.
</Warning>

<Tip>
  **Set up periodic cache maintenance** if you have long-running sandboxes with many executions.
</Tip>

## 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

## Related

* **[Cache Statistics](/core-concepts/cache/statistics)** - Monitor cache performance
* **SDK**: [sandbox.cache.clear()](/sdk/python/cache#clear) - Python SDK method
* **API**: [POST /cache/clear](/api/vm-agent/clear-cache) - VM Agent API endpoint

## Next Steps

* Learn about [Cache Statistics](/core-concepts/cache/statistics) to monitor cache

* Review [Code Execution](/core-concepts/code-execution/synchronous) for execution results

* [Cache Statistics](/core-concepts/cache/statistics) - Monitor cache performance

* **[CLI System Commands](/cli/commands/system)** - View cache statistics from CLI
