High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(snapshot): make maxTokens a ceiling on the reply, not on the nodes in it
Darshan Jain6d6e1ea72df4
diff --git a/docs/reference/snapshot.md b/docs/reference/snapshot.mdindex ca0006e0..e45e6685 100644--- a/docs/reference/snapshot.md+++ b/docs/reference/snapshot.md@@ -117,6 +117,17 @@ The cost is measured, not modelled: each node is charged the bytes its own formarendered for `compact` and `text`, marshalled for `json` and `yaml` — so a change to aformatter changes the budget with it. Tokens are estimated at four bytes each.+For `compact` and `text` the ceiling covers the **whole reply**, not only the nodes in it.+The header, the `# hint:` and `# ignored params:` lines and the untrusted-content wrapper+are reserved before any node is allocated, so the budget is not spent twice. This matters+because the header carries the page title and URL: on a page with an ordinary marketing+title and a nested path it is around 45 tokens, which a budget of 100 cannot absorb+silently. The framing is priced by building the string that gets written, so what is+reserved and what is sent cannot drift apart.++`json` and `yaml` budget the node array only; their envelope is a small fixed cost next to+nodes that run to hundreds of bytes each.+Formats are not interchangeable for a given budget. `yaml` is roughly three times the sizeof `json` for the same nodes, because the node struct carries JSON field tags and no YAMLones, so YAML emits every field including the empty ones. The same `maxTokens` thereforediff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex 4754125f..b7ef86cb 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -68,12 +68,73 @@ func attachIgnoredParams(data map[string]any, ignored []string) map[string]any {return data}-// writeIgnoredParamsComment is the same disclosure for the plain-text formats, in the-// comment shape those responses already use for hints.-func writeIgnoredParamsComment(w http.ResponseWriter, ignored []string) {- if len(ignored) > 0 {- _, _ = fmt.Fprintf(w, "# ignored params: %s\n", strings.Join(ignored, ", "))+// estimateSnapshotTokens converts framing bytes into the same tokens the truncator+// charges nodes in. Four bytes per token is the approximation the budget rests on,+// and the reserve has to be denominated in it or the two halves of the ceiling+// would be measured in different units.+//+// It rounds UP where the truncator's charge rounds down, and the asymmetry is the+// point: a charge that rounds down can spend a fraction of a token it did not pay+// for, while a reserve that rounds down leaves a fraction of the framing unfunded.+// Both were floors to begin with, and the two remainders met — framing of 44.75+// tokens reserved 44, and a 100-token budget returned 101.+func estimateSnapshotTokens(bytes int) int {+ return (bytes + 3) / 4+}++// snapshotFramingReserve is what this reply costs before a node is written. The+// untrusted-content wrapper is included when the configuration turns it on: it is+// decided by config rather than by the scan — scanSnapshotIDPI reads+// IDPI.Enabled && IDPI.WrapContent — so it is knowable here, ahead of the scan+// that deliberately runs after truncation. It is also the larger of the two+// framings, being a fixed advisory paragraph.+func (h *Handlers) snapshotFramingReserve(format, title, url string, count int, scope *frameDisclosure, hint string, ignored []string, maxTokens int) int {+ var header string+ switch format {+ case "text":+ header = snapshotTextHeader(title, url, count, scope)+ default:+ header = snapshotCompactHeader(title, url, count, scope)}+ n := len(snapshotFraming(format, header, hint, ignored, true, maxTokens))+ if h.Config != nil && h.Config.IDPI.Enabled && h.Config.IDPI.WrapContent && h.IDPIGuard != nil {+ n += len(h.IDPIGuard.WrapContent("", url))+ }+ return n+}++func ignoredParamsComment(ignored []string) string {+ if len(ignored) == 0 {+ return ""+ }+ return fmt.Sprintf("# ignored params: %s\n", strings.Join(ignored, ", "))+}++// snapshotFraming is everything the caller is sent that is not a node: the header,+// the hint, the ignored-params comment, and the blank line the text layout puts+// between them and the tree.+//+// It is built once and used twice — measured to reserve budget, then written — so+// the charge cannot drift from the output. Building a second model of the framing+// in order to price it is the mistake nodeCost already avoids by rendering through+// appendNode rather than describing it.+func snapshotFraming(format, header, hint string, ignored []string, truncated bool, maxTokens int) string {+ var b strings.Builder+ b.WriteString(header)+ // Only the compact layout annotates the header with the budget; text does not,+ // and this reproduces each exactly rather than making them agree.+ if truncated && format != "text" {+ fmt.Fprintf(&b, " (truncated to ~%d tokens)", maxTokens)+ }+ b.WriteString("\n")+ if hint != "" {+ fmt.Fprintf(&b, "# hint: %s\n", hint)+ }+ b.WriteString(ignoredParamsComment(ignored))+ if format == "text" {+ b.WriteString("\n")+ }+ return b.String()}func snapshotFormatCarriesMetadata(format string) bool {@@ -226,7 +287,23 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {truncated := falseif maxTokens > 0 {- flat, truncated = bridge.TruncateToTokens(flat, maxTokens, format)+ // The budget has to cover the reply, not just the part of it made of nodes.+ // TruncateToTokens was fitting the tree to maxTokens and the header was then+ // written on top of it, so what the caller received was over by whatever the+ // header cost — and the header carries the title and the URL, so that is a+ // page-dependent amount, not a constant to shrug at. Measured on a page with+ // an ordinary marketing title and path, a budget of 100 returned ~142 tokens.+ //+ // Reserved before allocating, with truncation assumed: a budget is a ceiling,+ // so where the two readings differ this takes the larger one. The node count+ // in the header is the pre-truncation one for the same reason — it has at+ // least as many digits as the count that will be printed.+ reserve := estimateSnapshotTokens(h.snapshotFramingReserve(format, title, url, len(flat), scopeInfo, scopedEmptyHint, controls.Ignored, maxTokens))+ nodeBudget := maxTokens - reserve+ if nodeBudget < 0 {+ nodeBudget = 0+ }+ flat, truncated = bridge.TruncateToTokens(flat, nodeBudget, format)}prev := h.Bridge.GetRefCache(resolvedTabID)@@ -375,13 +452,9 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if format == "compact" {w.Header().Set("Content-Type", "text/plain; charset=utf-8")w.WriteHeader(200)- _, _ = fmt.Fprintf(w, "%s | +%d ~%d -%d",+ diffHeader := fmt.Sprintf("%s | +%d ~%d -%d",snapshotCompactHeader(title, url, len(flat), scopeInfo), len(added), len(changed), len(removed))- if truncated {- _, _ = fmt.Fprintf(w, " (truncated to ~%d tokens)", maxTokens)- }- _, _ = w.Write([]byte("\n"))- writeIgnoredParamsComment(w, controls.Ignored)+ _, _ = w.Write([]byte(snapshotFraming(format, diffHeader, "", controls.Ignored, truncated, maxTokens)))content := bridge.FormatSnapshotCompactDiff(flat, added, changed, removed)if wrapContent {content = h.IDPIGuard.WrapContent(content, url)@@ -412,15 +485,9 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {case "compact":w.Header().Set("Content-Type", "text/plain; charset=utf-8")w.WriteHeader(200)- _, _ = fmt.Fprintf(w, "%s", snapshotCompactHeader(title, url, len(flat), scopeInfo))- if truncated {- _, _ = fmt.Fprintf(w, " (truncated to ~%d tokens)", maxTokens)- }- _, _ = w.Write([]byte("\n"))- if scopedEmptyHint != "" {- _, _ = fmt.Fprintf(w, "# hint: %s\n", scopedEmptyHint)- }- writeIgnoredParamsComment(w, controls.Ignored)+ _, _ = w.Write([]byte(snapshotFraming(format,+ snapshotCompactHeader(title, url, len(flat), scopeInfo),+ scopedEmptyHint, controls.Ignored, truncated, maxTokens)))content := bridge.FormatSnapshotCompact(flat)if wrapContent {content = h.IDPIGuard.WrapContent(content, url)@@ -429,12 +496,9 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {case "text":w.Header().Set("Content-Type", "text/plain; charset=utf-8")w.WriteHeader(200)- _, _ = fmt.Fprintf(w, "%s\n", snapshotTextHeader(title, url, len(flat), scopeInfo))- if scopedEmptyHint != "" {- _, _ = fmt.Fprintf(w, "# hint: %s\n", scopedEmptyHint)- }- writeIgnoredParamsComment(w, controls.Ignored)- _, _ = w.Write([]byte("\n"))+ _, _ = w.Write([]byte(snapshotFraming(format,+ snapshotTextHeader(title, url, len(flat), scopeInfo),+ scopedEmptyHint, controls.Ignored, truncated, maxTokens)))content := bridge.FormatSnapshotText(flat)if wrapContent {content = h.IDPIGuard.WrapContent(content, url)diff --git a/internal/handlers/snapshot_budget_framing_test.go b/internal/handlers/snapshot_budget_framing_test.gonew file mode 100644index 00000000..a0c4fcb7--- /dev/null+++ b/internal/handlers/snapshot_budget_framing_test.go@@ -0,0 +1,132 @@+package handlers++import (+ "fmt"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/idpi"+)++// framingProbeNodes is a page's worth of compact nodes: small individually, which+// is exactly the case where a header is not a rounding error.+func framingProbeNodes(count int) []bridge.A11yNode {+ nodes := make([]bridge.A11yNode, 0, count)+ for i := 0; i < count; i++ {+ nodes = append(nodes, bridge.A11yNode{+ Ref: fmt.Sprintf("e%d", i),+ Role: []string{"heading", "link", "button", "textbox"}[i%4],+ Name: "Compare plans and pricing",+ })+ }+ return nodes+}++// maxTokens is documented as a ceiling on the response. It was a ceiling on the+// part of the response made of nodes: the tree was fitted to the budget and the+// header was then written on top of it.+//+// The header carries the page title and URL, so the overshoot is page-dependent+// rather than a constant. Measured through a real browser on a page with an+// ordinary marketing title and a nested path, a budget of 100 returned ~142+// tokens - 182 bytes of header against 386 bytes of nodes that were themselves+// correctly under budget.+//+// This drives the same two pieces the handler does, at the same sizes, and holds+// the whole reply to the number that was asked for.+func TestSnapshotBudgetCoversTheFramingNotJustTheNodes(t *testing.T) {+ h := &Handlers{+ Config: &config.RuntimeConfig{},+ IDPIGuard: idpi.NewGuard(config.IDPIConfig{}, nil),+ }+ const (+ title = "Enterprise Platform Pricing, Plans and Frequently Asked Questions"+ url = "https://example.com/a-fairly-long-marketing-path/with-nested-segments/"+ )+ nodes := framingProbeNodes(80)++ for _, format := range []string{"compact", "text"} {+ for _, budget := range []int{100, 150, 300, 600} {+ t.Run(fmt.Sprintf("%s/%d", format, budget), func(t *testing.T) {+ reserve := estimateSnapshotTokens(+ h.snapshotFramingReserve(format, title, url, len(nodes), nil, "", nil, budget))+ nodeBudget := budget - reserve+ if nodeBudget < 0 {+ nodeBudget = 0+ }+ kept, truncated := bridge.TruncateToTokens(nodes, nodeBudget, format)++ header := snapshotCompactHeader(title, url, len(kept), nil)+ if format == "text" {+ header = snapshotTextHeader(title, url, len(kept), nil)+ }+ framing := snapshotFraming(format, header, "", nil, truncated, budget)++ var body string+ if format == "text" {+ body = bridge.FormatSnapshotText(kept)+ } else {+ body = bridge.FormatSnapshotCompact(kept)+ }++ total := estimateSnapshotTokens(len(framing) + len(body))+ if total > budget {+ t.Errorf("%s budget=%d: reply is ~%d tokens (%d%% of budget) - framing ~%d + nodes ~%d; the budget is a ceiling on the reply",+ format, budget, total, total*100/budget,+ estimateSnapshotTokens(len(framing)), estimateSnapshotTokens(len(body)))+ }+ t.Logf("%-7s budget=%3d -> reply ~%3d tokens (%3d%%), framing ~%2d, %d/%d nodes",+ format, budget, total, total*100/budget, estimateSnapshotTokens(len(framing)), len(kept), len(nodes))+ })+ }+ }+}++// The framing is priced by building it, so a change to what the handler writes+// changes the charge with it. This pins that the reserve is that string's length+// and not a second description of it - the failure mode nodeCost already avoids+// by rendering through appendNode.+func TestFramingReserveIsTheFramingItself(t *testing.T) {+ h := &Handlers{+ Config: &config.RuntimeConfig{},+ IDPIGuard: idpi.NewGuard(config.IDPIConfig{}, nil),+ }+ const title, url = "Title", "https://example.com/p"++ for _, format := range []string{"compact", "text"} {+ header := snapshotCompactHeader(title, url, 7, nil)+ if format == "text" {+ header = snapshotTextHeader(title, url, 7, nil)+ }+ want := len(snapshotFraming(format, header, "", nil, true, 500))+ got := h.snapshotFramingReserve(format, title, url, 7, nil, "", nil, 500)+ if got != want {+ t.Errorf("%s: reserved %d bytes but the framing it writes is %d", format, got, want)+ }+ }+}++// The untrusted-content wrapper is part of the reply and is decided by config, not+// by the scan, so it can be and is charged. Leaving it out would put the ceiling+// back over by an advisory paragraph - the larger of the two framings.+func TestFramingReserveChargesTheUntrustedContentWrapper(t *testing.T) {+ const title, url = "Title", "https://example.com/p"+ plain := &Handlers{+ Config: &config.RuntimeConfig{},+ IDPIGuard: idpi.NewGuard(config.IDPIConfig{}, nil),+ }+ wrapping := &Handlers{+ Config: &config.RuntimeConfig{IDPI: config.IDPIConfig{Enabled: true, WrapContent: true}},+ IDPIGuard: idpi.NewGuard(config.IDPIConfig{Enabled: true, WrapContent: true}, nil),+ }++ bare := plain.snapshotFramingReserve("compact", title, url, 7, nil, "", nil, 500)+ wrapped := wrapping.snapshotFramingReserve("compact", title, url, 7, nil, "", nil, 500)+ if wrapped <= bare {+ t.Fatalf("wrapping config reserved %d bytes, no more than the %d reserved without it", wrapped, bare)+ }+ if overhead := wrapped - bare; overhead < 100 {+ t.Errorf("wrapper charged only %d bytes; the advisory alone is larger than that", overhead)+ }+}diff --git a/internal/handlers/snapshot_params_test.go b/internal/handlers/snapshot_params_test.goindex 7a6bc6a3..3d9dda53 100644--- a/internal/handlers/snapshot_params_test.go+++ b/internal/handlers/snapshot_params_test.go@@ -506,7 +506,29 @@ func TestAResponseWithoutIgnoredParamsCarriesNoDisclosure(t *testing.T) {const snapshotHandlerFile = "snapshot.go"-var disclosureHelpers = map[string]bool{"attachIgnoredParams": true, "writeIgnoredParamsComment": true}+// snapshotFraming belongs here for the same reason attachIgnoredParams does: it+// discloses.+// It emits ignoredParamsComment unconditionally as part of the framing it returns,+// so a text branch that writes its framing has told the caller what was ignored.+//+// This is the scan being taught the helper that replaced writeIgnoredParamsComment,+// not being relaxed. Every response+// branch must still call one of these, and a branch that calls none still fails —+// which is what caught the text branches when the disclosure moved inside the+// framing and the scan could no longer see it by name.+var disclosureHelpers = map[string]bool{+ "attachIgnoredParams": true,+ "snapshotFraming": true,+}++// The framing helper only counts as a disclosure while it actually makes one, so+// this fails if ignoredParamsComment ever stops being part of what it returns.+func TestSnapshotFramingIsWhyItCountsAsADisclosure(t *testing.T) {+ framing := snapshotFraming("compact", "# T | u | 1 nodes", "", []string{"bogusParam"}, false, 0)+ if !strings.Contains(framing, "bogusParam") {+ t.Fatalf("snapshotFraming is trusted by disclosureHelpers to disclose ignored params, but %q carries none; drop it from that set or restore the disclosure", framing)+ }+}func successResponseBlocks(fn *ast.FuncDecl) []ast.Node {var stack, blocks []ast.Node@@ -612,7 +634,7 @@ func TestEveryResponseBranchDisclosesIgnoredParams(t *testing.T) {}for _, block := range blocks {if !disclosesIgnoredParams(block) {- t.Errorf("%s: this response branch calls neither attachIgnoredParams nor writeIgnoredParamsComment, so a caller served by it is never told which of its parameters did nothing; the helpers make the disclosure easy to add, and only this scan makes it hard to forget",+ t.Errorf("%s: this response branch calls neither attachIgnoredParams nor snapshotFraming, so a caller served by it is never told which of its parameters did nothing; the helpers make the disclosure easy to add, and only this scan makes it hard to forget",fset.Position(block.Pos()))}}