Official Documentation

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.

bash
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:

bash
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:

bash
xattr -d com.apple.quarantine /path/to/hunt

Then run the binary normally:

bash
/path/to/hunt --help

# 1. Getting Help

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

bash
mkdir -p ~/.config/hunt
cat > ~/.config/hunt/config.json <<'EOF'
{
  "index-dir": "/path/to/your/indexes",
  "sorting-budget-mb": 4096
}
EOF

# Config behavior

FieldMeaning
index-dirThe 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-mbRAM 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.

  1. index — scan the .hprof once and write persistent index files.
  2. overview — build a small overview.bin cache for fast summary queries.
  3. Query commands — read from the index/cache.

You must run index, then overview, before any query command.

# 3.1 Index the dump

bash
hunt index path/to/heap.hprof --index-dir path/to/heap.idx

On success it prints a JSON summary:

json
{"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:

json
{"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.

OptionMeaning
--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-dominatorsSkip dominator computation. Dominator queries then fail cleanly until you rebuild without this flag.
--forceRebuild even if a matching index exists
--no-progressSuppress progress spinner

# 3.2 Build the overview cache

bash
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

bash
hunt info --index-dir path/to/heap.idx

Sample output:

text
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

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

OptionMeaning
-l N, --limit NTop N rows (default 15)
--viewFormatted table instead of CSV
-s, --sort-instancesSort 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

bash
hunt classes --index-dir path/to/heap.idx --view

Output columns: class, superclass, instance_size.

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

bash
hunt objects 'com.example.heapforge.User' --index-dir path/to/heap.idx --limit 10

Output is JSON:

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
}
OptionMeaning
--limit NMax objects (default 100)
--offset NSkip first N matches
--reverseDescending ordinal order

# sample: decoded representative objects

bash
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:

json
{
  "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

bash
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

bash
hunt refs-from 0x0000000708827488 --index-dir path/to/heap.idx --limit 10

Sample:

json
{
  "object": "0x0000000708827488",
  "direction": "outbound",
  "items": [
    {"id": "0x...", "ordinal": 3998, "class": "java/lang/String", "relation": "name"}
  ],
  "next_offset": 5
}

# refs-to: incoming references

bash
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

bash
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:

json
{
  "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"}
  ]
}
OptionMeaning
--max-visited <n>Cap BFS node visits

# tree: bounded expansion

bash
# 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
OptionMeaning
--direction from or toFollow 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

bash
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:

text
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?

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

bash
hunt dominator 0x0000000708800840 --index-dir path/to/heap.idx
json
{
  "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

bash
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:

json
{
  "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.

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

bash
hunt retained 0x0000000708800840 --index-dir path/to/heap.idx
json
{
  "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

bash
hunt retainers --index-dir path/to/heap.idx --top 5
json
{
  "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?"

OptionMeaning
--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.

ToolDescription
analyze_heap_dumpIndex a dump and build the overview cache. First tool to call for a new dump.
heap_infoHeader and high-level summary.
heap_histogramClass-level histogram of instance counts and shallow bytes.
heap_classesLoaded class metadata with names, superclasses, and instance sizes.
find_objectsObject IDs whose class name matches a regex.
sample_objectsDecoded sample objects matching a class regex.
get_objectFull decode of a single object, including typed field values and decoded java.lang.String text.
refs_fromOutgoing references of an object.
refs_toIncoming references of an object.
list_threadsThreads with names, states, priorities, daemon flags, and stack traces decoded on demand.
find_rootsShortest path from an object to a GC root.
reference_treeBounded reference tree expansion from an object.
retained_sizeRetained size, shallow size, retained delta, dominator depth, and dominator chain for one object. Requires dominators.
top_retainersObjects 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:

json
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}

Index a dump (emits progress notifications while the index builds):

json
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"analyze_heap_dump","arguments":{"hprof_path":"/tmp/heap.hprof"}}}

Query the histogram:

json
{"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

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

CommandDefaultWith --view
index, overviewJSONNot applicable
infoHuman tableNot applicable
histogram, classesCSVHuman table
objects, sample, objectJSONNot applicable
refs-from, refs-to, roots, treeJSONNot applicable
threadsHuman-readable textNot applicable
dominator, dominator-tree, retained, retainersJSONNot applicable
mcpJSON-RPC 2.0 over stdioNot applicable

# 12. Environment Variables

VariableEffect
NO_COLOR=1Disable colored output
FORCE_COLOR=1Force colored output even when not a TTY
XDG_CONFIG_HOMEChanges default config search path

# 13. Common Errors

ErrorCauseFix
overview cache not found; run 'hunt overview ...'Querying before overviewRun overview after index
index not found; run 'hunt index ...'Missing or wrong --index-dirCheck path, run index first
object id not found in indexID does not exist or wrong formatUse IDs returned by objects
index was built without dominators; re-index with dominators enabledQuerying dominator, dominator-tree, retained, or retainers on an index built with --no-dominatorsRebuild the index without --no-dominators
dominator does not support --depth or --max-nodes; use hunt dominator-treePassing depth bounds to dominator or retainedUse hunt dominator-tree for a bounded chain

# 14. Quick Command Reference

CommandWhat it doesNeeds
index <dump>Build persistent index (with dominators by default)Source .hprof dump
overview <dump>Build overview.bin cacheExisting index
infoDump summaryOverview cache
histogramClass usage by size/countOverview cache
classesClass metadataOverview cache
objects <regex>Object IDs by classIndex
sample <regex>Decoded object samplesIndex
object <id>Single object decodeIndex
threadsThreads with states and stack tracesIndex + source dump
refs-from <id>Outbound refsIndex
refs-to <id>Inbound refsIndex
roots <id>Shortest path to GC rootIndex
tree <id>Bounded ref treeIndex
dominator <id>Immediate dominator + retained sizeIndex with dominators
dominator-tree <id>Dominator chain to the top of the graphIndex with dominators
retained <id>Retained size + retention chainIndex with dominators
retainersObjects with the largest retained sizesIndex with dominators
mcpMCP server over stdio for AI agentsConfig file (optional)

Ready to run your first index?