Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat(memory): compare two heap snapshots to report constructor growth and retained-size deltas (PIN-399)

Luigi Agosti587f3cb28583
diff --git a/cmd/pinchtab/cmd_cli_memory.go b/cmd/pinchtab/cmd_cli_memory.go
index 2944763c..5c9cdad0 100644
--- a/cmd/pinchtab/cmd_cli_memory.go
+++ b/cmd/pinchtab/cmd_cli_memory.go
@@ -11,8 +11,9 @@ var memoryCmd = &cobra.Command{
Long: `Read the tab's JavaScript heap usage and DOM counters.
Pass --gc to run a garbage collection first so two reads compare live memory only.
-Subcommands: snapshot writes a V8 heap snapshot to a server-side file, and summary
-lists its top constructors and duplicate strings. Both need security.allowMemory,
+Subcommands: snapshot writes a V8 heap snapshot to a server-side file, summary
+lists its top constructors and duplicate strings, and compare reports what grew
+between two snapshots. All three need security.allowMemory,
because a heap snapshot holds every string on the page, tokens included.`,
Run: func(cmd *cobra.Command, args []string) {
runCLI(func(rt cliRuntime) {
@@ -48,6 +49,22 @@ var memorySummaryCmd = &cobra.Command{
},
}
+var memoryCompareCmd = &cobra.Command{
+ Use: "compare <base> <head>",
+ Short: "Compare two saved heap snapshots by constructor growth",
+ Long: `Compare two saved heap snapshots: per constructor, count and self size in each and
+the delta, largest change first, plus duplicate strings new in head. Take a snapshot,
+run the suspect action, take another, then compare the two ids. --retained adds each
+listed constructor's retained size in head from a dominator tree, which costs memory
+and time proportional to the snapshot's edges.`,
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.MemoryCompare(rt.client, rt.base, rt.token, cmd, args[0], args[1])
+ })
+ },
+}
+
func configureMemoryFlags() {
memoryCmd.Flags().Bool("gc", false, "Collect garbage before reading")
memoryCmd.Flags().String("tab", "", "Target tab ID")
@@ -57,4 +74,7 @@ func configureMemoryFlags() {
memorySnapshotCmd.Flags().Bool("json", false, "Output raw JSON")
memorySummaryCmd.Flags().Int("top", 20, "Rows per table (max 200)")
memorySummaryCmd.Flags().Bool("json", false, "Output raw JSON")
+ memoryCompareCmd.Flags().Int("top", 20, "Constructor and duplicate-string rows (max 200)")
+ memoryCompareCmd.Flags().Bool("retained", false, "Add retained sizes from the head snapshot's dominator tree")
+ memoryCompareCmd.Flags().Bool("json", false, "Output raw JSON")
}
diff --git a/cmd/pinchtab/cmd_cli_memory_test.go b/cmd/pinchtab/cmd_cli_memory_test.go
index f7ebf308..7b63488a 100644
--- a/cmd/pinchtab/cmd_cli_memory_test.go
+++ b/cmd/pinchtab/cmd_cli_memory_test.go
@@ -6,6 +6,7 @@ func TestMemoryCommandsAreRegisteredWithTheirFlags(t *testing.T) {
want := map[string][]string{
"snapshot": {"tab", "out", "json"},
"summary": {"top", "json"},
+ "compare": {"top", "retained", "json"},
}
for _, sub := range memoryCmd.Commands() {
flags, ok := want[sub.Name()]
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 1f767604..aafeb703 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -47,7 +47,7 @@ func registerBrowserCommands() {
networkCmd.AddCommand(networkRouteCmd, networkUnrouteCmd, networkRulesCmd)
recordCmd.AddCommand(recordStartCmd, recordStopCmd, recordStatusCmd)
a11yCmd.AddCommand(a11yAuditCmd)
- memoryCmd.AddCommand(memorySnapshotCmd, memorySummaryCmd)
+ memoryCmd.AddCommand(memorySnapshotCmd, memorySummaryCmd, memoryCompareCmd)
configureBrowserFlags()
configureA11yFlags()
diff --git a/docs/commands.md b/docs/commands.md
index a2f311df..48e7077d 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -219,9 +219,11 @@ pinchtab memory --gc --json # Collect garbage first, raw JSON
pinchtab memory snapshot # V8 heap snapshot to a server-side file (security.allowMemory)
pinchtab memory snapshot --out app.heapsnapshot # Also copy it to a local path
pinchtab memory summary <id> --top 5 # Top constructors and duplicate strings of a snapshot
+pinchtab memory compare <a> <b> --top 5 # Constructor growth from snapshot a to snapshot b
+pinchtab memory compare <a> <b> --retained # Also retained sizes from b's dominator tree
```
-`pinchtab memory snapshot` and `pinchtab memory summary` need
+`pinchtab memory snapshot`, `summary` and `compare` need
`security.allowMemory`, because a heap snapshot holds every string on the page.
See [reference/memory.md](reference/memory.md).
diff --git a/docs/endpoints.md b/docs/endpoints.md
index d4e4e1c4..377c1da4 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -183,10 +183,11 @@ POST /tabs/{id}/evaluate
GET /memory
POST /memory/snapshot
GET /memory/snapshot/{snapshotId}/summary
+GET /memory/compare?base=<id>&head=<id>
```
-`/memory` reads the tab's JavaScript heap and DOM counters; the snapshot and summary
-routes need `security.allowMemory` — see [reference/memory.md](reference/memory.md).
+`/memory` reads the tab's JavaScript heap and DOM counters; the snapshot, summary and
+compare routes need `security.allowMemory` — see [reference/memory.md](reference/memory.md).
`POST /actions` and `POST /macro` answer **200 whatever their steps did**: the envelope
reports the run, and each step's outcome is its own entry — `{"index", "success", "code",
diff --git a/docs/mcp.md b/docs/mcp.md
index 06051fa1..d6516e68 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -114,7 +114,7 @@ PINCHTAB_TOKEN=<that-host-token> pinchtab --server http://remote:9867 mcp
## Available Tools
-PinchTab currently exposes 46 tools:
+PinchTab currently exposes 47 tools:
- Navigation: 9
- Interaction: 8
@@ -122,11 +122,11 @@ PinchTab currently exposes 46 tools:
- Content: 4
- Recording: 1
- Site: 1
-- Tab management: 5
+- Tab management: 6
- Human handoff: 3
- Wait utilities: 1
-- Network: 5
-- Diagnostics: 5
+- Network: 6
+- Diagnostics: 6
- Dialog: 1
### Navigation
@@ -206,6 +206,7 @@ PinchTab currently exposes 46 tools:
- `pinchtab_a11y_audit` — accessibility audit; `engine=axe` runs vendored axe-core in the isolated world and returns ref-mapped violations with WCAG tags and help URLs
- `pinchtab_memory` — JavaScript heap usage and DOM counters for the tab; `gc=true` collects garbage first so two reads compare retained memory
- `pinchtab_memory_snapshot` — take a V8 heap snapshot to a server-side file and return only its path and a summary (top constructors, duplicate strings); needs `security.allowMemory`. See [Memory](reference/memory.md)
+- `pinchtab_memory_compare` — compare two snapshot ids: per-constructor count and self-size deltas, largest first, plus new duplicate strings; `retained=true` adds retained sizes from the head snapshot's dominator tree; needs `security.allowMemory`
### Dialog
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 0f0f1f90..41fd1f21 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -609,7 +609,7 @@ same key and accepts the same flag.
| Setting | Default | Effect |
| --- | --- | --- |
-| `security.allowMemory` | `false` | Enables `POST /memory/snapshot` and `GET /memory/snapshot/{snapshotId}/summary` (code `memory_disabled` when off). `GET /memory` needs no capability. |
+| `security.allowMemory` | `false` | Enables `POST /memory/snapshot`, `GET /memory/snapshot/{snapshotId}/summary` and `GET /memory/compare` (code `memory_disabled` when off). `GET /memory` needs no capability. |
| `security.memorySnapshotMaxBytes` | `536870912` (512 MB) | Size cap for one heap snapshot, max 4 GB; a larger snapshot is aborted with `memory_snapshot_too_large` and no file is left behind |
A heap snapshot contains every string on the page, tokens included, which is why
diff --git a/docs/reference/index.md b/docs/reference/index.md
index e7c3f6aa..accf6940 100644
--- a/docs/reference/index.md
+++ b/docs/reference/index.md
@@ -20,6 +20,7 @@ Note: this index is generated and should be checked against the code when comman
- [Hover](./hover.md)
- [Instances](./instances.md)
- [Keyboard](./keyboard.md)
+- [Memory](./memory.md)
- [Metrics](./metrics.md)
- [Mouse](./mouse.md)
- [Navigate](./navigate.md)
diff --git a/docs/reference/memory.md b/docs/reference/memory.md
new file mode 100644
index 00000000..1ce84d6c
--- /dev/null
+++ b/docs/reference/memory.md
@@ -0,0 +1,135 @@
+# Memory
+
+PinchTab can answer "is this page leaking?" without a human at DevTools: read the
+tab's heap usage, write V8 heap snapshots to server-side files, summarize one, and
+compare two to see which constructors grew.
+
+`GET /memory` is always available. Everything that touches a heap snapshot needs
+`security.allowMemory` (default off; code `memory_disabled` when off), because a
+heap snapshot holds every string on the page, tokens included.
+
+## Endpoints
+
+| Method | Path | Capability | Purpose |
+| --- | --- | --- | --- |
+| `GET` | `/memory`, `/tabs/{id}/memory` | none | Heap usage and DOM counters |
+| `POST` | `/memory/snapshot`, `/tabs/{id}/memory/snapshot` | `allowMemory` | Take a heap snapshot to a file |
+| `GET` | `/memory/snapshot/{snapshotId}/summary` | `allowMemory` | Top constructors and duplicate strings of one snapshot |
+| `GET` | `/memory/compare` | `allowMemory` | Constructor growth between two snapshots |
+
+## Usage
+
+`GET /memory?tabId=<id>&gc=true` returns `usedJSHeapSize`, `totalJSHeapSize`,
+`jsHeapSizeLimit`, `documents`, `nodes`, `listeners` and `frames`. `gc=true` runs a
+garbage collection first so two reads compare live memory only.
+
+```bash
+pinchtab memory --gc
+```
+
+## Snapshot
+
+`POST /memory/snapshot` with an optional `{"tabId": "..."}` streams the snapshot to
+`<stateDir>/heapsnapshots/<id>.heapsnapshot` and returns
+`{id, path, bytes, nodeCount, durationMs, tabId}`. The file loads in the Chrome
+DevTools Memory panel. A snapshot larger than `security.memorySnapshotMaxBytes`
+(default 512 MB) is discarded and answered `413 memory_snapshot_too_large`.
+
+```bash
+pinchtab memory snapshot # prints the id and path
+pinchtab memory snapshot --out app.heapsnapshot # also copy it locally
+```
+
+## Summary
+
+`GET /memory/snapshot/{snapshotId}/summary?top=20` returns `nodeCount`, `edgeCount`,
+`totalSelfSize`, `topBySize`, `topByCount` (constructor rows of `name`, `count`,
+`selfSize`) and `duplicateStrings` (`value`, `length`, `count`, `selfSize`).
+
+```bash
+pinchtab memory summary heap_20260913_101010 --top 5
+```
+
+Objects group by constructor name; other V8 node types group as `(array)`,
+`(string)`, `(closure)`, `(compiled code)`, `(system)` and so on, as in DevTools. A
+JavaScript `Array`'s elements live in a separate `(array)` backing store, so a
+growing array shows its bytes under `(array)` while `Array` itself stays small.
+
+## Compare
+
+`GET /memory/compare?base=<id>&head=<id>&top=20&retained=false`
+
+| Parameter | Default | Description |
+| --- | --- | --- |
+| `base` | required | The earlier snapshot id |
+| `head` | required | The later snapshot id |
+| `top` | `20` | Rows in `constructors` and `newDuplicateStrings` (max 200) |
+| `retained` | `false` | Add `retainedSize` to each returned row, from a dominator tree of `head` |
+
+```json
+{
+ "top": 20,
+ "retained": false,
+ "base": {"id": "heap_20260913_101010", "nodeCount": 51234, "edgeCount": 210876, "totalSelfSize": 2811904},
+ "head": {"id": "heap_20260913_101042", "nodeCount": 51310, "edgeCount": 211002, "totalSelfSize": 18543616},
+ "nodeDelta": 76,
+ "sizeDelta": 15731712,
+ "changed": 41,
+ "constructors": [
+ {"name": "(array)", "baseCount": 812, "headCount": 815, "countDelta": 3,
+ "baseSelfSize": 190440, "headSelfSize": 15919128, "sizeDelta": 15728688}
+ ],
+ "newDuplicateStrings": [
+ {"value": "session-expired", "length": 15, "count": 3, "selfSize": 96}
+ ]
+}
+```
+
+- `constructors` lists only constructors whose count or self size changed, largest
+ absolute `sizeDelta` first, so both growth and release rise to the top. `changed`
+ counts every changed constructor, including those `top` cut.
+- `newDuplicateStrings` are strings held more than once in `head` that were not
+ duplicated in `base`.
+- `retainedSize` is the memory freed if every object of that constructor were
+ collected: the sum of each object's dominator-tree subtree, counting an object
+ nested under another of the same constructor once. It is present only with
+ `retained=true`. Weak edges are ignored, as in DevTools. Computing it holds the
+ whole head graph in memory and costs time proportional to its edges, which is why
+ it is opt-in.
+- Parsed snapshots are cached in memory per snapshot file for the process lifetime,
+ so comparing the same ids again, or summarizing one you compared, does not reparse.
+
+Errors: `400 bad_snapshot_id` (missing or malformed id), `400 bad_top`,
+`400 bad_retained`, `404 memory_snapshot_not_found` (details name the `id`),
+`422 memory_snapshot_invalid` (details name the `id` and the broken `section`),
+`403 memory_disabled`.
+
+CLI and MCP:
+
+```bash
+pinchtab memory compare <base> <head> --top 5
+pinchtab memory compare <base> <head> --retained --json
+```
+
+MCP `pinchtab_memory_compare` takes `base`, `head`, `top` and `retained`.
+
+## Walkthrough: find a leak
+
+1. Load the page and settle it, then take the baseline:
+ `pinchtab memory snapshot` prints `heap_A`.
+2. Repeat the suspect action several times (open and close a dialog, paginate,
+ route back and forth). Repetition makes a leak grow linearly while one-off
+ caches stay flat.
+3. Take a second snapshot: `heap_B`. Taking a snapshot runs a full garbage
+ collection, so anything still counted is reachable.
+4. Compare: `pinchtab memory compare heap_A heap_B --top 10`. A leaking
+ constructor sits near the top with a positive `sizeDelta` and a `countDelta`
+ that tracks the number of repetitions.
+5. Ask who holds it: `pinchtab memory compare heap_A heap_B --retained` shows
+ how much each listed constructor keeps alive. A small object with a large
+ retained size (a component, a closure, a `Map`) is usually the owner to fix.
+6. Undo the action (close, release, navigate away), take `heap_C`, and compare
+ `heap_B heap_C`: the constructor should show a negative `sizeDelta`. If it
+ does not, something still references it.
+7. Open the files in DevTools (Memory panel, Comparison view) for the retainer
+ path of an individual object.
diff --git a/internal/cli/actions/actions_memory.go b/internal/cli/actions/actions_memory.go
index f9bd68a7..d344daa0 100644
--- a/internal/cli/actions/actions_memory.go
+++ b/internal/cli/actions/actions_memory.go
@@ -156,3 +156,71 @@ func constructorTable(rows []heapsnap.Constructor) string {
}
return out
}
+
+type memoryComparison struct {
+ Top int `json:"top"`
+ Retained bool `json:"retained"`
+ heapsnap.Comparison
+}
+
+func MemoryCompare(client *http.Client, base, token string, cmd *cobra.Command, baseID, headID string) {
+ params := url.Values{}
+ params.Set("base", baseID)
+ params.Set("head", headID)
+ if top, _ := cmd.Flags().GetInt("top"); top > 0 {
+ params.Set("top", strconv.Itoa(top))
+ }
+ if retained, _ := cmd.Flags().GetBool("retained"); retained {
+ params.Set("retained", "true")
+ }
+ if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ apiclient.DoGet(client, base, token, "/memory/compare", params)
+ return
+ }
+ body := apiclient.DoGetRaw(client, base, token, "/memory/compare", params)
+ var cmp memoryComparison
+ if err := json.Unmarshal(body, &cmp); err != nil {
+ fmt.Println(string(body))
+ return
+ }
+ fmt.Print(formatMemoryComparison(cmp))
+}
+
+func formatMemoryComparison(c memoryComparison) string {
+ out := fmt.Sprintf("%s → %s: self size %s → %s (%s), nodes %+d, %d constructors changed\n",
+ c.Base.ID, c.Head.ID, formatBytes(c.Base.TotalSelfSize), formatBytes(c.Head.TotalSelfSize),
+ formatSignedBytes(c.SizeDelta), c.NodeDelta, c.Changed)
+ out += "\nConstructors by size delta\n"
+ if len(c.Constructors) == 0 {
+ out += " (no change)\n"
+ } else {
+ header := fmt.Sprintf(" %-32s %8s %12s %10s %10s", "CONSTRUCTOR", "COUNT Δ", "SIZE Δ", "BASE", "HEAD")
+ if c.Retained {
+ header += fmt.Sprintf(" %10s", "RETAINED")
+ }
+ out += header + "\n"
+ for _, r := range c.Constructors {
+ line := fmt.Sprintf(" %-32s %+8d %12s %10s %10s", r.Name, r.CountDelta, formatSignedBytes(r.SizeDelta), formatBytes(r.BaseSelfSize), formatBytes(r.HeadSelfSize))
+ if r.RetainedSize != nil {
+ line += fmt.Sprintf(" %10s", formatBytes(*r.RetainedSize))
+ }
+ out += line + "\n"
+ }
+ }
+ out += "\nNew duplicate strings\n"
+ if len(c.NewDuplicateStrings) == 0 {
+ return out + " (none)\n"
+ }
+ out += fmt.Sprintf(" %8s %10s %s\n", "COUNT", "SELF SIZE", "VALUE")
+ for _, d := range c.NewDuplicateStrings {
+ out += fmt.Sprintf(" %8d %10s %q\n", d.Count, formatBytes(d.SelfSize), d.Value)
+ }
+ return out
+}
+
+func formatSignedBytes(n int64) string {
+ if n < 0 {
+ return "-" + formatBytes(-n)
+ }
+ return "+" + formatBytes(n)
+}
diff --git a/internal/cli/actions/actions_memory_test.go b/internal/cli/actions/actions_memory_test.go
index faea2455..1552bbae 100644
--- a/internal/cli/actions/actions_memory_test.go
+++ b/internal/cli/actions/actions_memory_test.go
@@ -10,6 +10,7 @@ import (
"strings"
"testing"
+ "github.com/pinchtab/pinchtab/internal/heapsnap"
"github.com/spf13/cobra"
)
@@ -103,3 +104,56 @@ func TestMemorySummaryPrintsTheConstructorTable(t *testing.T) {
}
}
}
+
+func TestMemoryComparePrintsTheDeltaTable(t *testing.T) {
+ var got string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got = r.URL.RequestURI()
+ _, _ = io.WriteString(w, `{"top":5,"retained":true,
+ "base":{"id":"heap_a","nodeCount":20,"edgeCount":6,"totalSelfSize":3536},
+ "head":{"id":"heap_b","nodeCount":15,"edgeCount":17,"totalSelfSize":10820},
+ "nodeDelta":-5,"sizeDelta":7284,"changed":7,
+ "constructors":[{"name":"(array)","baseCount":1,"headCount":2,"countDelta":1,"baseSelfSize":800,"headSelfSize":10000,"sizeDelta":9200,"retainedSize":10000},
+ {"name":"Array","baseCount":3,"headCount":2,"countDelta":-1,"baseSelfSize":1664,"headSelfSize":64,"sizeDelta":-1600,"retainedSize":10064}],
+ "newDuplicateStrings":[{"value":"new-dup-string","length":14,"count":2,"selfSize":80}]}`)
+ }))
+ defer srv.Close()
+
+ cmd := memoryCommand(t, "--top", "5")
+ cmd.Flags().Bool("retained", false, "")
+ if err := cmd.Flags().Set("retained", "true"); err != nil {
+ t.Fatal(err)
+ }
+ out := captureStdout(t, func() {
+ MemoryCompare(srv.Client(), srv.URL, "", cmd, "heap_a", "heap_b")
+ })
+ if got != "/memory/compare?base=heap_a&head=heap_b&retained=true&top=5" {
+ t.Fatalf("request = %q", got)
+ }
+ lines := strings.Split(out, "\n")
+ firstRow := ""
+ for i, line := range lines {
+ if strings.Contains(line, "CONSTRUCTOR") && i+1 < len(lines) {
+ firstRow = lines[i+1]
+ }
+ }
+ if !strings.Contains(firstRow, "(array)") || !strings.Contains(firstRow, "+9.0 KB") {
+ t.Fatalf("first row = %q\n%s", firstRow, out)
+ }
+ for _, want := range []string{"heap_a → heap_b", "+7.1 KB", "7 constructors changed", "RETAINED", "-1.6 KB", "9.8 KB", `"new-dup-string"`} {
+ if !strings.Contains(out, want) {
+ t.Errorf("output lacks %q:\n%s", want, out)
+ }
+ }
+}
+
+func TestMemoryCompareWithoutRetainedPrintsNoRetainedColumn(t *testing.T) {
+ out := formatMemoryComparison(memoryComparison{Comparison: heapsnap.Comparison{
+ Base: heapsnap.Totals{ID: "heap_a"},
+ Head: heapsnap.Totals{ID: "heap_b"},
+ Constructors: []heapsnap.ConstructorDelta{{Name: "Array", CountDelta: 1, SizeDelta: 32}},
+ }})
+ if strings.Contains(out, "RETAINED") || !strings.Contains(out, "(none)") {
+ t.Fatalf("output:\n%s", out)
+ }
+}
diff --git a/internal/devtools/e2e_escalation_test.go b/internal/devtools/e2e_escalation_test.go
index 96c1b719..4d5deb33 100644
--- a/internal/devtools/e2e_escalation_test.go
+++ b/internal/devtools/e2e_escalation_test.go
@@ -379,6 +379,9 @@ var enrolledAreas = []enrolledArea{
name: "compare",
match: `(?i)compare`,
suites: []string{"run_cli_extended"},
+ excluded: map[string]string{
+ "internal/heapsnap/compare.go": "heap snapshot diffing — the memory compare route, a different sense of the word, covered by the memory scenarios rather than the compare ones",
+ },
},
}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index e674342a..381461b2 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -14,6 +14,7 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/contentguard"
"github.com/pinchtab/pinchtab/internal/dashboard"
+ "github.com/pinchtab/pinchtab/internal/heapsnap"
"github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/idpi"
"github.com/pinchtab/pinchtab/internal/ids"
@@ -45,6 +46,8 @@ type Handlers struct {
recorder *recorder
+ heapSnapshots heapsnap.Cache
+
// Optional dependency injection (for unit testing)
evalJS func(ctx context.Context, expression string, out *string) error
autoSolverRunner func(ctx context.Context, tabID string) error
@@ -379,6 +382,7 @@ func (h *Handlers) bridgeBindings() []routeBinding {
{pattern: "GET /memory", root: h.HandleMemory, tab: h.HandleTabMemory, guards: guardDialogBlocked | guardDomainPolicy},
{pattern: "POST /memory/snapshot", root: h.HandleMemorySnapshot, tab: h.HandleTabMemorySnapshot, guards: guardDialogBlocked | guardDomainPolicy},
{pattern: "GET /memory/snapshot/{snapshotId}/summary", root: h.HandleMemorySnapshotSummary, guards: guardNone},
+ {pattern: "GET /memory/compare", root: h.HandleMemoryCompare, guards: guardNone},
{pattern: "GET /a11y/audit", root: h.HandleA11yAudit, tab: h.HandleTabA11yAudit, guards: guardDialogBlocked | guardDomainPolicy},
{pattern: "POST /audit/page", root: h.HandleAuditPage, guards: guardNone},
{pattern: "POST /audit", root: h.HandleAudit, guards: guardNone},
diff --git a/internal/handlers/memory.go b/internal/handlers/memory.go
index 129fc8df..8eb3a7b9 100644
--- a/internal/handlers/memory.go
+++ b/internal/handlers/memory.go
@@ -195,40 +195,113 @@ func (h *Handlers) HandleMemorySnapshotSummary(w http.ResponseWriter, r *http.Re
}
id := strings.TrimSpace(r.PathValue("snapshotId"))
- path, err := heapsnap.PathForID(h.memorySnapshotDir(), id)
- if err != nil {
- httpx.ErrorCode(w, 400, "bad_snapshot_id", err.Error(), false, nil)
+ path, ok := h.snapshotPathOrRespond(w, id)
+ if !ok {
+ return
+ }
+ top, ok := memoryTopOrRespond(w, r)
+ if !ok {
return
}
+ agg, ok := h.loadSnapshotOrRespond(w, id, path, false)
+ if !ok {
+ return
+ }
+ httpx.JSON(w, 200, memorySummaryResponse{ID: id, Path: path, Top: top, Summary: agg.Summary(top)})
+}
- top := heapsnap.DefaultTop
- if raw := strings.TrimSpace(r.URL.Query().Get("top")); raw != "" {
- n, err := strconv.Atoi(raw)
- if err != nil || n <= 0 {
- httpx.ErrorCode(w, 400, "bad_top", fmt.Sprintf("top must be a positive integer, got %q", raw), false, nil)
- return
- }
- top = heapsnap.ClampTop(n)
+type memoryCompareResponse struct {
+ Top int `json:"top"`
+ Retained bool `json:"retained"`
+ heapsnap.Comparison
+}
+
+func (h *Handlers) HandleMemoryCompare(w http.ResponseWriter, r *http.Request) {
+ if !h.memoryEnabled() {
+ h.writeCapabilityDisabled(w, routes.CapMemory)
+ return
}
- if _, err := os.Stat(path); err != nil {
- if errors.Is(err, os.ErrNotExist) {
- httpx.ErrorCode(w, 404, memorySnapshotNotFoundCode, fmt.Sprintf("no heap snapshot with id %q", id), false, nil)
+ q := r.URL.Query()
+ baseID, headID := strings.TrimSpace(q.Get("base")), strings.TrimSpace(q.Get("head"))
+ if baseID == "" || headID == "" {
+ httpx.ErrorCode(w, 400, "bad_snapshot_id", "base and head are both required: pass the ids two POST /memory/snapshot calls returned", false, nil)
+ return
+ }
+ basePath, ok := h.snapshotPathOrRespond(w, baseID)
+ if !ok {
+ return
+ }
+ headPath, ok := h.snapshotPathOrRespond(w, headID)
+ if !ok {
+ return
+ }
+ top, ok := memoryTopOrRespond(w, r)
+ if !ok {
+ return
+ }
+ retained := false
+ if raw := strings.TrimSpace(q.Get("retained")); raw != "" {
+ parsed, err := strconv.ParseBool(raw)
+ if err != nil {
+ httpx.ErrorCode(w, 400, "bad_retained", fmt.Sprintf("retained must be true or false, got %q", raw), false, nil)
return
}
- httpx.Error(w, 500, fmt.Errorf("stat heap snapshot: %w", err))
- return
+ retained = parsed
}
- summary, err := heapsnap.SummarizeFile(path, top)
+ base, ok := h.loadSnapshotOrRespond(w, baseID, basePath, false)
+ if !ok {
+ return
+ }
+ head, ok := h.loadSnapshotOrRespond(w, headID, headPath, retained)
+ if !ok {
+ return
+ }
+ cmp, err := heapsnap.Compare(base, head, heapsnap.Options{Top: top, Retained: retained})
if err != nil {
- var parseErr *heapsnap.ParseError
- if errors.As(err, &parseErr) {
- httpx.ErrorCode(w, 422, memorySnapshotInvalidCode, err.Error(), false, map[string]any{"section": parseErr.Section})
- return
- }
- httpx.Error(w, 500, fmt.Errorf("summarize heap snapshot: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("compare heap snapshots: %w", err))
return
}
- httpx.JSON(w, 200, memorySummaryResponse{ID: id, Path: path, Top: top, Summary: summary})
+ cmp.Base.ID, cmp.Head.ID = baseID, headID
+ httpx.JSON(w, 200, memoryCompareResponse{Top: top, Retained: retained, Comparison: cmp})
+}
+
+func (h *Handlers) snapshotPathOrRespond(w http.ResponseWriter, id string) (string, bool) {
+ path, err := heapsnap.PathForID(h.memorySnapshotDir(), id)
+ if err != nil {
+ httpx.ErrorCode(w, 400, "bad_snapshot_id", err.Error(), false, nil)
+ return "", false
+ }
+ return path, true
+}
+
+func memoryTopOrRespond(w http.ResponseWriter, r *http.Request) (int, bool) {
+ raw := strings.TrimSpace(r.URL.Query().Get("top"))
+ if raw == "" {
+ return heapsnap.DefaultTop, true
+ }
+ n, err := strconv.Atoi(raw)
+ if err != nil || n <= 0 {
+ httpx.ErrorCode(w, 400, "bad_top", fmt.Sprintf("top must be a positive integer, got %q", raw), false, nil)
+ return 0, false
+ }
+ return heapsnap.ClampTop(n), true
+}
+
+func (h *Handlers) loadSnapshotOrRespond(w http.ResponseWriter, id, path string, retained bool) (*heapsnap.Aggregate, bool) {
+ agg, err := h.heapSnapshots.Load(path, retained)
+ if err == nil {
+ return agg, true
+ }
+ var parseErr *heapsnap.ParseError
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ httpx.ErrorCode(w, 404, memorySnapshotNotFoundCode, fmt.Sprintf("no heap snapshot with id %q", id), false, map[string]any{"id": id})
+ case errors.As(err, &parseErr):
+ httpx.ErrorCode(w, 422, memorySnapshotInvalidCode, err.Error(), false, map[string]any{"id": id, "section": parseErr.Section})
+ default:
+ httpx.Error(w, 500, fmt.Errorf("read heap snapshot %s: %w", id, err))
+ }
+ return nil, false
}
diff --git a/internal/handlers/memory_compare_test.go b/internal/handlers/memory_compare_test.go
new file mode 100644
index 00000000..48ed58bb
--- /dev/null
+++ b/internal/handlers/memory_compare_test.go
@@ -0,0 +1,111 @@
+package handlers
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func grownFixture(t *testing.T) string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join("..", "heapsnap", "testdata", "grown.heapsnapshot"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+func compareRequest(h *Handlers, query string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ h.HandleMemoryCompare(w, httptest.NewRequest(http.MethodGet, "/memory/compare"+query, nil))
+ return w
+}
+
+func TestMemoryCompareReportsConstructorGrowth(t *testing.T) {
+ h, stateDir := memoryHandlers(t, true)
+ seedSnapshot(t, stateDir, "heap_base", committedFixture(t))
+ seedSnapshot(t, stateDir, "heap_head", grownFixture(t))
+
+ w := compareRequest(h, "?base=heap_base&head=heap_head&top=3")
+ if w.Code != http.StatusOK {
+ t.Fatalf("compare = %d %s", w.Code, w.Body.String())
+ }
+ if strings.Contains(w.Body.String(), "retainedSize") {
+ t.Fatalf("compare without retained carries retainedSize: %s", w.Body.String())
+ }
+ var got memoryCompareResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Top != 3 || got.Retained || got.Base.ID != "heap_base" || got.Head.ID != "heap_head" || got.Changed != 7 || got.SizeDelta != 7284 {
+ t.Fatalf("compare header = %+v", got)
+ }
+ if len(got.Constructors) != 3 || got.Constructors[0].Name != "(array)" || got.Constructors[0].SizeDelta != 9200 {
+ t.Fatalf("constructors = %+v", got.Constructors)
+ }
+ if len(got.NewDuplicateStrings) != 1 || got.NewDuplicateStrings[0].Value != "new-dup-string" {
+ t.Fatalf("new duplicate strings = %+v", got.NewDuplicateStrings)
+ }
+
+ w = compareRequest(h, "?base=heap_base&head=heap_head&top=5&retained=true")
+ if w.Code != http.StatusOK {
+ t.Fatalf("compare retained = %d %s", w.Code, w.Body.String())
+ }
+ got = memoryCompareResponse{}
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if !got.Retained || len(got.Constructors) != 5 {
+ t.Fatalf("retained compare = %s", w.Body.String())
+ }
+ for _, row := range got.Constructors {
+ if row.RetainedSize == nil {
+ t.Fatalf("row %s lacks retainedSize: %s", row.Name, w.Body.String())
+ }
+ }
+ if got.Constructors[4].Name != "Leaker" || *got.Constructors[4].RetainedSize != 10168 {
+ t.Fatalf("Leaker row = %+v", got.Constructors[4])
+ }
+}
+
+func TestMemoryCompareRefusals(t *testing.T) {
+ h, stateDir := memoryHandlers(t, true)
+ seedSnapshot(t, stateDir, "heap_base", committedFixture(t))
+ seedSnapshot(t, stateDir, "heap_broken", strings.Replace(committedFixture(t), `"node_count":20`, `"node_count":3`, 1))
+
+ cases := []struct {
+ query string
+ status int
+ code string
+ }{
+ {"?base=heap_base", http.StatusBadRequest, "bad_snapshot_id"},
+ {"?head=heap_base", http.StatusBadRequest, "bad_snapshot_id"},
+ {"?base=..&head=heap_base", http.StatusBadRequest, "bad_snapshot_id"},
+ {"?base=heap_base&head=heap_base&top=-1", http.StatusBadRequest, "bad_top"},
+ {"?base=heap_base&head=heap_base&retained=maybe", http.StatusBadRequest, "bad_retained"},
+ {"?base=heap_missing&head=heap_base", http.StatusNotFound, "memory_snapshot_not_found"},
+ {"?base=heap_base&head=heap_missing", http.StatusNotFound, "memory_snapshot_not_found"},
+ {"?base=heap_base&head=heap_broken", http.StatusUnprocessableEntity, "memory_snapshot_invalid"},
+ }
+ for _, tc := range cases {
+ w := compareRequest(h, tc.query)
+ if w.Code != tc.status || errorCode(t, w) != tc.code {
+ t.Errorf("%s = %d %s, want %d %s", tc.query, w.Code, w.Body.String(), tc.status, tc.code)
+ }
+ }
+ w := compareRequest(h, "?base=heap_base&head=heap_missing")
+ if !strings.Contains(w.Body.String(), `"id":"heap_missing"`) {
+ t.Errorf("not-found refusal does not name the missing id: %s", w.Body.String())
+ }
+
+ off, offDir := memoryHandlers(t, false)
+ seedSnapshot(t, offDir, "heap_base", committedFixture(t))
+ w = compareRequest(off, "?base=heap_base&head=heap_base")
+ if w.Code != http.StatusForbidden || errorCode(t, w) != "memory_disabled" {
+ t.Fatalf("compare with allowMemory off = %d %s, want 403 memory_disabled", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index b592c74b..3ae7e569 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -166,6 +166,14 @@ func (h *Handlers) openAPIDocument(description string) map[string]any {
{"name": "top", "in": "query", "description": "Rows per table (default 20, max 200)", "schema": map[string]string{"type": "integer"}},
}
}
+ if op, ok := paths["/memory/compare"]["get"].(map[string]any); ok {
+ op["parameters"] = []map[string]any{
+ {"name": "base", "in": "query", "required": true, "description": "Id of the earlier heap snapshot", "schema": map[string]string{"type": "string"}},
+ {"name": "head", "in": "query", "required": true, "description": "Id of the later heap snapshot", "schema": map[string]string{"type": "string"}},
+ {"name": "top", "in": "query", "description": "Constructor and duplicate-string rows (default 20, max 200)", "schema": map[string]string{"type": "integer"}},
+ {"name": "retained", "in": "query", "description": "Add retained sizes from a dominator tree of the head snapshot; costs memory and time proportional to its edges", "schema": map[string]string{"type": "boolean"}},
+ }
+ }
info := map[string]any{
"title": "Pinchtab API",
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index 4b5882ee..82fafe24 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -99,6 +99,6 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
"GET /tabs/{id}/network/route", "POST /tabs/{id}/network/route", "DELETE /tabs/{id}/network/route",
}),
"memory": capState(routes.CapMemory, h.memoryEnabled(),
- []string{"POST /memory/snapshot", "POST /tabs/{id}/memory/snapshot", "GET /memory/snapshot/{snapshotId}/summary"}),
+ []string{"POST /memory/snapshot", "POST /tabs/{id}/memory/snapshot", "GET /memory/snapshot/{snapshotId}/summary", "GET /memory/compare"}),
}
}
diff --git a/internal/handlers/tab_guards_test.go b/internal/handlers/tab_guards_test.go
index a707ff4e..a9365f7e 100644
--- a/internal/handlers/tab_guards_test.go
+++ b/internal/handlers/tab_guards_test.go
@@ -562,6 +562,7 @@ var dialogGuardAllowList = map[string]string{
"DELETE /cookies": "browser-side",
"GET /metrics": "browser-side",
"GET /memory/snapshot/{snapshotId}/summary": "server-side",
+ "GET /memory/compare": "server-side",
"GET /network/route": "browser-side",
"POST /network/route": "browser-side",
"DELETE /network/route": "browser-side",
diff --git a/internal/heapsnap/cache.go b/internal/heapsnap/cache.go
new file mode 100644
index 00000000..8a011793
--- /dev/null
+++ b/internal/heapsnap/cache.go
@@ -0,0 +1,48 @@
+package heapsnap
+
+import (
+ "fmt"
+ "os"
+ "sync"
+ "time"
+)
+
+type Cache struct {
+ mu sync.Mutex
+ entries map[string]cacheEntry
+ parse func(path string, opts ParseOptions) (*Aggregate, error)
+}
+
+type cacheEntry struct {
+ size int64
+ modTime time.Time
+ agg *Aggregate
+}
+
+func (c *Cache) Load(path string, retained bool) (*Aggregate, error) {
+ info, err := os.Stat(path)
+ if err != nil {
+ return nil, fmt.Errorf("stat heap snapshot: %w", err)
+ }
+ c.mu.Lock()
+ entry, ok := c.entries[path]
+ parse := c.parse
+ c.mu.Unlock()
+ if ok && entry.size == info.Size() && entry.modTime.Equal(info.ModTime()) && (!retained || entry.agg.Retained != nil) {
+ return entry.agg, nil
+ }
+ if parse == nil {
+ parse = ParseFileWith
+ }
+ agg, err := parse(path, ParseOptions{Retained: retained})
+ if err != nil {
+ return nil, err
+ }
+ c.mu.Lock()
+ if c.entries == nil {
+ c.entries = map[string]cacheEntry{}
+ }
+ c.entries[path] = cacheEntry{size: info.Size(), modTime: info.ModTime(), agg: agg}
+ c.mu.Unlock()
+ return agg, nil
+}
diff --git a/internal/heapsnap/compare.go b/internal/heapsnap/compare.go
new file mode 100644
index 00000000..92c6c27b
--- /dev/null
+++ b/internal/heapsnap/compare.go
@@ -0,0 +1,143 @@
+package heapsnap
+
+import (
+ "errors"
+ "sort"
+)
+
+var ErrRetainedNotParsed = errors.New("head snapshot was parsed without retained sizes")
+
+type Options struct {
+ Top int
+ Retained bool
+}
+
+type Totals struct {
+ ID string `json:"id,omitempty"`
+ NodeCount int `json:"nodeCount"`
+ EdgeCount int `json:"edgeCount"`
+ TotalSelfSize int64 `json:"totalSelfSize"`
+}
+
+type ConstructorDelta struct {
+ Name string `json:"name"`
+ BaseCount int `json:"baseCount"`
+ HeadCount int `json:"headCount"`
+ CountDelta int `json:"countDelta"`
+ BaseSelfSize int64 `json:"baseSelfSize"`
+ HeadSelfSize int64 `json:"headSelfSize"`
+ SizeDelta int64 `json:"sizeDelta"`
+ RetainedSize *int64 `json:"retainedSize,omitempty"`
+}
+
+type Comparison struct {
+ Base Totals `json:"base"`
+ Head Totals `json:"head"`
+ NodeDelta int `json:"nodeDelta"`
+ SizeDelta int64 `json:"sizeDelta"`
+ Changed int `json:"changed"`
+ Constructors []ConstructorDelta `json:"constructors"`
+ NewDuplicateStrings []DuplicateString `json:"newDuplicateStrings"`
+}
+
+func (a *Aggregate) totals() Totals {
+ return Totals{NodeCount: a.NodeCount, EdgeCount: a.EdgeCount, TotalSelfSize: a.TotalSelfSize}
+}
+
+func Compare(base, head *Aggregate, opts Options) (Comparison, error) {
+ if opts.Retained && head.Retained == nil {
+ return Comparison{}, ErrRetainedNotParsed
+ }
+ top := ClampTop(opts.Top)
+
+ rows := map[string]*ConstructorDelta{}
+ row := func(name string) *ConstructorDelta {
+ r := rows[name]
+ if r == nil {
+ r = &ConstructorDelta{Name: name}
+ rows[name] = r
+ }
+ return r
+ }
+ for _, c := range base.Constructors {
+ r := row(c.Name)
+ r.BaseCount, r.BaseSelfSize = c.Count, c.SelfSize
+ }
+ for _, c := range head.Constructors {
+ r := row(c.Name)
+ r.HeadCount, r.HeadSelfSize = c.Count, c.SelfSize
+ }
+ changed := make([]ConstructorDelta, 0, len(rows))
+ for _, r := range rows {
+ r.CountDelta = r.HeadCount - r.BaseCount
+ r.SizeDelta = r.HeadSelfSize - r.BaseSelfSize
+ if r.CountDelta != 0 || r.SizeDelta != 0 {
+ changed = append(changed, *r)
+ }
+ }
+ sort.Slice(changed, func(i, j int) bool { return lessDelta(changed[i], changed[j]) })
+ constructors := changed
+ if len(constructors) > top {
+ constructors = constructors[:top:top]
+ }
+ if opts.Retained {
+ for i := range constructors {
+ size := head.Retained[constructors[i].Name]
+ constructors[i].RetainedSize = &size
+ }
+ }
+
+ return Comparison{
+ Base: base.totals(),
+ Head: head.totals(),
+ NodeDelta: head.NodeCount - base.NodeCount,
+ SizeDelta: head.TotalSelfSize - base.TotalSelfSize,
+ Changed: len(changed),
+ Constructors: constructors,
+ NewDuplicateStrings: newDuplicates(base, head, top),
+ }, nil
+}
+
+func lessDelta(a, b ConstructorDelta) bool {
+ if x, y := abs(a.SizeDelta), abs(b.SizeDelta); x != y {
+ return x > y
+ }
+ if a.SizeDelta != b.SizeDelta {
+ return a.SizeDelta > b.SizeDelta
+ }
+ if x, y := abs(int64(a.CountDelta)), abs(int64(b.CountDelta)); x != y {
+ return x > y
+ }
+ if a.CountDelta != b.CountDelta {
+ return a.CountDelta > b.CountDelta
+ }
+ return a.Name < b.Name
+}
+
+func abs(v int64) int64 {
+ if v < 0 {
+ return -v
+ }
+ return v
+}
+
+func newDuplicates(base, head *Aggregate, top int) []DuplicateString {
+ type key struct {
+ value string
+ length int
+ }
+ inBase := make(map[key]bool, len(base.DuplicateStrings))
+ for _, d := range base.DuplicateStrings {
+ inBase[key{d.Value, d.Length}] = true
+ }
+ out := make([]DuplicateString, 0)
+ for _, d := range head.DuplicateStrings {
+ if len(out) == top {
+ break
+ }
+ if !inBase[key{d.Value, d.Length}] {
+ out = append(out, d)
+ }
+ }
+ return out
+}
diff --git a/internal/heapsnap/compare_test.go b/internal/heapsnap/compare_test.go
new file mode 100644
index 00000000..906fb7ea
--- /dev/null
+++ b/internal/heapsnap/compare_test.go
@@ -0,0 +1,302 @@
+package heapsnap
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+const grownFixturePath = "testdata/grown.heapsnapshot"
+
+func parseFixture(t testing.TB, path string, retained bool) *Aggregate {
+ t.Helper()
+ agg, err := ParseFileWith(path, ParseOptions{Retained: retained})
+ if err != nil {
+ t.Fatalf("parse %s: %v", path, err)
+ }
+ return agg
+}
+
+func TestCompareOverTheFixturesReturnsTheDeltaTableDeterministically(t *testing.T) {
+ want := Comparison{
+ Base: Totals{NodeCount: 20, EdgeCount: 6, TotalSelfSize: 3536},
+ Head: Totals{NodeCount: 15, EdgeCount: 17, TotalSelfSize: 10820},
+ NodeDelta: -5,
+ SizeDelta: 7284,
+ Changed: 7,
+ Constructors: []ConstructorDelta{
+ {Name: "(array)", BaseCount: 1, HeadCount: 2, CountDelta: 1, BaseSelfSize: 800, HeadSelfSize: 10000, SizeDelta: 9200},
+ {Name: "Array", BaseCount: 3, HeadCount: 2, CountDelta: -1, BaseSelfSize: 1664, HeadSelfSize: 64, SizeDelta: -1600},
+ {Name: "HTMLDivElement", BaseCount: 1, CountDelta: -1, BaseSelfSize: 200, SizeDelta: -200},
+ {Name: "(string)", BaseCount: 8, HeadCount: 5, CountDelta: -3, BaseSelfSize: 228, HeadSelfSize: 160, SizeDelta: -68},
+ {Name: "Leaker", HeadCount: 1, CountDelta: 1, HeadSelfSize: 64, SizeDelta: 64},
+ {Name: "(closure)", BaseCount: 1, CountDelta: -1, BaseSelfSize: 64, SizeDelta: -64},
+ {Name: "(system)", BaseCount: 1, CountDelta: -1, BaseSelfSize: 48, SizeDelta: -48},
+ },
+ NewDuplicateStrings: []DuplicateString{
+ {Value: "new-dup-string", Length: 14, Count: 2, SelfSize: 80},
+ },
+ }
+ var first []byte
+ for run := 0; run < 2; run++ {
+ got, err := Compare(parseFixture(t, fixturePath, false), parseFixture(t, grownFixturePath, false), Options{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("run %d comparison =\n%+v\nwant\n%+v", run, got, want)
+ }
+ raw, err := json.Marshal(got)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if run == 0 {
+ first = raw
+ } else if string(raw) != string(first) {
+ t.Fatalf("second run marshalled differently:\n%s\n%s", first, raw)
+ }
+ }
+ if strings.Contains(string(first), "retainedSize") {
+ t.Fatalf("a comparison without retained carries retainedSize: %s", first)
+ }
+}
+
+func TestCompareTopCutsTheTableButCountsEveryChangedConstructor(t *testing.T) {
+ got, err := Compare(parseFixture(t, fixturePath, false), parseFixture(t, grownFixturePath, false), Options{Top: 2})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got.Constructors) != 2 || got.Constructors[0].Name != "(array)" || got.Constructors[1].Name != "Array" {
+ t.Fatalf("top 2 = %+v", got.Constructors)
+ }
+ if got.Changed != 7 {
+ t.Fatalf("changed = %d, want 7", got.Changed)
+ }
+}
+
+func TestCompareOfASnapshotWithItselfReportsNoChange(t *testing.T) {
+ agg := parseFixture(t, grownFixturePath, false)
+ got, err := Compare(agg, agg, Options{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Changed != 0 || len(got.Constructors) != 0 || len(got.NewDuplicateStrings) != 0 || got.SizeDelta != 0 {
+ t.Fatalf("self comparison = %+v", got)
+ }
+ if got.Constructors == nil || got.NewDuplicateStrings == nil {
+ t.Fatal("empty tables must marshal as [] not null")
+ }
+}
+
+func TestRetainedSizesFollowTheDominatorTree(t *testing.T) {
+ agg := parseFixture(t, grownFixturePath, true)
+ want := map[string]int64{
+ "(synthetic)": 10820,
+ "Window": 10440,
+ "Leaker": 10168,
+ "Array": 10064,
+ "(array)": 10000,
+ "(compiled code)": 300,
+ "(string)": 160,
+ "Object": 152,
+ }
+ if !reflect.DeepEqual(agg.Retained, want) {
+ t.Fatalf("retained = %v, want %v", agg.Retained, want)
+ }
+
+ plain := parseFixture(t, grownFixturePath, false)
+ if plain.Retained != nil {
+ t.Fatalf("a parse without retained computed %v", plain.Retained)
+ }
+ agg.Retained = nil
+ if !reflect.DeepEqual(agg, plain) {
+ t.Fatalf("retained parse changed the aggregate:\n%+v\n%+v", agg, plain)
+ }
+}
+
+func TestCompareWithRetainedAnnotatesTheReturnedRows(t *testing.T) {
+ got, err := Compare(parseFixture(t, fixturePath, false), parseFixture(t, grownFixturePath, true), Options{Top: 5, Retained: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]int64{"(array)": 10000, "Array": 10064, "HTMLDivElement": 0, "(string)": 160, "Leaker": 10168}
+ if len(got.Constructors) != len(want) {
+ t.Fatalf("rows = %+v", got.Constructors)
+ }
+ for _, row := range got.Constructors {
+ if row.RetainedSize == nil || *row.RetainedSize != want[row.Name] {
+ t.Errorf("%s retainedSize = %v, want %d", row.Name, row.RetainedSize, want[row.Name])
+ }
+ }
+ raw, _ := json.Marshal(got.Constructors[2])
+ if !strings.Contains(string(raw), `"retainedSize":0`) {
+ t.Fatalf("a requested zero retained size must still be present: %s", raw)
+ }
+
+ if _, err := Compare(parseFixture(t, fixturePath, false), parseFixture(t, grownFixturePath, false), Options{Retained: true}); !errors.Is(err, ErrRetainedNotParsed) {
+ t.Fatalf("err = %v, want ErrRetainedNotParsed", err)
+ }
+}
+
+func TestRetainedParseRefusesAnInconsistentEdgeTable(t *testing.T) {
+ src, err := os.ReadFile(grownFixturePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cases := map[string]string{
+ "to_node off a node boundary": strings.Replace(string(src), "\"edges\":[1,1,7", "\"edges\":[1,1,8", 1),
+ "to_node past the last node": strings.Replace(string(src), "\"edges\":[1,1,7", "\"edges\":[1,1,700", 1),
+ "edge_count sum too small": strings.Replace(string(src), "\"nodes\":[9,1,1,0,5", "\"nodes\":[9,1,1,0,4", 1),
+ }
+ for name, body := range cases {
+ t.Run(name, func(t *testing.T) {
+ _, err := ParseWith(strings.NewReader(body), ParseOptions{Retained: true})
+ var pe *ParseError
+ if !errors.As(err, &pe) || pe.Section != SectionEdges {
+ t.Fatalf("err = %v, want a ParseError naming edges", err)
+ }
+ })
+ }
+}
+
+func TestCacheParsesEachSnapshotOnceUntilItChanges(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "heap_1"+Ext)
+ src, err := os.ReadFile(grownFixturePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, src, 0600); err != nil {
+ t.Fatal(err)
+ }
+ var calls []bool
+ c := &Cache{parse: func(p string, opts ParseOptions) (*Aggregate, error) {
+ calls = append(calls, opts.Retained)
+ return ParseFileWith(p, opts)
+ }}
+
+ first, err := c.Load(path, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ again, err := c.Load(path, false)
+ if err != nil || again != first {
+ t.Fatalf("second load = %p, %v; want the cached %p", again, err, first)
+ }
+ withRetained, err := c.Load(path, true)
+ if err != nil || withRetained.Retained == nil {
+ t.Fatalf("retained load = %+v, %v", withRetained, err)
+ }
+ if plain, _ := c.Load(path, false); plain != withRetained {
+ t.Fatal("a plain load after a retained one must reuse the richer entry")
+ }
+ later := time.Now().Add(time.Hour)
+ if err := os.Chtimes(path, later, later); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := c.Load(path, false); err != nil {
+ t.Fatal(err)
+ }
+ if want := []bool{false, true, false}; !reflect.DeepEqual(calls, want) {
+ t.Fatalf("parse calls = %v, want %v", calls, want)
+ }
+ if _, err := c.Load(filepath.Join(dir, "missing"+Ext), false); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("missing file err = %v, want os.ErrNotExist", err)
+ }
+}
+
+func writeSyntheticSnapshot(tb testing.TB, path string, targetBytes int) {
+ tb.Helper()
+ f, err := os.Create(path)
+ if err != nil {
+ tb.Fatal(err)
+ }
+ defer func() { _ = f.Close() }()
+ const perObject, rootEvery = 3, 16
+ objects := targetBytes / 115
+ nodes := 1 + objects*perObject
+ rootEdges := (objects + rootEvery - 1) / rootEvery
+ edges := rootEdges + objects*4
+ objectOffset := func(i int) int { return (1 + i*perObject) * 7 }
+ meta := strings.SplitN(readFixtureTB(tb), `"node_count"`, 2)[0]
+ var b strings.Builder
+ b.WriteString(meta)
+ fmt.Fprintf(&b, `"node_count":%d,"edge_count":%d,"trace_function_count":0},`+"\n", nodes, edges)
+ fmt.Fprintf(&b, `"nodes":[9,1,1,0,%d,0,0`, rootEdges)
+ id := 3
+ for i := 0; i < objects; i++ {
+ fmt.Fprintf(&b, "\n,3,%d,%d,%d,4,0,0", 2+i%4, id, 32+i%64)
+ fmt.Fprintf(&b, "\n,1,6,%d,%d,0,0,0", id+2, 16+i%512)
+ fmt.Fprintf(&b, "\n,2,%d,%d,%d,0,0,0", 6+i%3, id+4, 20+i%8)
+ id += 6
+ }
+ b.WriteString("],\n\"edges\":[")
+ sep := ""
+ for i := 0; i < objects; i += rootEvery {
+ fmt.Fprintf(&b, "%s1,%d,%d", sep, i, objectOffset(i))
+ sep = "\n,"
+ }
+ for i := 0; i < objects; i++ {
+ obj := 1 + i*perObject
+ fmt.Fprintf(&b, "\n,3,8,%d\n,2,7,%d\n,2,6,%d\n,2,8,%d", (obj+1)*7, (obj+2)*7, objectOffset((i*7919+1)%objects), objectOffset((i+1)%objects))
+ }
+ b.WriteString("],\n\"strings\":[\"<dummy>\",\"(GC roots)\",\"Window\",\"Array\",\"Object\",\"Leaker\",\"hello\",\"leak\",\"items\"]}\n")
+ if _, err := f.WriteString(b.String()); err != nil {
+ tb.Fatal(err)
+ }
+ if info, err := f.Stat(); err == nil && targetBytes >= 1<<20 && info.Size() < int64(targetBytes)*9/10 {
+ tb.Fatalf("synthetic snapshot is %d bytes, want about %d", info.Size(), targetBytes)
+ }
+}
+
+func readFixtureTB(tb testing.TB) string {
+ tb.Helper()
+ raw, err := os.ReadFile(fixturePath)
+ if err != nil {
+ tb.Fatal(err)
+ }
+ return string(raw)
+}
+
+func TestSyntheticSnapshotParsesWithAndWithoutRetained(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "synthetic"+Ext)
+ writeSyntheticSnapshot(t, path, 64<<10)
+ plain := parseFixture(t, path, false)
+ rich := parseFixture(t, path, true)
+ if rich.Retained["(synthetic)"] != plain.TotalSelfSize {
+ t.Fatalf("root retains %d, want every byte %d", rich.Retained["(synthetic)"], plain.TotalSelfSize)
+ }
+}
+
+func benchmarkCompare(b *testing.B, retained bool) {
+ path := filepath.Join(b.TempDir(), "synthetic"+Ext)
+ writeSyntheticSnapshot(b, path, 20<<20)
+ info, err := os.Stat(path)
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.SetBytes(info.Size())
+ base, err := ParseFile(path)
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ head, err := ParseFileWith(path, ParseOptions{Retained: retained})
+ if err != nil {
+ b.Fatal(err)
+ }
+ if _, err := Compare(base, head, Options{Retained: retained}); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkCompare20MB(b *testing.B) { benchmarkCompare(b, false) }
+func BenchmarkCompare20MBRetained(b *testing.B) { benchmarkCompare(b, true) }
diff --git a/internal/heapsnap/graph.go b/internal/heapsnap/graph.go
new file mode 100644
index 00000000..ae458cd5
--- /dev/null
+++ b/internal/heapsnap/graph.go
@@ -0,0 +1,298 @@
+package heapsnap
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+)
+
+const rootNode = 0
+
+type graph struct {
+ classKey []int64
+ selfSize []int64
+ edgeCount []int32
+ firstEdge []int32
+ to []int32
+}
+
+type edgeLayout struct {
+ fields int
+ typeAt int
+ toAt int
+ weak int64
+ shortcut int64
+}
+
+func (h *Header) edgeLayout() (edgeLayout, error) {
+ l := edgeLayout{fields: len(h.Meta.EdgeFields), typeAt: -1, toAt: -1, weak: -1, shortcut: -1}
+ for i, f := range h.Meta.EdgeFields {
+ switch f {
+ case "type":
+ l.typeAt = i
+ case "to_node":
+ l.toAt = i
+ }
+ }
+ if l.typeAt < 0 || l.toAt < 0 {
+ return l, &ParseError{Section: SectionMeta, Err: fmt.Errorf("edge_fields %v lack type or to_node", h.Meta.EdgeFields)}
+ }
+ if len(h.Meta.EdgeTypes) <= l.typeAt {
+ return l, &ParseError{Section: SectionMeta, Err: errors.New("edge_types has no entry for the type field")}
+ }
+ var names []string
+ if err := json.Unmarshal(h.Meta.EdgeTypes[l.typeAt], &names); err != nil {
+ return l, &ParseError{Section: SectionMeta, Err: fmt.Errorf("edge_types type enum: %w", err)}
+ }
+ for i, name := range names {
+ switch name {
+ case "weak":
+ l.weak = int64(i)
+ case "shortcut":
+ l.shortcut = int64(i)
+ }
+ }
+ return l, nil
+}
+
+func classKeyFor(kind string, typ, name int64) int64 {
+ if kind == "object" || kind == "native" {
+ return name
+ }
+ return -(typ + 1)
+}
+
+func (g *graph) addNode(key, size, edges int64) error {
+ if edges < 0 || edges > math.MaxInt32 {
+ return &ParseError{Section: SectionNodes, Err: fmt.Errorf("edge_count %d out of range", edges)}
+ }
+ g.classKey = append(g.classKey, key)
+ g.selfSize = append(g.selfSize, size)
+ g.edgeCount = append(g.edgeCount, int32(edges))
+ return nil
+}
+
+type edgeReader struct {
+ g *graph
+ layout edgeLayout
+ nodeSize int
+ field int
+ typ int64
+ target int64
+ owner int
+ left int32
+}
+
+func (g *graph) edgeReader(layout edgeLayout, nodeFields int) *edgeReader {
+ g.firstEdge = make([]int32, len(g.selfSize)+1)
+ return &edgeReader{g: g, layout: layout, nodeSize: nodeFields, owner: -1}
+}
+
+func (r *edgeReader) value(v int64) error {
+ switch r.field {
+ case r.layout.typeAt:
+ r.typ = v
+ case r.layout.toAt:
+ r.target = v
+ }
+ r.field++
+ if r.field < r.layout.fields {
+ return nil
+ }
+ r.field = 0
+ return r.edge()
+}
+
+func (r *edgeReader) edge() error {
+ g := r.g
+ n := len(g.selfSize)
+ for r.left == 0 {
+ r.owner++
+ if r.owner >= n {
+ return &ParseError{Section: SectionEdges, Err: errors.New("more edges than the nodes' edge_count fields declare")}
+ }
+ g.firstEdge[r.owner] = int32(len(g.to))
+ r.left = g.edgeCount[r.owner]
+ }
+ r.left--
+ if r.target < 0 || r.target%int64(r.nodeSize) != 0 || r.target/int64(r.nodeSize) >= int64(n) {
+ return &ParseError{Section: SectionEdges, Err: fmt.Errorf("to_node %d is not a node offset", r.target)}
+ }
+ if r.typ == r.layout.weak || (r.typ == r.layout.shortcut && r.owner != rootNode) {
+ return nil
+ }
+ g.to = append(g.to, int32(r.target/int64(r.nodeSize)))
+ return nil
+}
+
+func (r *edgeReader) finish() error {
+ g := r.g
+ if r.left != 0 {
+ return &ParseError{Section: SectionEdges, Err: errors.New("fewer edges than the nodes' edge_count fields declare")}
+ }
+ for k := r.owner + 1; k < len(g.selfSize); k++ {
+ if g.edgeCount[k] != 0 {
+ return &ParseError{Section: SectionEdges, Err: errors.New("fewer edges than the nodes' edge_count fields declare")}
+ }
+ g.firstEdge[k] = int32(len(g.to))
+ }
+ g.firstEdge[len(g.selfSize)] = int32(len(g.to))
+ return nil
+}
+
+func (g *graph) postOrder() (order []int32, index []int32) {
+ n := len(g.selfSize)
+ index = make([]int32, n)
+ for i := range index {
+ index[i] = -1
+ }
+ if n == 0 {
+ return nil, index
+ }
+ visited := make([]bool, n)
+ order = make([]int32, 0, n)
+ stack := []int32{rootNode}
+ cursor := []int32{g.firstEdge[rootNode]}
+ visited[rootNode] = true
+ for len(stack) > 0 {
+ top := len(stack) - 1
+ node := stack[top]
+ if cursor[top] < g.firstEdge[node+1] {
+ next := g.to[cursor[top]]
+ cursor[top]++
+ if !visited[next] {
+ visited[next] = true
+ stack = append(stack, next)
+ cursor = append(cursor, g.firstEdge[next])
+ }
+ continue
+ }
+ index[node] = int32(len(order))
+ order = append(order, node)
+ stack = stack[:top]
+ cursor = cursor[:top]
+ }
+ return order, index
+}
+
+func (g *graph) dominators(order, index []int32) []int32 {
+ m := len(order)
+ predStart := make([]int32, m+1)
+ for _, u := range order {
+ for e := g.firstEdge[u]; e < g.firstEdge[u+1]; e++ {
+ predStart[index[g.to[e]]+1]++
+ }
+ }
+ for i := 1; i <= m; i++ {
+ predStart[i] += predStart[i-1]
+ }
+ preds := make([]int32, predStart[m])
+ fill := append([]int32(nil), predStart[:m]...)
+ for _, u := range order {
+ for e := g.firstEdge[u]; e < g.firstEdge[u+1]; e++ {
+ v := index[g.to[e]]
+ preds[fill[v]] = index[u]
+ fill[v]++
+ }
+ }
+
+ doms := make([]int32, m)
+ for i := range doms {
+ doms[i] = -1
+ }
+ root := int32(m - 1)
+ doms[root] = root
+ intersect := func(a, b int32) int32 {
+ for a != b {
+ for a < b {
+ a = doms[a]
+ }
+ for b < a {
+ b = doms[b]
+ }
+ }
+ return a
+ }
+ for changed := true; changed; {
+ changed = false
+ for i := root - 1; i >= 0; i-- {
+ idom := int32(-1)
+ for _, p := range preds[predStart[i]:predStart[i+1]] {
+ if doms[p] < 0 {
+ continue
+ }
+ if idom < 0 {
+ idom = p
+ } else {
+ idom = intersect(p, idom)
+ }
+ }
+ if idom != doms[i] {
+ doms[i] = idom
+ changed = true
+ }
+ }
+ }
+ return doms
+}
+
+func (g *graph) classRetained(classOf []int32, classes int) []int64 {
+ order, index := g.postOrder()
+ m := len(order)
+ out := make([]int64, classes)
+ if m == 0 {
+ return out
+ }
+ doms := g.dominators(order, index)
+ retained := make([]int64, m)
+ for i, node := range order {
+ retained[i] = g.selfSize[node]
+ }
+ root := int32(m - 1)
+ for i := int32(0); i < root; i++ {
+ retained[doms[i]] += retained[i]
+ }
+
+ childStart := make([]int32, m+1)
+ for i := int32(0); i < root; i++ {
+ childStart[doms[i]+1]++
+ }
+ for i := 1; i <= m; i++ {
+ childStart[i] += childStart[i-1]
+ }
+ children := make([]int32, childStart[m])
+ fill := append([]int32(nil), childStart[:m]...)
+ for i := int32(0); i < root; i++ {
+ children[fill[doms[i]]] = i
+ fill[doms[i]]++
+ }
+
+ active := make([]int32, classes)
+ enter := func(i int32) {
+ class := classOf[order[i]]
+ if active[class] == 0 {
+ out[class] += retained[i]
+ }
+ active[class]++
+ }
+ stack := []int32{root}
+ cursor := []int32{childStart[root]}
+ enter(root)
+ for len(stack) > 0 {
+ top := len(stack) - 1
+ i := stack[top]
+ if cursor[top] < childStart[i+1] {
+ child := children[cursor[top]]
+ cursor[top]++
+ enter(child)
+ stack = append(stack, child)
+ cursor = append(cursor, childStart[child])
+ continue
+ }
+ active[classOf[order[i]]]--
+ stack = stack[:top]
+ cursor = cursor[:top]
+ }
+ return out
+}
diff --git a/internal/heapsnap/parse.go b/internal/heapsnap/parse.go
index e4d66982..8a0b8a67 100644
--- a/internal/heapsnap/parse.go
+++ b/internal/heapsnap/parse.go
@@ -54,15 +54,16 @@ type Header struct {
}
type nodeLayout struct {
- fields int
- typeAt int
- nameAt int
- sizeAt int
- typeName []string
+ fields int
+ typeAt int
+ nameAt int
+ sizeAt int
+ edgeCountAt int
+ typeName []string
}
func (h *Header) layout() (nodeLayout, error) {
- l := nodeLayout{fields: len(h.Meta.NodeFields), typeAt: -1, nameAt: -1, sizeAt: -1}
+ l := nodeLayout{fields: len(h.Meta.NodeFields), typeAt: -1, nameAt: -1, sizeAt: -1, edgeCountAt: -1}
for i, f := range h.Meta.NodeFields {
switch f {
case "type":
@@ -71,6 +72,8 @@ func (h *Header) layout() (nodeLayout, error) {
l.nameAt = i
case "self_size":
l.sizeAt = i
+ case "edge_count":
+ l.edgeCountAt = i
}
}
if l.typeAt < 0 || l.nameAt < 0 || l.sizeAt < 0 {
@@ -167,6 +170,11 @@ type Aggregate struct {
TotalSelfSize int64
Constructors []Constructor
DuplicateStrings []DuplicateString
+ Retained map[string]int64
+}
+
+type ParseOptions struct {
+ Retained bool
}
type bucket struct {
@@ -186,9 +194,14 @@ type parser struct {
byString map[int64]*bucket
strings map[int64]string
seen map[string]bool
+ graph *graph
}
func Parse(r io.Reader) (*Aggregate, error) {
+ return ParseWith(r, ParseOptions{})
+}
+
+func ParseWith(r io.Reader, opts ParseOptions) (*Aggregate, error) {
p := &parser{
s: newScanner(r),
byName: map[int64]*bucket{},
@@ -197,6 +210,9 @@ func Parse(r io.Reader) (*Aggregate, error) {
strings: map[int64]string{},
seen: map[string]bool{},
}
+ if opts.Retained {
+ p.graph = &graph{}
+ }
if err := p.document(); err != nil {
return nil, err
}
@@ -204,12 +220,16 @@ func Parse(r io.Reader) (*Aggregate, error) {
}
func ParseFile(path string) (*Aggregate, error) {
+ return ParseFileWith(path, ParseOptions{})
+}
+
+func ParseFileWith(path string, opts ParseOptions) (*Aggregate, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open heap snapshot: %w", err)
}
defer func() { _ = f.Close() }()
- return Parse(f)
+ return ParseWith(f, opts)
}
func (p *parser) document() error {
@@ -276,7 +296,10 @@ func (p *parser) nodes() error {
return &ParseError{Section: SectionNodes, Err: errors.New("appears before snapshot.meta")}
}
l := p.layout
- var typ, name, size int64
+ if p.graph != nil && l.edgeCountAt < 0 {
+ return &ParseError{Section: SectionMeta, Err: fmt.Errorf("node_fields %v lack edge_count, which retained sizes need", p.header.Meta.NodeFields)}
+ }
+ var typ, name, size, edges int64
field := 0
count, err := p.s.intArray(func(v int64) error {
switch field {
@@ -286,13 +309,15 @@ func (p *parser) nodes() error {
name = v
case l.sizeAt:
size = v
+ case l.edgeCountAt:
+ edges = v
}
field++
if field < l.fields {
return nil
}
field = 0
- return p.node(typ, name, size)
+ return p.node(typ, name, size, edges)
})
if err != nil {
return sectionError(SectionNodes, err)
@@ -307,12 +332,17 @@ func (p *parser) nodes() error {
return nil
}
-func (p *parser) node(typ, name, size int64) error {
+func (p *parser) node(typ, name, size, edges int64) error {
if typ < 0 || int(typ) >= len(p.layout.typeName) {
return &ParseError{Section: SectionNodes, Err: fmt.Errorf("node type %d outside node_types", typ)}
}
p.totalSize += size
kind := p.layout.typeName[typ]
+ if p.graph != nil {
+ if err := p.graph.addNode(classKeyFor(kind, typ, name), size, edges); err != nil {
+ return err
+ }
+ }
switch kind {
case "object", "native":
add(p.byName, name, size)
@@ -345,7 +375,20 @@ func (p *parser) edges() error {
if p.header == nil {
return &ParseError{Section: SectionEdges, Err: errors.New("appears before snapshot.meta")}
}
- count, err := p.s.intArray(func(int64) error { return nil })
+ visit := func(int64) error { return nil }
+ var reader *edgeReader
+ if p.graph != nil {
+ if !p.seen[SectionNodes] {
+ return &ParseError{Section: SectionEdges, Err: errors.New("appears before nodes, which retained sizes need")}
+ }
+ layout, err := p.header.edgeLayout()
+ if err != nil {
+ return err
+ }
+ reader = p.graph.edgeReader(layout, p.layout.fields)
+ visit = reader.value
+ }
+ count, err := p.s.intArray(visit)
if err != nil {
return sectionError(SectionEdges, err)
}
@@ -357,6 +400,9 @@ func (p *parser) edges() error {
if edges := count / fields; edges != p.header.EdgeCount {
return &ParseError{Section: SectionEdges, Err: fmt.Errorf("holds %d edges, snapshot.edge_count says %d", edges, p.header.EdgeCount)}
}
+ if reader != nil {
+ return reader.finish()
+ }
return nil
}
@@ -451,9 +497,52 @@ func (p *parser) aggregate() (*Aggregate, error) {
sort.Slice(agg.DuplicateStrings, func(i, j int) bool {
return lessDuplicate(agg.DuplicateStrings[i], agg.DuplicateStrings[j])
})
+ if p.graph != nil {
+ retained, err := p.retained()
+ if err != nil {
+ return nil, err
+ }
+ agg.Retained = retained
+ }
return agg, nil
}
+func (p *parser) classNameFor(key int64) (string, error) {
+ if key >= 0 {
+ return p.lookup(key)
+ }
+ return className(p.layout.typeName[-key-1]), nil
+}
+
+func (p *parser) retained() (map[string]int64, error) {
+ ids := map[int64]int32{}
+ byName := map[string]int32{}
+ var names []string
+ classOf := make([]int32, len(p.graph.classKey))
+ for node, key := range p.graph.classKey {
+ id, ok := ids[key]
+ if !ok {
+ name, err := p.classNameFor(key)
+ if err != nil {
+ return nil, err
+ }
+ if id, ok = byName[name]; !ok {
+ id = int32(len(names))
+ names = append(names, name)
+ byName[name] = id
+ }
+ ids[key] = id
+ }
+ classOf[node] = id
+ }
+ sizes := p.graph.classRetained(classOf, len(names))
+ out := make(map[string]int64, len(names))
+ for id, name := range names {
+ out[name] = sizes[id]
+ }
+ return out, nil
+}
+
const MaxValueRunes = 120
func truncateValue(v string) string {
diff --git a/internal/heapsnap/testdata/grown.heapsnapshot b/internal/heapsnap/testdata/grown.heapsnapshot
new file mode 100644
index 00000000..e60ddeb5
--- /dev/null
+++ b/internal/heapsnap/testdata/grown.heapsnapshot
@@ -0,0 +1,48 @@
+{"snapshot":{"meta":{"node_fields":["type","name","id","self_size","edge_count","trace_node_id","detachedness"],"node_types":[["hidden","array","string","object","code","closure","regexp","number","native","synthetic","concatenated string","sliced string","symbol","bigint","object shape"],"string","number","number","number","number","number"],"edge_fields":["type","name_or_index","to_node"],"edge_types":[["context","element","property","internal","hidden","shortcut","weak"],"string_or_number","node"],"trace_function_info_fields":["function_id","name","script_name","script_id","line","column"],"trace_node_fields":["id","function_info_index","count","size","children"],"sample_fields":["timestamp_us","last_assigned_id"],"location_fields":["object_index","script_id","line","column"]},"node_count":15,"edge_count":17,"trace_function_count":0},
+"nodes":[9,1,1,0,5,0,0
+,3,2,3,120,2,0,0
+,3,9,5,64,3,0,0
+,3,3,7,32,2,0,0
+,3,3,9,32,2,0,0
+,3,4,11,56,2,0,0
+,3,4,13,56,1,0,0
+,1,8,15,4000,0,0,0
+,1,8,17,6000,0,0,0
+,2,10,19,40,0,0,0
+,2,10,21,40,0,0,0
+,2,6,23,20,0,0,0
+,2,6,25,20,0,0,0
+,4,6,27,300,0,0,0
+,2,5,29,40,0,0,0],
+"edges":[1,1,7
+,1,2,77
+,1,3,84
+,1,4,91
+,1,5,98
+,2,7,14
+,2,8,35
+,1,0,21
+,1,1,28
+,6,0,70
+,1,0,49
+,2,6,63
+,1,0,56
+,2,6,63
+,2,8,42
+,2,7,70
+,2,7,70],
+"trace_function_infos":[],
+"trace_tree":[],
+"samples":[],
+"locations":[],
+"strings":["<dummy>",
+"(GC roots)",
+"Window",
+"Array",
+"Object",
+"secret-token-abc",
+"hello",
+"leak",
+"items",
+"Leaker",
+"new-dup-string"]}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index cdb21ccb..08f377f2 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -35,6 +35,7 @@ func rawHandlerMap(c *Client) map[string]func(context.Context, mcp.CallToolReque
"pinchtab_a11y_audit": handleA11yAudit(c),
"pinchtab_memory": handleMemory(c),
"pinchtab_memory_snapshot": handleMemorySnapshot(c),
+ "pinchtab_memory_compare": handleMemoryCompare(c),
"pinchtab_click": handleAction(c, "click"),
"pinchtab_type": handleAction(c, "type"),
diff --git a/internal/mcp/routing_test.go b/internal/mcp/routing_test.go
index 32ed7b93..9e620c61 100644
--- a/internal/mcp/routing_test.go
+++ b/internal/mcp/routing_test.go
@@ -26,6 +26,7 @@ var browserToolArgs = map[string]map[string]any{
"pinchtab_a11y_audit": {},
"pinchtab_memory": {},
"pinchtab_memory_snapshot": {},
+ "pinchtab_memory_compare": {"base": "heap_a", "head": "heap_b"},
"pinchtab_click": {"selector": "#go"},
"pinchtab_type": {"selector": "#q", "text": "hello"},
"pinchtab_hover": {"selector": "#go"},
diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go
index afea12aa..7894c130 100644
--- a/internal/mcp/server_test.go
+++ b/internal/mcp/server_test.go
@@ -19,8 +19,8 @@ func TestNewServer(t *testing.T) {
func TestNewServerRegistersAllTools(t *testing.T) {
_ = NewServer("http://localhost:9867", "")
tools := allTools()
- if len(tools) != 46 {
- t.Errorf("expected 46 tools, got %d — if a tool was added or removed, update this count and the totals in docs/mcp.md", len(tools))
+ if len(tools) != 47 {
+ t.Errorf("expected 47 tools, got %d — if a tool was added or removed, update this count and the totals in docs/mcp.md", len(tools))
}
}
diff --git a/internal/mcp/testdata/preamble_budget.json b/internal/mcp/testdata/preamble_budget.json
index d3edf4b7..b7ceaa6b 100644
--- a/internal/mcp/testdata/preamble_budget.json
+++ b/internal/mcp/testdata/preamble_budget.json
@@ -2,7 +2,7 @@
{
"surface": "mcp:allTools",
"minBytes": 18092,
- "maxBytes": 46400,
+ "maxBytes": 47200,
"takenOn": "2026-09-13",
"commit": "9b6705a2"
},
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 9027c6fd..e23d4ab1 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -387,5 +387,6 @@ func allTools() []mcp.Tool {
a11yAuditTool(),
memoryTool(),
memorySnapshotTool(),
+ memoryCompareTool(),
}
}
diff --git a/internal/mcp/tools_memory.go b/internal/mcp/tools_memory.go
index b4201667..7ab0c2c7 100644
--- a/internal/mcp/tools_memory.go
+++ b/internal/mcp/tools_memory.go
@@ -31,6 +31,36 @@ func memorySnapshotTool() mcp.Tool {
)
}
+func memoryCompareTool() mcp.Tool {
+ return mcp.NewTool("pinchtab_memory_compare",
+ mcp.WithDescription("Compare two pinchtab_memory_snapshot ids: per-constructor count and self-size deltas, largest first, and new duplicate strings. Snapshot, act, snapshot, compare to find a leak. Needs security.allowMemory."),
+ mcp.WithString("base", mcp.Required(), mcp.Description("Earlier snapshot id")),
+ mcp.WithString("head", mcp.Required(), mcp.Description("Later snapshot id")),
+ mcp.WithNumber("top", mcp.Description("Rows (default 20)")),
+ mcp.WithBoolean("retained", mcp.Description("Add retained sizes (slower)")),
+ browserParam(),
+ )
+}
+
+func handleMemoryCompare(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ base, head := optString(r, "base"), optString(r, "head")
+ if base == "" || head == "" {
+ return mcp.NewToolResultError("base and head are required: pass two ids pinchtab_memory_snapshot returned"), nil
+ }
+ q := url.Values{}
+ q.Set("base", base)
+ q.Set("head", head)
+ if top, ok := optInt(r, "top"); ok && top > 0 {
+ q.Set("top", strconv.Itoa(top))
+ }
+ if retained, ok := optBool(r, "retained"); ok && retained {
+ q.Set("retained", "true")
+ }
+ return toolResult(c.withTimeout(memorySnapshotMCPTimeout).Get(ctx, "/memory/compare", routedQuery(r, q)))
+ }
+}
+
func handleMemory(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
q := url.Values{}
diff --git a/internal/mcp/tools_memory_test.go b/internal/mcp/tools_memory_test.go
index e15c9ef4..d2b579aa 100644
--- a/internal/mcp/tools_memory_test.go
+++ b/internal/mcp/tools_memory_test.go
@@ -29,6 +29,11 @@ func memoryMockServer(t *testing.T, seen *[]string, snapshotStatus int) *httptes
"nodeCount": 20, "edgeCount": 6,
"topBySize": []map[string]any{{"name": "Array", "count": 3, "selfSize": 1664}},
})
+ case "/memory/compare":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "base": map[string]any{"id": r.URL.Query().Get("base")}, "head": map[string]any{"id": r.URL.Query().Get("head")},
+ "constructors": []map[string]any{{"name": "(array)", "sizeDelta": 15728640}},
+ })
default:
w.WriteHeader(http.StatusNotFound)
}
@@ -87,3 +92,24 @@ func TestMemorySnapshotToolSurfacesTheCapabilityRefusal(t *testing.T) {
t.Fatalf("refusal text = %q, want the capability code", text)
}
}
+
+func TestMemoryCompareToolForwardsTheIdsTopAndRetained(t *testing.T) {
+ var seen []string
+ srv := memoryMockServer(t, &seen, http.StatusOK)
+ defer srv.Close()
+
+ body := resultJSON(t, callSharedTool(t, NewClient(srv.URL, ""), "pinchtab_memory_compare", map[string]any{"base": "heap_a", "head": "heap_b", "top": float64(5), "retained": true}))
+ if len(seen) != 1 || seen[0] != "GET /memory/compare?base=heap_a&head=heap_b&retained=true&top=5" {
+ t.Fatalf("requests = %v", seen)
+ }
+ rows, _ := body["constructors"].([]any)
+ if len(rows) != 1 {
+ t.Fatalf("result = %v", body)
+ }
+
+ seen = nil
+ result := callSharedTool(t, NewClient(srv.URL, ""), "pinchtab_memory_compare", map[string]any{"base": "heap_a"})
+ if !result.IsError || len(seen) != 0 {
+ t.Fatalf("a compare without head = error %v after requests %v, want a local refusal", result.IsError, seen)
+ }
+}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 21efe901..731fa41d 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -154,6 +154,7 @@ var coreEndpoints = []Endpoint{
{"GET", "/memory", "JavaScript heap usage and DOM counters", CapNone, true},
{"POST", "/memory/snapshot", "Take a V8 heap snapshot to a server-side file", CapMemory, true},
{"GET", "/memory/snapshot/{snapshotId}/summary", "Summarize a saved heap snapshot", CapMemory, false},
+ {"GET", "/memory/compare", "Compare two saved heap snapshots by constructor growth", CapMemory, false},
{"GET", "/a11y/audit", "Accessibility findings and score", CapNone, true},
{"POST", "/audit/page", "Audit a single page with browser enrichment", CapNone, false},
{"POST", "/audit", "Run a multi-page site audit", CapNone, false},
diff --git a/tests/e2e/scenarios/api/memory-basic.sh b/tests/e2e/scenarios/api/memory-basic.sh
index ebf1d882..9df88f26 100644
--- a/tests/e2e/scenarios/api/memory-basic.sh
+++ b/tests/e2e/scenarios/api/memory-basic.sh
@@ -99,3 +99,61 @@ assert_json_eq "$RESULT" '.code' 'memory_snapshot_not_found' "unknown id is memo
pt_post /action -d "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"selector\":\"#release\"}"
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "memory: compare puts (array) growth of three leaks at the top, and a negative delta after release"
+
+pt_post /memory/snapshot -d "{\"tabId\":\"${TAB_ID}\"}"
+assert_ok "baseline snapshot"
+BASE_ID=$(echo "$RESULT" | jq -r '.id')
+
+for i in 1 2 3; do
+ pt_post /action -d "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"selector\":\"#leak\"}"
+ assert_ok "leak click ${i}"
+done
+
+pt_post /memory/snapshot -d "{\"tabId\":\"${TAB_ID}\"}"
+assert_ok "snapshot after three leaks"
+LEAK_ID=$(echo "$RESULT" | jq -r '.id')
+
+pt_get "/memory/compare?base=${BASE_ID}&head=${LEAK_ID}&top=20"
+assert_ok "compare baseline to leaked"
+assert_json_eq "$RESULT" '.base.id' "$BASE_ID" "compare names the base snapshot"
+assert_json_eq "$RESULT" '.head.id' "$LEAK_ID" "compare names the head snapshot"
+assert_json_eq "$RESULT" '.constructors[0].name' '(array)' "the leaked double arrays' backing stores top the table"
+assert_json_jq "$RESULT" ".constructors[0].sizeDelta >= $((10 * MB))" \
+ "top row grew by at least 10 MB" "top row grew by less than 10 MB"
+assert_json_jq "$RESULT" '.sizeDelta > 0 and .changed >= 1' "totals report growth" "totals report no growth"
+assert_json_jq "$RESULT" '[.constructors[] | has("retainedSize")] | any | not' \
+ "no retainedSize without retained=true" "retainedSize present without retained=true"
+assert_json_exists "$RESULT" '.newDuplicateStrings' "compare lists new duplicate strings"
+
+pt_get "/memory/compare?base=${BASE_ID}&head=${LEAK_ID}&top=5&retained=true"
+assert_ok "compare with retained sizes"
+assert_json_eq "$RESULT" '.retained' 'true' "response says retained"
+assert_json_jq "$RESULT" "[.constructors[] | has(\"retainedSize\")] | all" \
+ "every row carries retainedSize" "a row lacks retainedSize"
+assert_json_jq "$RESULT" ".constructors[0].retainedSize >= $((10 * MB))" \
+ "(array) retains at least 10 MB" "(array) retains under 10 MB"
+
+pt_post /action -d "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"selector\":\"#release\"}"
+assert_ok "release click"
+pt_get "/memory?tabId=${TAB_ID}&gc=true"
+assert_ok "collect garbage after release"
+
+pt_post /memory/snapshot -d "{\"tabId\":\"${TAB_ID}\"}"
+assert_ok "snapshot after release"
+RELEASED_ID=$(echo "$RESULT" | jq -r '.id')
+
+pt_get "/memory/compare?base=${LEAK_ID}&head=${RELEASED_ID}&top=20"
+assert_ok "compare leaked to released"
+assert_json_eq "$RESULT" '.constructors[0].name' '(array)' "the released backing stores top the table"
+assert_json_jq "$RESULT" ".constructors[0].sizeDelta <= -$((10 * MB))" \
+ "top row shrank by at least 10 MB" "top row did not shrink by 10 MB"
+
+pt_get "/memory/compare?base=${BASE_ID}&head=heap_does_not_exist"
+assert_http_status 404 "unknown head id"
+assert_json_eq "$RESULT" '.code' 'memory_snapshot_not_found' "unknown id is memory_snapshot_not_found"
+assert_json_eq "$RESULT" '.details.id' 'heap_does_not_exist' "refusal names the missing id"
+
+end_test
diff --git a/tests/e2e/scenarios/api/memory-extended.sh b/tests/e2e/scenarios/api/memory-extended.sh
index d7457cf1..bb128c62 100644
--- a/tests/e2e/scenarios/api/memory-extended.sh
+++ b/tests/e2e/scenarios/api/memory-extended.sh
@@ -10,7 +10,7 @@ source "${GROUP_DIR}/../../helpers/api.sh"
memory_disabled_tests() {
# ─────────────────────────────────────────────────────────────────
- start_test "memory: allowMemory off refuses snapshot and summary, usage still answers"
+ start_test "memory: allowMemory off refuses snapshot, summary and compare, usage still answers"
pt_get /health
assert_ok "health"
@@ -39,6 +39,10 @@ memory_disabled_tests() {
assert_http_status 403 "summary refused"
assert_json_eq "$RESULT" '.code' 'memory_disabled' "summary answers memory_disabled"
+ pt_get "/memory/compare?base=heap_a&head=heap_b"
+ assert_http_status 403 "compare refused"
+ assert_json_eq "$RESULT" '.code' 'memory_disabled' "compare answers memory_disabled"
+
end_test
}
diff --git a/tests/e2e/scenarios/cli/memory-basic.sh b/tests/e2e/scenarios/cli/memory-basic.sh
index 411b57bc..d3943142 100644
--- a/tests/e2e/scenarios/cli/memory-basic.sh
+++ b/tests/e2e/scenarios/cli/memory-basic.sh
@@ -48,3 +48,50 @@ assert_output_contains '"topBySize"' "json summary carries topBySize"
pt_ok click "#release"
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab memory compare <a> <b> --top 5"
+
+snapshot_id() {
+ grep -o 'pinchtab memory summary [^ ]*' <<<"$PT_OUT" | awk '{print $4}'
+}
+
+pt_ok memory snapshot
+BASE_ID=$(snapshot_id)
+
+pt_ok click "#leak"
+pt_ok click "#leak"
+pt_ok click "#leak"
+
+pt_ok memory snapshot
+HEAD_ID=$(snapshot_id)
+if [ -n "$BASE_ID" ] && [ -n "$HEAD_ID" ] && [ "$BASE_ID" != "$HEAD_ID" ]; then
+ pass_assert "two snapshot ids: $BASE_ID → $HEAD_ID"
+else
+ fail_assert "snapshot ids '$BASE_ID' and '$HEAD_ID' are missing or equal"
+fi
+
+pt_ok memory compare "$BASE_ID" "$HEAD_ID" --top 5 --json
+JSON_TOP=$(echo "$PT_OUT" | jq -r '.constructors[0].name')
+if [ "$JSON_TOP" = "(array)" ] && echo "$PT_OUT" | jq -e '.constructors[0].sizeDelta >= 10485760' >/dev/null; then
+ pass_assert "json top row is (array) grown by at least 10 MB"
+else
+ fail_assert "json top row is '$JSON_TOP', want (array) grown by at least 10 MB"
+fi
+
+pt_ok memory compare "$BASE_ID" "$HEAD_ID" --top 5
+assert_output_contains "$BASE_ID → $HEAD_ID" "header names both snapshots"
+assert_output_contains "CONSTRUCTOR" "delta table header"
+FIRST_ROW=$(grep -A1 'CONSTRUCTOR' <<<"$PT_OUT" | tail -1 | awk '{print $1}')
+if [ "$FIRST_ROW" = "$JSON_TOP" ]; then
+ pass_assert "human table prints the same top row ($FIRST_ROW)"
+else
+ fail_assert "human top row '$FIRST_ROW' differs from json top row '$JSON_TOP'"
+fi
+
+pt_ok memory compare "$BASE_ID" "$HEAD_ID" --top 5 --retained
+assert_output_contains "RETAINED" "--retained adds the retained column"
+
+pt_ok click "#release"
+
+end_test
diff --git a/tests/e2e/scenarios/manifest.json b/tests/e2e/scenarios/manifest.json
index a9f32ce3..42c5fe50 100644
--- a/tests/e2e/scenarios/manifest.json
+++ b/tests/e2e/scenarios/manifest.json
@@ -596,6 +596,7 @@
"api/memory-basic.sh": {
"tags": [
"memory",
+ "compare",
"pr"
]
},
@@ -613,6 +614,7 @@
],
"tags": [
"memory",
+ "compare",
"secure",
"medium"
]
@@ -620,6 +622,7 @@
"cli/memory-basic.sh": {
"tags": [
"memory",
+ "compare",
"pr"
]
},