From 0e8f93bf74fec571897f7d90cfc10f64a8f4761b Mon Sep 17 00:00:00 2001 From: Tim Voronov Date: Tue, 17 Nov 2026 20:34:25 -0500 Subject: [PATCH 1/2] Add bounded debugger variable inspection Define paged variable requests with shared range validation, filtered child views, and optional indexed and named counts. Expand session contracts with reference, snapshot, cancellation, and atomic publication semantics, and add inspection guidance and contract tests. Update the README to describe debugger value summaries, child counts, paging, and reference lifetimes. --- README.md | 16 +- debugger/inspection_contract_test.go | 173 +++++++++++++++++++ debugger/session.go | 28 ++- debugger/types.go | 23 ++- debugger/types_test.go | 2 +- debugger/value_reference.go | 9 +- debugger/variable_page.go | 58 +++++++ debugger/variable_page_test.go | 131 ++++++++++++++ docs/debugger-inspection.md | 249 +++++++++++++++++++++++++++ 9 files changed, 675 insertions(+), 14 deletions(-) create mode 100644 debugger/inspection_contract_test.go create mode 100644 debugger/variable_page.go create mode 100644 debugger/variable_page_test.go create mode 100644 docs/debugger-inspection.md diff --git a/README.md b/README.md index 10aa238..cd6a6cd 100644 --- a/README.md +++ b/README.md @@ -263,15 +263,19 @@ and any restrictions for debug compilation. Native Ferret produces one-based lines and byte columns, with zero-based, half-open byte spans. Source names are identities and need not be filesystem paths; anonymous sources have an empty name. Adapters translate native indexed -source text into the portable `Source` representation. Portable coordinates, debugger -values, variables, frames, breakpoints, and reasons retain their existing representations. +source text into the portable `Source` representation. Encoded content uses the new nested metadata shape described below. Debugger events retain their field names, including `output`, whose value is materialized `*Content`. -`debugger.ValueReference.Valid` accepts positive references. References are scoped -to a paused state and become stale when execution resumes. `debugger.NoFunction` -identifies the top-level program body. Compiler table identifiers and validation -remain implementation details. +Debugger values carry a semantic type, a shallow display summary, and optional +indexed and named child counts. Describing a value reads no children. To expand +a positive reference, call `Session.Variables(ctx, ref, debugger.VariablePage{...})`. +The zero-value request reads at most `debugger.DefaultVariablePageSize` children. +Callers can retain a page as a read-only snapshot after its expansion references +expire on resume, termination, or close. [Debugger inspection guide](docs/debugger-inspection.md) + +`debugger.NoFunction` identifies the top-level program body. Compiler table +identifiers and validation remain implementation details. Debugger commands are `StepIn`, `StepOver`, and `StepOut`. Breakpoint requests use canonical source locations and binding options. `ReplaceBreakpoints(ctx, sourceName, diff --git a/debugger/inspection_contract_test.go b/debugger/inspection_contract_test.go new file mode 100644 index 0000000..7bc579c --- /dev/null +++ b/debugger/inspection_contract_test.go @@ -0,0 +1,173 @@ +package debugger_test + +import ( + "context" + "errors" + "math" + "slices" + "strconv" + "testing" + + "github.com/MontFerret/api/debugger" +) + +// inspectionFixture supplies a paused binding and scripted page reads to caller +// examples. The runtime owns handle allocation and stop transitions. +type inspectionFixture struct { + sessionContract + value debugger.Value + read func(debugger.VariablePage) ([]debugger.Variable, error) +} + +func (s inspectionFixture) Locals(context.Context) ([]debugger.Variable, error) { + return []debugger.Variable{{Name: "results", Value: s.value}}, nil +} + +func (s inspectionFixture) Variables(ctx context.Context, ref debugger.ValueReference, page debugger.VariablePage) ([]debugger.Variable, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if !ref.Valid() || ref != s.value.Reference { + return nil, debugger.ErrInvalidValueReference + } + page, err := page.Normalize() + if err != nil { + return nil, err + } + return s.read(page) +} + +func TestInspectionReadsOnlyTheRequestedMillionElementArrayPage(t *testing.T) { + length, noNames := int64(1_000_000), int64(0) + var reads []int64 + var session debugger.Session = inspectionFixture{ + value: debugger.Value{Type: "Array", Display: "Array(1000000)", Reference: 1, IndexedCount: &length, NamedCount: &noNames}, + read: func(page debugger.VariablePage) ([]debugger.Variable, error) { + if page.Filter == debugger.VariableFilterNamed { + return nil, nil + } + var children []debugger.Variable + for index := page.Start; index < min(length, page.Start+page.Count); index++ { + reads = append(reads, index) + children = append(children, debugger.Variable{Name: strconv.FormatInt(index, 10)}) + } + return children, nil + }, + } + locals, err := session.Locals(t.Context()) + if err != nil || len(locals) != 1 || len(reads) != 0 { + t.Fatalf("Locals = %v, %v; child reads = %v", locals, err, reads) + } + value := locals[0].Value + if value.IndexedCount == nil || *value.IndexedCount != 1_000_000 || value.NamedCount == nil || *value.NamedCount != 0 { + t.Fatalf("array counts = %+v", value) + } + named, err := session.Variables(t.Context(), value.Reference, debugger.VariablePage{Filter: debugger.VariableFilterNamed}) + if err != nil || len(named) != 0 || len(reads) != 0 { + t.Fatalf("absent named children = %v, %v; child reads = %v", named, err, reads) + } + children, err := session.Variables(t.Context(), value.Reference, debugger.VariablePage{Filter: debugger.VariableFilterIndexed, Start: 1000, Count: 20}) + if err != nil || len(children) != 20 || len(reads) != 20 { + t.Fatalf("page length = %d, reads = %v, error = %v", len(children), reads, err) + } + for i, child := range children { + if child.Name != strconv.Itoa(1000+i) || reads[i] != int64(1000+i) { + t.Fatalf("child %d = %q, source index = %d", i, child.Name, reads[i]) + } + } +} + +func TestInspectionPagesWithUnknownCounts(t *testing.T) { + // The caller only knows the reference. Each slice describes the source order. + views := map[debugger.VariableFilter][]debugger.Variable{ + debugger.VariableFilterNamed: {{Name: "0"}, {Name: "size"}}, + debugger.VariableFilterIndexed: {{Name: "0"}, {Name: "1"}, {Name: "2"}, {Name: "3"}}, + } + views[debugger.VariableFilterAll] = slices.Concat(views[debugger.VariableFilterNamed], views[debugger.VariableFilterIndexed]) + session := inspectionFixture{value: debugger.Value{Reference: 1}, read: func(page debugger.VariablePage) ([]debugger.Variable, error) { + children := views[page.Filter] + end := int64(len(children)) + return children[min(page.Start, end):min(page.Start+page.Count, end)], nil + }} + for _, tc := range []struct { + page debugger.VariablePage + want []string + }{ + {debugger.VariablePage{Count: 3}, []string{"0", "size", "0"}}, + {debugger.VariablePage{Start: 1, Count: 3}, []string{"size", "0", "1"}}, + {debugger.VariablePage{Start: 4, Count: 2}, []string{"2", "3"}}, + {debugger.VariablePage{Filter: debugger.VariableFilterNamed, Start: 1, Count: 4}, []string{"size"}}, + {debugger.VariablePage{Filter: debugger.VariableFilterIndexed, Start: 3, Count: 2}, []string{"3"}}, + {debugger.VariablePage{Start: 6}, nil}, + {debugger.VariablePage{Start: 8}, nil}, + } { + got, err := session.Variables(t.Context(), session.value.Reference, tc.page) + if err != nil || len(got) != len(tc.want) { + t.Fatalf("Variables(%+v) = %v, %v; want %v", tc.page, got, err, tc.want) + } + for i, child := range got { + if child.Name != tc.want[i] { + t.Errorf("page %+v child %d = %q, want %q", tc.page, i, child.Name, tc.want[i]) + } + } + } +} + +func TestInspectionContinuesAtSignedBoundaryWithIndexedFilter(t *testing.T) { + // One named child precedes MaxInt64 indexed children in the combined view. + const last = math.MaxInt64 - 1 + var reads []int64 + session := inspectionFixture{value: debugger.Value{Reference: 1}, read: func(page debugger.VariablePage) ([]debugger.Variable, error) { + index := page.Start + if page.Filter == debugger.VariableFilterAll { + index-- + } + reads = append(reads, index) + return []debugger.Variable{{Name: strconv.FormatInt(index, 10)}}, nil + }} + page := debugger.VariablePage{Start: last, Count: 1} + got, err := session.Variables(t.Context(), 1, page) + if err != nil || len(got) != 1 || got[0].Name != strconv.FormatInt(last-1, 10) { + t.Fatalf("last combined page = %v, %v", got, err) + } + got, err = session.Variables(t.Context(), 1, debugger.VariablePage{Start: math.MaxInt64, Count: 1}) + if got != nil || !errors.Is(err, debugger.ErrInvalidVariablePage) || !slices.Equal(reads, []int64{last - 1}) { + t.Fatalf("combined continuation = %v, %v; reads = %v", got, err, reads) + } + page.Filter = debugger.VariableFilterIndexed + got, err = session.Variables(t.Context(), 1, page) + if err != nil || len(got) != 1 || got[0].Name != strconv.FormatInt(last, 10) || !slices.Equal(reads, []int64{last - 1, last}) { + t.Fatalf("indexed continuation = %v, %v; reads = %v", got, err, reads) + } +} + +func TestInspectionErrorResults(t *testing.T) { + // This stop issued reference 2. Reference 1 belonged to the previous stop. + session := inspectionFixture{value: debugger.Value{Reference: 2}} + for _, ref := range []debugger.ValueReference{-1, 0, 1, 99} { + got, err := session.Variables(t.Context(), ref, debugger.VariablePage{}) + if got != nil || !errors.Is(err, debugger.ErrInvalidValueReference) { + t.Fatalf("Variables(%d) = %v, %v", ref, got, err) + } + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + page := debugger.VariablePage{Count: 1} + got, err := session.Variables(ctx, 2, page) + if got != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("canceled page = %v, %v", got, err) + } + readErr := errors.New("child read failed") + session.read = func(debugger.VariablePage) ([]debugger.Variable, error) { return nil, readErr } + got, err = session.Variables(t.Context(), 2, page) + if got != nil || !errors.Is(err, readErr) { + t.Fatalf("failed page = %v, %v", got, err) + } + session.read = func(debugger.VariablePage) ([]debugger.Variable, error) { + return []debugger.Variable{{Name: "0"}}, nil + } + got, err = session.Variables(t.Context(), 2, page) + if err != nil || len(got) != 1 || got[0].Name != "0" { + t.Fatalf("retry at same stop = %v, %v", got, err) + } +} diff --git a/debugger/session.go b/debugger/session.go index cb56653..c15e586 100644 --- a/debugger/session.go +++ b/debugger/session.go @@ -13,7 +13,7 @@ import ( // run concurrently with execution. Pause and Close may interrupt an active command. // Close terminates execution, waits for commands, and releases resources; // repeated closes retain the cleanup result without requiring identical -// error-wrapper pointers. Inspection references expire on resume. +// error-wrapper pointers. Inspection references expire on resume or termination. // A command can return an event and an error, including available completion // content when subsequent cleanup fails. Event.Output holds detached materialized // Content that remains readable after cleanup; inspecting a retained event never @@ -60,7 +60,31 @@ type Session interface { Frames(ctx context.Context) ([]Frame, error) Locals(ctx context.Context) ([]Variable, error) FrameLocals(ctx context.Context, frame int) ([]Variable, error) - Variables(ctx context.Context, reference ValueReference) ([]Variable, error) + + // Variables reads one bounded page of immediate children in the current + // paused state. Page arguments follow VariablePage.Normalize. Select the + // child kind before applying the range. An absent kind or a start at or + // beyond the end returns an empty page. A short successful page means the + // selected sequence is exhausted, including when its length is unknown. + // Recognized modes that cannot be paged safely return an error matching + // errors.ErrUnsupported. Invalid, unknown, or expired references while + // paused return an error matching ErrInvalidValueReference. + // + // Callers may retain the page as a read-only snapshot. Its slice entries + // and counts remain readable across later calls, resume, and Close. Only + // the expansion references expire. + // Repeated reads of the same position in a parent's named or indexed + // sequence reuse the child's reference for that stop. + // + // The producing session checks the context during reads and before publishing + // the complete page and its new handles together. A malformed UTF-8 key in + // the requested page is a child-read error. Read failure, cancellation, + // termination, or handle exhaustion before publication returns a nil page + // and an error. Exhaustion preserves previously issued handles. If remote + // delivery fails after publication, the caller also receives a nil page + // and an error. Context errors preserve errors.Is identity. Canceling an + // inspection affects only that request. + Variables(ctx context.Context, reference ValueReference, page VariablePage) ([]Variable, error) Evaluate(ctx context.Context, expression string) (Value, error) EvaluateFrame(ctx context.Context, frame int, expression string) (Value, error) } diff --git a/debugger/types.go b/debugger/types.go index 0734340..638fada 100644 --- a/debugger/types.go +++ b/debugger/types.go @@ -19,14 +19,29 @@ type ( // an executable debug point. BreakpointBindingMode int - // Value is a safely formatted debugger value. + // Value describes a value without reading its children. Producing Type and + // Display takes bounded work and space. Presentation and counts are + // detached snapshots that remain readable after the stop. Value struct { - Type string `json:"type"` - Display string `json:"display"` + // Type is the user-facing semantic type, including for host values. + Type string `json:"type"` + // Display is a cheap, bounded summary. Collection summaries can use a + // cheaply known size without previewing elements. + Display string `json:"display"` + // Reference is positive when safe, bounded expansion is available. + // A known empty collection or a summary-only value has reference zero. Reference ValueReference `json:"reference"` + + // IndexedCount and NamedCount are optional, read-only exact counts of + // each child kind. Nil means unknown. A present count is nonnegative + // and can be zero. A known count alone does not grant expansion. + IndexedCount *int64 `json:"indexedCount,omitempty"` + NamedCount *int64 `json:"namedCount,omitempty"` } - // Variable describes a visible local or bind parameter. + // Variable describes a local, bind parameter, or immediate child of a + // debugger value. A named child's Name preserves its valid UTF-8 key + // exactly. An indexed child's Name is its absolute decimal index. Variable struct { Name string `json:"name"` Value Value `json:"value"` diff --git a/debugger/types_test.go b/debugger/types_test.go index ea99b10..3690b08 100644 --- a/debugger/types_test.go +++ b/debugger/types_test.go @@ -48,7 +48,7 @@ func (sessionContract) FrameLocals(ctx context.Context, frame int) ([]debugger.V return nil, nil } -func (sessionContract) Variables(ctx context.Context, reference debugger.ValueReference) ([]debugger.Variable, error) { +func (sessionContract) Variables(context.Context, debugger.ValueReference, debugger.VariablePage) ([]debugger.Variable, error) { return nil, nil } diff --git a/debugger/value_reference.go b/debugger/value_reference.go index f8e1b90..87b0809 100644 --- a/debugger/value_reference.go +++ b/debugger/value_reference.go @@ -1,7 +1,14 @@ package debugger +import "errors" + +// ErrInvalidValueReference identifies a reference that cannot be resolved in +// the current paused state. Implementations may wrap it. Use errors.Is. +var ErrInvalidValueReference = errors.New("invalid debugger value reference") + // ValueReference identifies an expandable debugger value within one paused -// session state. References are invalidated when execution starts or resumes. +// session state. Resume, termination, and Close invalidate references. An +// expired reference must never identify another value later in that session. type ValueReference int // Valid reports whether the reference has a valid portable encoding. It does diff --git a/debugger/variable_page.go b/debugger/variable_page.go new file mode 100644 index 0000000..9a2ab43 --- /dev/null +++ b/debugger/variable_page.go @@ -0,0 +1,58 @@ +package debugger + +import ( + "errors" + "math" +) + +// VariableFilter selects the immediate children in a page. +type VariableFilter string + +const ( + // VariableFilterAll selects named children first, followed by indexed children. + VariableFilterAll VariableFilter = "" + // VariableFilterNamed selects named children in stable order for the stop. + VariableFilterNamed VariableFilter = "named" + // VariableFilterIndexed selects indexed children in ascending source order. + VariableFilterIndexed VariableFilter = "indexed" +) + +const ( + // DefaultVariablePageSize is the number requested when Count is zero. + DefaultVariablePageSize = 100 + // MaxVariablePageSize is the largest accepted Count for one call. + MaxVariablePageSize = 1000 +) + +// ErrInvalidVariablePage identifies an unknown filter or an invalid page range. +var ErrInvalidVariablePage = errors.New("invalid debugger variable page") + +// VariablePage requests a range in the selected child sequence. Start is a +// zero-based offset. Count is the maximum number of children to read. The +// zero value requests the first bounded page across both child kinds. +type VariablePage struct { + Filter VariableFilter `json:"filter,omitempty"` + Start int64 `json:"start,omitempty"` + Count int64 `json:"count,omitempty"` +} + +// Normalize replaces a zero Count with DefaultVariablePageSize. An unknown +// filter, negative Start or Count, Count above MaxVariablePageSize, or an +// exclusive end exceeding math.MaxInt64 returns ErrInvalidVariablePage. +func (p VariablePage) Normalize() (VariablePage, error) { + switch p.Filter { + case VariableFilterAll, VariableFilterNamed, VariableFilterIndexed: + default: + return VariablePage{}, ErrInvalidVariablePage + } + + if p.Count == 0 { + p.Count = DefaultVariablePageSize + } + + if p.Start < 0 || p.Count < 0 || p.Count > MaxVariablePageSize || p.Start > math.MaxInt64-p.Count { + return VariablePage{}, ErrInvalidVariablePage + } + + return p, nil +} diff --git a/debugger/variable_page_test.go b/debugger/variable_page_test.go new file mode 100644 index 0000000..606c9f6 --- /dev/null +++ b/debugger/variable_page_test.go @@ -0,0 +1,131 @@ +package debugger_test + +import ( + "encoding/json" + "errors" + "math" + "reflect" + "testing" + + "github.com/MontFerret/api/debugger" +) + +func TestVariablePageNormalize(t *testing.T) { + for _, tc := range []struct { + name string + page debugger.VariablePage + want int64 + }{ + {"default", debugger.VariablePage{}, debugger.DefaultVariablePageSize}, + {"indexed", debugger.VariablePage{Filter: debugger.VariableFilterIndexed, Start: 1000, Count: 20}, 20}, + {"maximum", debugger.VariablePage{Filter: debugger.VariableFilterNamed, Count: debugger.MaxVariablePageSize}, debugger.MaxVariablePageSize}, + {"last representable end", debugger.VariablePage{Start: math.MaxInt64 - 1, Count: 1}, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := tc.page.Normalize() + want := tc.page + want.Count = tc.want + if err != nil || got != want { + t.Fatalf("Normalize() = %+v, %v, want %+v", got, err, want) + } + }) + } +} + +func TestVariablePageRejectsInvalidRangesAndFilters(t *testing.T) { + for _, page := range []debugger.VariablePage{ + {Filter: "other"}, + {Start: -1}, + {Count: -1}, + {Count: math.MinInt64}, + {Count: debugger.MaxVariablePageSize + 1}, + {Start: math.MaxInt64, Count: 1}, + {Start: math.MaxInt64 - debugger.DefaultVariablePageSize + 1}, + } { + if _, err := page.Normalize(); !errors.Is(err, debugger.ErrInvalidVariablePage) { + t.Errorf("Normalize(%+v) error = %v, want ErrInvalidVariablePage", page, err) + } + } +} + +func TestValueJSONPreservesChildCounts(t *testing.T) { + var zero int64 + large := int64(1 << 40) + for _, tc := range []struct { + name string + value debugger.Value + indexed string + named string + }{ + {"unknown counts", debugger.Value{Type: "Collection", Reference: 1}, "", ""}, + {"empty array", debugger.Value{Type: "Array", Display: "Array(0)", IndexedCount: &zero}, "0", ""}, + {"indexed children", debugger.Value{Reference: 1, IndexedCount: &large, NamedCount: &zero}, "1099511627776", "0"}, + {"summary-only object", debugger.Value{Type: "Object", NamedCount: &large}, "", "1099511627776"}, + } { + t.Run(tc.name, func(t *testing.T) { + data, err := json.Marshal(tc.value) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + t.Fatal(err) + } + if string(fields["indexedCount"]) != tc.indexed || string(fields["namedCount"]) != tc.named { + t.Fatalf("unexpected child count presence or value in %s", data) + } + var got debugger.Value + if err := json.Unmarshal(data, &got); err != nil || !reflect.DeepEqual(got, tc.value) { + t.Fatalf("round trip of %s = %+v, %v", data, got, err) + } + }) + } +} + +func TestVariablePageJSON(t *testing.T) { + fields := func(data []byte) map[string]json.RawMessage { + t.Helper() + var obj map[string]json.RawMessage + if err := json.Unmarshal(data, &obj); err != nil { + t.Fatal(err) + } + return obj + } + for _, tc := range []struct { + wire string + page debugger.VariablePage + }{ + {`{}`, debugger.VariablePage{}}, + {`{"filter":"indexed","start":1099511627776,"count":20}`, debugger.VariablePage{Filter: debugger.VariableFilterIndexed, Start: 1 << 40, Count: 20}}, + {`{"filter":"named"}`, debugger.VariablePage{Filter: debugger.VariableFilterNamed}}, + } { + var got debugger.VariablePage + if err := json.Unmarshal([]byte(tc.wire), &got); err != nil || got != tc.page { + t.Errorf("decode %s = %+v, %v, want %+v", tc.wire, got, err, tc.page) + } + data, err := json.Marshal(tc.page) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(fields(data), fields([]byte(tc.wire))) { + t.Errorf("encode %+v = %s, want fields of %s", tc.page, data, tc.wire) + } + } +} + +func TestVariableJSONPreservesExactChildNames(t *testing.T) { + for _, name := range []string{"", "before\x00after", "\uFFFD", "\u00E9", "e\u0301"} { + data, err := json.Marshal(debugger.Variable{Name: name}) + if err != nil { + t.Fatal(err) + } + // An omitted name must be distinguishable from a present empty key. + got := debugger.Variable{Name: "missing name"} + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + if got.Name != name { + t.Errorf("child name after JSON round trip = %q, want %q", got.Name, name) + } + } +} diff --git a/docs/debugger-inspection.md b/docs/debugger-inspection.md new file mode 100644 index 0000000..438b43a --- /dev/null +++ b/docs/debugger-inspection.md @@ -0,0 +1,249 @@ +# Debugger value inspection + +A paused session describes a value without reading its children. A caller +expands that value by requesting one bounded page. The Universal API owns this +contract. Core owns safe access to runtime values, Wire carries the same +operation, and clients decide when to expand a node. + +## Value metadata + +`debugger.Value` contains `Type string`, `Display string`, +`Reference ValueReference`, and optional `IndexedCount, NamedCount *int64`. +Locals, evaluation results and children all use this description. + +- `Type` is a semantic FQL or resource type. `Display` is a cheap summary, + such as `Array(1000000)`, `Object(42)` or `Binary(1024)`. An opaque resource + can supply a name such as `SQL::Rows`. Fallbacks must keep concrete Go types, + package paths and pointer strings private. + Both fields are valid UTF-8. The presentation budget bounds the work and + memory used to produce them, including validation, escaping and truncation. +- Counts are read-only, detached metadata snapshots. A nonnegative count gives + the exact number of children of that kind. Zero means known empty, and nil + means unknown. Counts may be omitted independently. A binary's byte length + in its display, for example, need not be a child count. +- A positive reference permits safe expansion in at least one mode. Zero means + there is no expansion. A known empty array has indexed count zero and + reference zero. A summary-only object can report a positive known size. + A safely pageable collection keeps its reference regardless of its size. + +## Pages + +```go +type VariableFilter string + +type VariablePage struct { + Filter VariableFilter + Start int64 + Count int64 +} + +// Session method in package debugger +Variables(ctx context.Context, reference ValueReference, page VariablePage) ([]Variable, error) +``` + +`VariablePage.Normalize() (VariablePage, error)` is the shared source of range +validation. `VariableFilterNamed` (`"named"`) selects named children and +`VariableFilterIndexed` (`"indexed"`) selects indexed children. +`VariableFilterAll` (the empty string) concatenates named then indexed children. +Apply the offset to the selected sequence. An absent kind on a valid reference +returns an empty page. + +`Start` is zero-based. An omitted or zero `Count` selects +`DefaultVariablePageSize` (100). The maximum is `MaxVariablePageSize` (1000). +An unknown filter, negative offset or count, count above the maximum, or +overflow of the exclusive end `Start + Count` after defaulting fails with +`ErrInvalidVariablePage`. Oversized requests must be split explicitly. + +A successful page contains the requested number of children or all that remain. +A short page establishes the end even when the count is unknown. An offset at +or beyond the end succeeds with zero children for a valid range. For a full +page, advance to its exclusive end and limit the next count to the representable +range. At `math.MaxInt64` no further positive count is representable. A mixed +collection may still have indexed children reachable using the indexed filter. +When the named prefix length is unknown, clients that require lossless +traversal can request separate filtered views from the start. +Reading a page never enumerates an unbounded prefix to reach the offset. + +Indexed names are the decimal, zero-based **source** indices. Named children +keep their exact UTF-8 keys in deterministic order throughout the stop. A key +with malformed UTF-8 fails the requested page with an ordinary child-read +error. A literal U+FFFD is a valid key. Validate keys only on the requested +page so a malformed key elsewhere leaves other addressable pages readable. +Preserve the key bytes across JSON and protobuf. Substitution, normalization +and truncation can merge distinct children. + +Repeated and overlapping pages agree on names, order and values. To obtain an +indexed child's source position, subtract the named prefix length from its +offset in the combined sequence. +Adding both counts can overflow even for a representable range. The named key +`"0"` and indexed child zero occupy distinct positions. Clients can request +each kind separately. A recognized mode whose order or boundary cannot be +determined safely fails with `errors.ErrUnsupported`. + +For example, suppose `results` is a local returned by `FrameLocals`. Its value +has type `Array`, display `Array(1000000)`, indexed count 1,000,000, named +count zero, and a positive reference. Describing it reads zero elements. This +request retrieves elements 1000 through 1019. + +```go +children, err := session.Variables(ctx, results.Value.Reference, debugger.VariablePage{ + Filter: debugger.VariableFilterIndexed, + Start: 1000, + Count: 20, +}) +if err != nil { + return err +} +fmt.Println(children[0].Name, children[19].Name) // 1000 1019 +``` + +Each child is itself metadata. Expanding a nested value requires another +request. A caller can retain a page as a read-only snapshot. Its entries, names, +summaries and counts remain readable and unchanged by later requests, resume +and close. Only the expansion handles expire. + +## Safety and ownership + +Core can read stable native arrays and VM-owned buffered datasets directly. +The paused session serializes inspection with resume. A host lending mutable +values must also keep their reachable storage stable for the stop, including +borrowed backing slices, or supply an existing stable inspection view. Without +that guarantee return reference zero and only independently safe metadata. Omit +counts that would touch unstable storage. Obtaining a stable view must respect +the same work bounds. + +The existing `runtime.DebugInspectable.DebugInfo` hook supplies presentation +only. A custom value can separately opt into debugger-safe access by +guaranteeing cheap metadata, stable order and bounded reads at arbitrary +offsets. Implementing `runtime.List`, `runtime.Map` or `runtime.Queryable` +alone makes no such guarantee. + +Metadata and page reads must leave the debuggee unchanged. They must never +run a query, consume an iterator, materialize a stream, perform external I/O, +invoke a user function or call an untrusted formatter or accessor. A cursor or +deferred query without a safe view gets a summary and reference zero. +`Evaluate` and `EvaluateFrame` remain explicit operations with their own +expression rules. + +Every reference belongs to its issuing session and paused state. Starting or +resuming execution, a replacement stop, termination or close invalidates the +old references. Never reuse an expired ID within the session. +`ValueReference.Valid()` checks the integer encoding only. During a live stop, +a zero, negative, unknown or expired ID fails with `ErrInvalidValueReference`. +Callers must keep session identity with each ID. Outside a paused state, +`Variables` returns a session-state error. + +Within a stop, reuse the child handle for the same parent reference, kind +and position across repeated or overlapping reads. Equivalent values under +different parents may have different handles. If an implementation exhausts +its handle budget or positive ID space, fail the operation atomically with a +resource error. Existing handles stay usable until the stop ends. + +The session orders concurrent reads and resume with its existing command +serialization. Check the non-nil context before and after admission, during +reads and before publication. Waiting for admission need not be interruptible. +Commit a page and its new handles together, ordered against termination and +close. A child error, cancellation, deadline or termination before commit +returns nil and an error. Request cancellation affects only that request. +Preserve context and inspection sentinel errors for `errors.Is`. Adapters must +check the stop generation before installing handles or updating a client tree. + +## Downstream migration + +- **Ferret Core.** The current formatter and reference allocator both call + `DebugValueAccess.Inspect`. Only complete, nonempty snapshots within the + format limit (eight items by default) get a handle. The VM also falls back + to a reflected Go type for buffered `data.DataSet`. Separate description, + reference eligibility and page reads in the VM accessor, debugger and + `uapi` adapter. Use array semantics and direct indexing for buffered + datasets. Propagate the request context and child read errors. Format only + a bounded prefix under Core's `MaxBytes`, including for host presentation + hints. Today's UTF-8 validation and repair traverse the whole input before + truncation. A shape with efficient ordered access can page in that order. + On explicit expansion Core may sort at most 128 unordered keys if both the + backing scan and key processing are bounded. Sparse or preallocated storage + can exceed that work even with few live keys. Use a summary for unordered + maps without a bounded path. The threshold belongs to Core. +- **Wire.** The v1 `Variables` RPC carries only a reference. Change the + canonical RPC, client, server and value conversions together. Carry the + filter, signed 64-bit range and presence-aware nonnegative 64-bit counts + through all debugger value paths. Validate at both ends using the shared + bounds, checked reference conversions and result-length checks. Preserve + distinguishable page, reference, unsupported, cancellation and deadline + errors. Check response text before encoding and bound response bytes + independently of the item limit. An oversized page fails delivery with a + resource error and no prefix. The hosted session may already have committed + its page when size validation, cancellation or transport failure prevents + delivery. Wire cannot roll back those handles. Retrying the same range within + the same stop reuses them. Task 4 needs a new Wire protocol revision that + rejects **both** new-client/old-server and old-client/new-server pairs before + use. Today the client accepts a nonempty protocol version and the server + checks an output-framing version. + A response-only version bump leaves old clients able to connect. +- **ferretd / DAP.** The current adapter rejects paging and filtering. Forward + the DAP filter and range to the session and apply the same selection to + named bindings on scope handles. Return the actual child name and semantic + display. An `evaluateName` must be a valid expression for that variable. + Emit semantic `type` when the client advertises `supportsVariableType`. + Reuse stop-scoped DAP handles for the same unchanged occurrence, including + virtual range nodes. Stage each response's new mappings together so handle + exhaustion preserves previously published mappings and returns no partial + response. Expose optional `indexedVariables` and `namedVariables` on + variables, scopes and evaluation results as applicable. + Check DAP's unsigned 32-bit ranges and nonnegative signed 32-bit child counts + and handles. Omit unrepresentable counts and preserve explicit zero where + reported (go-dap's `int,omitempty` needs a + presence-aware response). Honor `supportsVariablePaging` from client + initialization. [DAP specification](https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Variables) +- **DAP requests for all children.** Missing or zero DAP count means all, + including for clients that support paging. A short successful DAP page + signals the end. For clients that expand large or unknown groups without a + range, expose ordinary DAP virtual range or continuation nodes. Choose the + immediate children when issuing the handle and keep that view stable for + the stop. Its DAP counts, filters and offsets describe those immediate + children. Expanding a continuation reads its bounded page. With unknown + size, a full page can offer a continuation at the next representable offset. + Its first read may discover the end. + For mixed values with an unknown named count, an adapter can omit the + parent's optional counts and expose separate virtual named and indexed + groups so both are reachable. If a request exceeds the resource budget for + an already issued handle, fail the request. Silently capping a response + loses children, and fetching every page defeats the bound. +- **Editorium.** JetBrains currently requests only a reference, discards + counts and marks the first batch complete. Advertise paging, carry both + counts through scopes, locals and watches, and request subsequent ranges + on user demand. The platform's `tooManyChildren` callback accepts `-1` + for an unknown remainder. Preserve the existing stop-generation and + obsolete-node checks on every asynchronous result. VS Code forwards DAP + through the extension. Its native tree pages a positive indexed count, + fetches named children without a count, and requests all children when the + indexed count is absent. Exercise both local and Wire sessions with ranges, + unknown counts and stale replies. Ordinary collection expansion must omit + the DAP `lazy` evaluation hint. [JetBrains paging API](https://github.com/JetBrains/intellij-community/blob/master/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java) ยท [VS Code variable tree](https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/debug/common/debugModel.ts) +- **CLI.** The current debugger renders `Value.Display` for bindings and + evaluations. Updating the API and runtime dependencies gives it the same + semantic summaries without adding a variable tree. + +## Downstream acceptance + +- **Core.** Record reads from a million-element buffered dataset and confirm + that description reads none and the example page reads only its 20 elements. + Exercise a borrowed stable view and a summary-only provider whose backing + accessors must never run. Put a malformed raw key beside a literal U+FFFD + key. Verify the malformed key fails its page and the valid key succeeds on + its own page. Hold one page through another read, resume and close. + Re-read overlapping expandable children and verify retained handles plateau. + Fail or cancel after staging the first new child, exercise close winning + publication, and exhaust the handle budget and positive ID range. Check + atomic failure and preservation of earlier handles while the stop is live. + Benchmark short and multi-megabyte strings with `-benchmem` at a fixed byte + budget. Cover valid, escaped and late-malformed inputs. Time and allocated + bytes should stay bounded as input length grows. Construct inputs outside + the measured loop. +- **Wire.** Round-trip the exact valid key and propagate the producer's + malformed-key error without a partial page. Force a delivery failure after + hosted success, then retry during the same stop and check handle reuse. +- **ferretd and Editorium.** Repeat expansions with overlapping pages and + exhaust DAP handles without evicting earlier ones. Exercise delayed replies + across resume or close and verify that a new stop never displays the old + children. From c5d735e4b0abb1155177dede95a8331bf3ae91b6 Mon Sep 17 00:00:00 2001 From: Tim Voronov Date: Tue, 17 Nov 2026 21:13:02 -0500 Subject: [PATCH 2/2] Clarify debugger root reference reuse and filtered expansion --- debugger/inspection_contract_test.go | 46 ++++++++++++++++++++++++++++ debugger/session.go | 13 ++++++-- debugger/types.go | 4 ++- docs/debugger-inspection.md | 25 ++++++++++++--- 4 files changed, 80 insertions(+), 8 deletions(-) diff --git a/debugger/inspection_contract_test.go b/debugger/inspection_contract_test.go index 7bc579c..3fc61b6 100644 --- a/debugger/inspection_contract_test.go +++ b/debugger/inspection_contract_test.go @@ -3,6 +3,7 @@ package debugger_test import ( "context" "errors" + "fmt" "math" "slices" "strconv" @@ -23,6 +24,13 @@ func (s inspectionFixture) Locals(context.Context) ([]debugger.Variable, error) return []debugger.Variable{{Name: "results", Value: s.value}}, nil } +func (s inspectionFixture) FrameLocals(ctx context.Context, frame int) ([]debugger.Variable, error) { + if frame != 0 { + return nil, fmt.Errorf("fixture has no frame %d", frame) + } + return s.Locals(ctx) +} + func (s inspectionFixture) Variables(ctx context.Context, ref debugger.ValueReference, page debugger.VariablePage) ([]debugger.Variable, error) { if err := ctx.Err(); err != nil { return nil, err @@ -40,9 +48,11 @@ func (s inspectionFixture) Variables(ctx context.Context, ref debugger.ValueRefe func TestInspectionReadsOnlyTheRequestedMillionElementArrayPage(t *testing.T) { length, noNames := int64(1_000_000), int64(0) var reads []int64 + var pageCalls int var session debugger.Session = inspectionFixture{ value: debugger.Value{Type: "Array", Display: "Array(1000000)", Reference: 1, IndexedCount: &length, NamedCount: &noNames}, read: func(page debugger.VariablePage) ([]debugger.Variable, error) { + pageCalls++ if page.Filter == debugger.VariableFilterNamed { return nil, nil } @@ -59,6 +69,19 @@ func TestInspectionReadsOnlyTheRequestedMillionElementArrayPage(t *testing.T) { t.Fatalf("Locals = %v, %v; child reads = %v", locals, err, reads) } value := locals[0].Value + if !value.Reference.Valid() { + t.Fatalf("array reference = %d", value.Reference) + } + topFrame := func(ctx context.Context) ([]debugger.Variable, error) { return session.FrameLocals(ctx, 0) } + for _, list := range []func(context.Context) ([]debugger.Variable, error){topFrame, session.Locals, topFrame} { + bindings, err := list(t.Context()) + if err != nil || len(bindings) != 1 || pageCalls != 0 { + t.Fatalf("relisted bindings = %v, %v; page calls = %d", bindings, err, pageCalls) + } + if binding := bindings[0]; binding.Name != locals[0].Name || binding.Value.Reference != value.Reference { + t.Fatalf("relisted binding = %v, want %s with reference %d", binding, locals[0].Name, value.Reference) + } + } if value.IndexedCount == nil || *value.IndexedCount != 1_000_000 || value.NamedCount == nil || *value.NamedCount != 0 { t.Fatalf("array counts = %+v", value) } @@ -141,6 +164,29 @@ func TestInspectionContinuesAtSignedBoundaryWithIndexedFilter(t *testing.T) { } } +func TestInspectionUsesIndexedViewAfterUnsupportedCombinedRange(t *testing.T) { + combined := debugger.VariablePage{Start: 1000, Count: 2} + indexed := debugger.VariablePage{Filter: debugger.VariableFilterIndexed, Start: 0, Count: 2} + session := inspectionFixture{value: debugger.Value{Reference: 1}, read: func(page debugger.VariablePage) ([]debugger.Variable, error) { + switch page { + case combined: + return nil, fmt.Errorf("cannot locate the named/indexed boundary: %w", errors.ErrUnsupported) + case indexed: + return []debugger.Variable{{Name: "0"}, {Name: "1"}}, nil + default: + return nil, fmt.Errorf("unexpected page %+v", page) + } + }} + got, err := session.Variables(t.Context(), session.value.Reference, combined) + if got != nil || !errors.Is(err, errors.ErrUnsupported) { + t.Fatalf("combined page = %v, %v; want nil and unsupported", got, err) + } + got, err = session.Variables(t.Context(), session.value.Reference, indexed) + if err != nil || len(got) != 2 || got[0].Name != "0" || got[1].Name != "1" { + t.Fatalf("first indexed page = %v, %v", got, err) + } +} + func TestInspectionErrorResults(t *testing.T) { // This stop issued reference 2. Reference 1 belonged to the previous stop. session := inspectionFixture{value: debugger.Value{Reference: 2}} diff --git a/debugger/session.go b/debugger/session.go index c15e586..c863623 100644 --- a/debugger/session.go +++ b/debugger/session.go @@ -58,7 +58,14 @@ type Session interface { // Nil or canceled contexts return an error. Breakpoints(ctx context.Context) ([]Breakpoint, error) Frames(ctx context.Context) ([]Frame, error) + + // Locals is equivalent to FrameLocals(ctx, 0), including the references + // returned for expandable bindings. Locals(ctx context.Context) ([]Variable, error) + + // FrameLocals lists a frame's visible bindings. Within one stop, repeated + // listings reuse the reference for each unchanged expandable local or + // bound parameter in that frame. FrameLocals(ctx context.Context, frame int) ([]Variable, error) // Variables reads one bounded page of immediate children in the current @@ -67,8 +74,10 @@ type Session interface { // beyond the end returns an empty page. A short successful page means the // selected sequence is exhausted, including when its length is unknown. // Recognized modes that cannot be paged safely return an error matching - // errors.ErrUnsupported. Invalid, unknown, or expired references while - // paused return an error matching ErrInvalidValueReference. + // errors.ErrUnsupported. If VariableFilterAll is unsupported, request + // VariableFilterNamed or VariableFilterIndexed on the same reference, + // using offsets within that kind. Invalid, unknown, or expired references + // while paused return an error matching ErrInvalidValueReference. // // Callers may retain the page as a read-only snapshot. Its slice entries // and counts remain readable across later calls, resume, and Close. Only diff --git a/debugger/types.go b/debugger/types.go index 638fada..3fb75da 100644 --- a/debugger/types.go +++ b/debugger/types.go @@ -28,7 +28,9 @@ type ( // Display is a cheap, bounded summary. Collection summaries can use a // cheaply known size without previewing elements. Display string `json:"display"` - // Reference is positive when safe, bounded expansion is available. + // Reference is positive when at least one paging mode is safe and bounded. + // A named or indexed view may be available even if VariableFilterAll + // is unsupported. // A known empty collection or a summary-only value has reference zero. Reference ValueReference `json:"reference"` diff --git a/docs/debugger-inspection.md b/docs/debugger-inspection.md index 438b43a..b6ef319 100644 --- a/docs/debugger-inspection.md +++ b/docs/debugger-inspection.md @@ -76,9 +76,16 @@ Repeated and overlapping pages agree on names, order and values. To obtain an indexed child's source position, subtract the named prefix length from its offset in the combined sequence. Adding both counts can overflow even for a representable range. The named key -`"0"` and indexed child zero occupy distinct positions. Clients can request -each kind separately. A recognized mode whose order or boundary cannot be -determined safely fails with `errors.ErrUnsupported`. +`"0"` and indexed child zero occupy distinct positions. + +A recognized mode whose order or boundary cannot be determined safely returns +an error matching `errors.ErrUnsupported`. A positive reference may support +only the named or indexed view. If a `VariableFilterAll` request fails, check +`errors.Is(err, errors.ErrUnsupported)`. On a match, try `VariableFilterNamed` +or `VariableFilterIndexed` on the same reference. Start the new view at offset +zero, even if its count is unknown, and track its pages separately from any +combined results. A short or empty page ends only that kind. Propagate other +errors. For example, suppose `results` is a local returned by `FrameLocals`. Its value has type `Array`, display `Array(1000000)`, indexed count 1,000,000, named @@ -133,8 +140,14 @@ a zero, negative, unknown or expired ID fails with `ErrInvalidValueReference`. Callers must keep session identity with each ID. Outside a paused state, `Variables` returns a session-state error. -Within a stop, reuse the child handle for the same parent reference, kind -and position across repeated or overlapping reads. Equivalent values under +Within a stop, repeated frame listings reuse the root handle for each +unchanged expandable local or bound parameter in that frame. `Locals(ctx)` +and `FrameLocals(ctx, 0)` list the same bindings and share their references. +The guarantee applies to each binding in its own frame, including recursive +calls with identically named locals. + +Reuse the child handle for the same parent reference, kind and position +across repeated or overlapping reads in the stop. Equivalent values under different parents may have different handles. If an implementation exhausts its handle budget or positive ID space, fail the operation atomically with a resource error. Existing handles stay usable until the stop ends. @@ -232,6 +245,8 @@ check the stop generation before installing handles or updating a client tree. accessors must never run. Put a malformed raw key beside a literal U+FFFD key. Verify the malformed key fails its page and the valid key succeeds on its own page. Hold one page through another read, resume and close. + Alternate `Locals` and `FrameLocals(0)`, and repeat a caller-frame listing. + Verify that refreshing unchanged bindings allocates no additional root handles. Re-read overlapping expandable children and verify retained handles plateau. Fail or cancel after staging the first new child, exercise close winning publication, and exhaust the handle budget and positive ID range. Check