Heap Hunter End-User Guide
Everything you need to index, inspect, and diagnose Java heap dumps with Heap Hunter.
This guide explains how to build the hunt binary and use it with a Java .hprof heap dump.
# Installation
Heap Hunter targets Zig 0.16.0 or later. The only build-time dependency is a Zig toolchain.
git clone https://github.com/AmeyaKasture/heap_hunter.git
cd heap_hunter
zig build -Doptimize=ReleaseFast
The resulting binary is written to zig-out/bin/hunt. Optionally copy it onto $PATH:
install -m 0755 zig-out/bin/hunt /usr/local/bin/hunt
# macOS Gatekeeper Note
If you downloaded a prebuilt hunt binary (for example, hunt-aarch64-macos) on macOS, Gatekeeper may refuse to run it and report operation not permitted. This happens because downloaded executables are tagged with the com.apple.quarantine extended attribute, which the kernel enforces even for valid, ad-hoc signed Mach-O binaries.
Remove the quarantine flag:
xattr -d com.apple.quarantine /path/to/hunt
Then run the binary normally:
/path/to/hunt --help
# 1. Getting Help
# Top-level help
hunt --help
# Per-command help
hunt index --help
hunt histogram --help
hunt roots --help
hunt dominator --help
The built-in help shows usage, options, examples, and exit codes for each command.
# 2. Optional: Create a Config File
To avoid typing --index-dir every time, create ~/.config/hunt/config.json:
mkdir -p ~/.config/hunt
cat > ~/.config/hunt/config.json <<'EOF'
{
"index-dir": "/path/to/your/indexes",
"sorting-budget-mb": 4096
}
EOF
# Config behavior
| Field | Meaning |
|---|---|
index-dir | The index location. For index and overview this is a base directory: each dump gets its own subdirectory at <base>/<stem>.idx/. For query commands, either pass the dump as the positional argument (the index directory is then derived from the base) or point --index-dir at a specific index directory. |
sorting-budget-mb | RAM budget in MiB for the external-sort catalog stage (default 4096). Memory stays bounded by this value regardless of dump size. Lower it on constrained machines; the sort then spills more and runs slower, but never exceeds the budget. |
Override the config path with --config /path/to/config.json, or override just the index dir with --index-dir <dir>.
# 3. The Standard Workflow
Working with Heap Hunter has three steps: two preparation commands, then queries.
index— scan the.hprofonce and write persistent index files.overview— build a smalloverview.bincache for fast summary queries.- Query commands — read from the index/cache.
You must run index, then overview, before any query command.
# 3.1 Index the dump
hunt index path/to/heap.hprof --index-dir path/to/heap.idx
On success it prints a JSON summary:
{"status":"complete","index_dir":"path/to/heap.idx","n_objects":170877,"n_classes":1844,"n_edges":262839,"n_roots":1851,...}
If an up-to-date index already exists, it prints:
{"status":"reused","index_dir":"path/to/heap.idx"}
By default the index also computes the dominator tree and retained sizes (dom_parent.bin, dom_order.bin, and retained.bin). These power the dominator and retained-size commands in section 8. The summary JSON reports "has_dominators": true when they were computed.
| Option | Meaning |
|---|---|
--index-dir <dir> | Where to write the index |
--sorting-budget-mb <n> | RAM budget for sorting (default 4096) |
--dominator-budget-mb <n> | RAM budget for dominator computation (default 4096) |
--dominator-algorithm <algo> | Dominator backend: lt (Lengauer-Tarjan, default, single reverse-preorder pass) or chk (Cooper-Harvey-Kennedy, iterative). Both produce identical results. |
--no-dominators | Skip dominator computation. Dominator queries then fail cleanly until you rebuild without this flag. |
--force | Rebuild even if a matching index exists |
--no-progress | Suppress progress spinner |
# 3.2 Build the overview cache
hunt overview path/to/heap.hprof --index-dir path/to/heap.idx
This creates overview.bin inside the index directory.
Run it again after re-indexing, or use --force to overwrite.
#
4. Summary Commands (use overview.bin)
#
info: high-level dump summary
hunt info --index-dir path/to/heap.idx
Sample output:
Header:
id_size: 8 bytes
timestamp: 1783429843270
Summary:
total objects: 169033
classloaders: 4
classes: 1844
arrays: 67091
heap bytes: 10137438
#
histogram: top classes by shallow heap
# CSV output, top 15 by bytes
hunt histogram --index-dir path/to/heap.idx
# Human-readable table
hunt histogram --index-dir path/to/heap.idx --view
# Sort by instance count
hunt histogram --index-dir path/to/heap.idx --view -s
# Limit to 20
hunt histogram --index-dir path/to/heap.idx --view -l 20
Output columns: class, instances, shallow_bytes.
| Option | Meaning |
|---|---|
-l N, --limit N | Top N rows (default 15) |
--view | Formatted table instead of CSV |
-s, --sort-instances | Sort by instance count, not bytes |
--match <regex> | Include only matching class names |
--exclude <regex> | Omit matching class names |
--min-bytes <n> | Minimum total shallow bytes |
--min-instances <n> | Minimum instance count |
Regex notes: supports ^, $, ., *, +, ?, escaped literals, and character classes.
#
classes: loaded class metadata
hunt classes --index-dir path/to/heap.idx --view
Output columns: class, superclass, instance_size.
| Option | Meaning |
|---|---|
--match <regex> | Filter class names |
--exclude <regex> | Exclude class names |
--min-instance-size <n> | Minimum bytes per instance |
# 5. Object Query Commands (use the persistent index)
#
objects: list object IDs by class
hunt objects 'com.example.heapforge.User' --index-dir path/to/heap.idx --limit 10
Output is JSON:
{
"pattern": "com.example.heapforge.User",
"limit": 10,
"offset": 0,
"items": [
{"id": "0x0000000708827488", "ordinal": 4001, "class": "com/example/heapforge/User", "kind": "instance", "shallow_bytes": 85}
],
"next_offset": 1
}
| Option | Meaning |
|---|---|
--limit N | Max objects (default 100) |
--offset N | Skip first N matches |
--reverse | Descending ordinal order |
#
sample: decoded representative objects
hunt sample 'com.example.heapforge.User' --index-dir path/to/heap.idx --limit 3
Returns the same objects as objects, but with field names and values:
{
"items": [{
"id": "0x0000000708827488",
"class": "com/example/heapforge/User",
"shallow_bytes": 85,
"fields": [
{"name": "id", "value": 1756},
{"name": "name", "ref": "0x...", "ordinal": 3998, "class": "java/lang/String"},
{"name": "active", "value": true}
]
}]
}
#
object: decode one object by ID
hunt object 0x0000000708827488 --index-dir path/to/heap.idx
# 6. Reference-Tracing Commands
These commands walk the heap graph built during indexing.
#
refs-from: outgoing references
hunt refs-from 0x0000000708827488 --index-dir path/to/heap.idx --limit 10
Sample:
{
"object": "0x0000000708827488",
"direction": "outbound",
"items": [
{"id": "0x...", "ordinal": 3998, "class": "java/lang/String", "relation": "name"}
],
"next_offset": 5
}
#
refs-to: incoming references
hunt refs-to 0x0000000708827488 --index-dir path/to/heap.idx --limit 10
Use this to answer "who is holding this object alive?"
#
roots: shortest path to a GC root
hunt roots 0x0000000708827488 --index-dir path/to/heap.idx --max-visited 10000
This is the classic leak-analysis command. It performs a breadth-first search back to the nearest GC root and prints the path:
{
"found": true,
"truncated": false,
"path": [
{"id": null, "ordinal": 170877, "class": "virtual root"},
{"id": "0x...", "class": "com/example/heapforge/UserRepository"},
{"id": "0x...", "class": "java/util/concurrent/ConcurrentHashMap"},
{"id": "0x...", "class": "com/example/heapforge/User"}
]
}
| Option | Meaning |
|---|---|
--max-visited <n> | Cap BFS node visits |
#
tree: bounded expansion
# Outbound tree
hunt tree 0x0000000708827488 --index-dir path/to/heap.idx --direction from --depth 3 --max-nodes 50
# Inbound tree
hunt tree 0x0000000708827488 --index-dir path/to/heap.idx --direction to --depth 3 --max-nodes 50
| Option | Meaning |
|---|---|
--direction from or to | Follow outbound or inbound refs (default from) |
--depth <n> | Max depth |
--max-nodes <n> | Max nodes in output |
# 7. Thread Queries
#
threads: live threads with reconstructed stacks
hunt threads --index-dir path/to/heap.idx
# If the dump moved since indexing, point at it explicitly:
hunt threads --index-dir path/to/heap.idx --source path/to/heap.hprof
Lists every thread captured in the dump, with its name, state (platform or virtual), priority, daemon flag, OS thread id (TID), and the reconstructed Java stack trace for each thread.
The index stores only small stack-trace metadata. Thread objects and name strings are decoded on demand from the source dump, so this command needs access to the original .hprof. If the dump moved after indexing, pass --source.
Sample output:
Thread: pool-worker-1
State: RUNNABLE
Priority: 5
Daemon: false
TID: 42
Stack trace:
at java.net.SocketInputStream.read(SocketInputStream.java:204)
at java.net.Socket$SocketInputStream.read(Socket.java:956)
at com.example.worker.Worker.process(Worker.java:88)
Use it to answer: what was each thread doing at the moment the dump was taken?
| Option | Meaning |
|---|---|
--index-dir <dir> | Directory containing the heap index |
--source <file> | Path to the original HPROF dump; overrides the path recorded in the index |
# 8. Dominator and Retained-Size Commands
These commands need an index built with dominators, which is the default for hunt index. If you built with --no-dominators, they fail with index was built without dominators; re-index with dominators enabled. Rebuild the index without that flag to use them.
Two definitions worth memorizing:
- The immediate dominator of an object is the nearest object whose removal would make the target unreachable.
- The retained size of an object is how many bytes would be freed if it became garbage.
#
dominator: immediate dominator and retained size
hunt dominator 0x0000000708800840 --index-dir path/to/heap.idx
{
"id": "0x0000000708800840",
"ordinal": 58,
"dominator": "0x0000000708803d78",
"retained_bytes": 1770
}
If the object is unreachable, or sits at the top of the reachable graph, dominator is null. Use dominator-tree to tell the two apart: an unreachable object yields a single-node path, while the top of the reachable graph yields a longer chain.
#
dominator-tree: bounded dominator chain
hunt dominator-tree 0x0000000708800840 --index-dir path/to/heap.idx --depth 2
Prints the chain of immediate dominators from the object up to the top of the reachable graph, with retained sizes that never decrease as you walk up:
{
"id": "0x0000000708800840",
"ordinal": 58,
"truncated": true,
"path": [
{ "ordinal": 58, "id": "0x0000000708800840", "retained_bytes": 1770 },
{ "ordinal": 358, "id": "0x0000000708803d78", "retained_bytes": 37413 },
{ "ordinal": 57734, "id": "0x0000000708c2c430", "retained_bytes": 37461 }
]
}
The virtual root is a synthetic construct of the tool and is never emitted, so the chain ends at a real object, usually a ClassLoader or a Thread.
| Option | Meaning |
|---|---|
--depth <n> | Follow at most n dominator links. The chain has one more node than this when it is not truncated. |
--max-nodes <n> | Maximum number of nodes in the output path |
When a bound cuts the chain short, the output reports "truncated": true. A chain that ends naturally (the object has no dominator, or it reached the top of the reachable graph) reports "truncated": false, so a caller can tell a bounded walk from a genuinely short chain.
#
retained: retained size and retention chain
hunt retained 0x0000000708800840 --index-dir path/to/heap.idx
{
"id": "0x0000000708800840",
"ordinal": 58,
"class": "java/lang/ClassLoader",
"shallow_bytes": 48,
"retained_bytes": 1770,
"retained_delta_bytes": 1722,
"dom_depth": 3,
"dominators": [
{ "id": "0x0000000708803d78", "class": "java/lang/ClassLoader", "retained_bytes": 37413 }
]
}
retained_delta_bytes is retained_bytes - shallow_bytes, and dominators walks upward from the object toward the top of the reachable graph. Unlike dominator-tree, retained has no depth bound. Use dominator-tree when you need a bounded chain.
#
retainers: objects with the largest retained sizes
hunt retainers --index-dir path/to/heap.idx --top 5
{
"top": 5,
"items": [
{
"id": "0x0000000708803d78",
"ordinal": 358,
"class": "java/lang/ClassLoader",
"shallow_bytes": 48,
"retained_bytes": 37461,
"retained_delta_bytes": 37413,
"dom_depth": 1
}
]
}
Results are ordered by retained_bytes descending, with the object ordinal as a deterministic tiebreak. This is the command for "what is holding most of the heap?"
| Option | Meaning |
|---|---|
--top <n> | Number of objects to report (default 10) |
# 9. MCP Server
hunt mcp runs Heap Hunter as a Model Context Protocol server. It speaks JSON-RPC 2.0 over stdin/stdout with newline-delimited messages, needs no sockets and no daemon, and exits when stdin closes. This is the integration point for AI agents: an agent can index a dump and answer retention questions directly from its tool loop.
The config file's index-dir is used as the default base directory when analyze_heap_dump is called without an explicit index_dir argument.
| Tool | Description |
|---|---|
analyze_heap_dump | Index a dump and build the overview cache. First tool to call for a new dump. |
heap_info | Header and high-level summary. |
heap_histogram | Class-level histogram of instance counts and shallow bytes. |
heap_classes | Loaded class metadata with names, superclasses, and instance sizes. |
find_objects | Object IDs whose class name matches a regex. |
sample_objects | Decoded sample objects matching a class regex. |
get_object | Full decode of a single object, including typed field values and decoded java.lang.String text. |
refs_from | Outgoing references of an object. |
refs_to | Incoming references of an object. |
list_threads | Threads with names, states, priorities, daemon flags, and stack traces decoded on demand. |
find_roots | Shortest path from an object to a GC root. |
reference_tree | Bounded reference tree expansion from an object. |
retained_size | Retained size, shallow size, retained delta, dominator depth, and dominator chain for one object. Requires dominators. |
top_retainers | Objects with the largest retained sizes. Requires dominators; use the top argument to bound the result. |
Example session, one JSON-RPC message per line. Responses come back newline-delimited on stdout.
Initialize the session:
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}
Index a dump (emits progress notifications while the index builds):
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"analyze_heap_dump","arguments":{"hprof_path":"/tmp/heap.hprof"}}}
Query the histogram:
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"heap_histogram","arguments":{"index_dir":"index/heap.idx","limit":10}}}
Tool results are returned as text content blocks containing JSON. Failures are reported with isError: true and a JSON error payload inside the content block.
# 10. Complete Example Session
# 1. Place heap dump file
#copy heap dump to the location where the binary exists
# 2. Index (dominators are computed by default)
hunt index production-heap.hprof --index-dir production-heap.idx
# 3. Overview
hunt overview production-heap.hprof --index-dir production-heap.idx
# 4. Summarize
hunt info --index-dir production-heap.idx
hunt histogram --index-dir production-heap.idx --view -l 20
# 5. Find suspicious class
hunt histogram --index-dir production-heap.idx --match '^com\.mycompany\.' --view -l 10
# 6. Sample instances
hunt sample 'com.mycompany.SessionContext' --index-dir production-heap.idx --limit 3
# 7. Pick an object and trace it
ID=$(hunt objects 'com.mycompany.SessionContext' --index-dir production-heap.idx --limit 1 | python3 -c "import sys,json; print(json.load(sys.stdin)['items'][0]['id'])")
hunt roots "$ID" --index-dir production-heap.idx --max-visited 50000
hunt tree "$ID" --index-dir production-heap.idx --direction to --depth 4 --max-nodes 100
# 8. Rank objects by retained size
hunt retainers --index-dir production-heap.idx --top 5
# 9. Inspect the retention chain of the top retainer (use its id from step 8)
hunt retained 0x0000000708803d78 --index-dir production-heap.idx
hunt dominator-tree 0x0000000708803d78 --index-dir production-heap.idx --depth 4
# 10. What was each thread doing when the dump was taken?
hunt threads --index-dir production-heap.idx
# 11. Output Formats
| Command | Default | With --view |
|---|---|---|
index, overview | JSON | Not applicable |
info | Human table | Not applicable |
histogram, classes | CSV | Human table |
objects, sample, object | JSON | Not applicable |
refs-from, refs-to, roots, tree | JSON | Not applicable |
threads | Human-readable text | Not applicable |
dominator, dominator-tree, retained, retainers | JSON | Not applicable |
mcp | JSON-RPC 2.0 over stdio | Not applicable |
# 12. Environment Variables
| Variable | Effect |
|---|---|
NO_COLOR=1 | Disable colored output |
FORCE_COLOR=1 | Force colored output even when not a TTY |
XDG_CONFIG_HOME | Changes default config search path |
# 13. Common Errors
| Error | Cause | Fix |
|---|---|---|
overview cache not found; run 'hunt overview ...' | Querying before overview | Run overview after index |
index not found; run 'hunt index ...' | Missing or wrong --index-dir | Check path, run index first |
object id not found in index | ID does not exist or wrong format | Use IDs returned by objects |
index was built without dominators; re-index with dominators enabled | Querying dominator, dominator-tree, retained, or retainers on an index built with --no-dominators | Rebuild the index without --no-dominators |
dominator does not support --depth or --max-nodes; use hunt dominator-tree | Passing depth bounds to dominator or retained | Use hunt dominator-tree for a bounded chain |
# 14. Quick Command Reference
| Command | What it does | Needs |
|---|---|---|
index <dump> | Build persistent index (with dominators by default) | Source .hprof dump |
overview <dump> | Build overview.bin cache | Existing index |
info | Dump summary | Overview cache |
histogram | Class usage by size/count | Overview cache |
classes | Class metadata | Overview cache |
objects <regex> | Object IDs by class | Index |
sample <regex> | Decoded object samples | Index |
object <id> | Single object decode | Index |
threads | Threads with states and stack traces | Index + source dump |
refs-from <id> | Outbound refs | Index |
refs-to <id> | Inbound refs | Index |
roots <id> | Shortest path to GC root | Index |
tree <id> | Bounded ref tree | Index |
dominator <id> | Immediate dominator + retained size | Index with dominators |
dominator-tree <id> | Dominator chain to the top of the graph | Index with dominators |
retained <id> | Retained size + retention chain | Index with dominators |
retainers | Objects with the largest retained sizes | Index with dominators |
mcp | MCP server over stdio for AI agents | Config file (optional) |
Ready to run your first index?