Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
219 changes: 219 additions & 0 deletions debugger/inspection_contract_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
package debugger_test

import (
"context"
"errors"
"fmt"
"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) 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
}
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 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
}
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.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)
}
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 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}}
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)
}
}
37 changes: 35 additions & 2 deletions debugger/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -58,9 +58,42 @@ 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(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. 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
// 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)
}
25 changes: 21 additions & 4 deletions debugger/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,31 @@ 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 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"`

// 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"`
Expand Down
2 changes: 1 addition & 1 deletion debugger/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
9 changes: 8 additions & 1 deletion debugger/value_reference.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Loading
Loading