---
name: memray-profiling
user-invocable: false
disable-model-invocation: true
description: >-
  Activated when the user mentions "memray", "memory profiling", "memory leaks",
  "peak memory usage", "high watermark", "pytest --memray", "@pytest.mark.limit_memory",
  "memory budgets in CI", "flamegraphs for memory", "memory allocation tracking", "tracemalloc",
  or wants to analyze or reduce memory consumption of Python code.
allowed-tools: ["Bash", "Read", "Write", "Grep", "Glob"]
---

# Memray Memory Profiling — Quick Reference

Full details: `../references/memory/guide.md`

## Critical Rules (always apply)

1. **`PYTHONMALLOC=malloc`** — Always set when profiling. Without it, pymalloc hides small allocations (<512 bytes) inside arenas.
2. **`--native`** — Always use for investigation. Without it, C extension allocations are opaque.
3. **Compare like-for-like** — Never compare `--native` vs non-native captures, or `PYTHONMALLOC=malloc` vs pymalloc captures.

```bash
PYTHONMALLOC=malloc memray run --native -o /tmp/profile.bin my_script.py
```

## Per-Test vs Process-Wide

| Tool | Measures | Includes imports? |
|------|----------|-------------------|
| `pytest --memray` | Test function body only | NO |
| `memray run` | Entire process | YES |

Import-time optimizations are invisible to `pytest --memray`.

## Leak Detection

- **CLI**: `memray stats --leaks /tmp/capture.bin` (unfreed at exit, not peak)
- **Programmatic**: `FileReader.get_leaked_allocation_records()` (NOT `get_high_watermark_allocation_records()`)
- **Leak ratio**: `leaked_total / peak_total` — near 100% = true leak, low = just caches

## Common Traps

- **`@functools.cache` on instance methods** — captures `self` as key, instance lives forever
- **Variables retain memory until function returns** — all intermediates coexist at peak; use `del` or break into subfunctions
- **`memray tree` / `memray live`** — interactive TUIs, never use in automated contexts
- **Only one Tracker per process** — cannot nest context managers
- **Heap != RSS** — memray tracks malloc/free only, not mmap'd files or shared memory

## Reference Files

- `../references/memory/guide.md` — Full memray guide, tracemalloc, leak detection, FileReader, framework leaks
- `../references/memory/cli-reference.md` — All CLI commands and flags
- `../references/memory/pytest-memray.md` — pytest markers, CI setup, gotchas
- `../references/memory/python-api.md` — Tracker, FileReader API
- `../references/memory/reference.md` — Memory optimization patterns and techniques
- `../references/memory/experiment-loop.md` — Memory domain experiment loop (used by codeflash-memory agent)
- `../references/memory/handoff-template.md` — Handoff template (used by codeflash-memory agent)
