PeaBox Lab › PeaLang › Learn › Chapter 6 › Lesson 4

Part II — Intermediate Development · Chapter 6 · Lesson 4 of 5 · 10 min read

Lesson 4: Debugging with the CLI, Debugger, and Debug Adapter Protocol

Lesson level: Intermediate

Purpose: Investigate reproducible failures systematically by combining formatting, checking, focused execution, breakpoints, state inspection, stack analysis, expression evaluation, and editor integration.

Learning objectives

By the end of this lesson, you should be able to:

4.1 Debugging begins before the debugger

A debugger is one investigation tool, not the first response to every failure. Begin with the lowest-cost signal:

4.2 Classify the question

QuestionBest first tool
Is the source formatted canonically?pea fmt --check
Is the source structurally or semantically invalid?pea check
Does a small program produce the wrong result?Focused run and state trace
Which branch or loop iteration is selected?Breakpoint and stepping
Which call supplied the incorrect value?Stack and scope inspection
Does compiled execution differ?Interpreter/VM comparison and VM tools
Does an editor need debugger integration?Debug Adapter Protocol

4.3 Build a reproducible case

A useful reproduction states:

Remove unrelated code without changing the failure. A small reproduction shortens every later debugging step.

4.4 Establish a state hypothesis

Before stepping, write what you expect at the suspected line. For example:

Debugging is a comparison between predicted and observed state. Without a prediction, stepping can become aimless.

4.5 Start a source debug session

The command-line entry point is:

pea debug FILE

To register a source-line breakpoint at startup:

pea debug FILE --break=LINE

Use one or more breakpoints on executable lines. Confirm that the source version and line numbers match the file being run.

4.6 Choosing breakpoints

A useful breakpoint is close to a decision or state transition:

Avoid setting many speculative breakpoints. Begin near the earliest known divergence and expand only when necessary.

4.7 Executable versus non-executable lines

Headings, blank lines, comments, and some declaration boundaries do not correspond to executable behavior. A breakpoint on a non-executable line may move to a nearby statement or may never trigger.

Choose a line with an expression, assignment, print, call, branch body, loop body, throw, or return.

4.8 Continue

Continue resumes execution until the next breakpoint, termination, exception, or other stop event. Use it when intermediate statements are not relevant to the current question.

Do not repeatedly continue past the earliest unexplained divergence. Once observed state is wrong, inspect how it became wrong.

4.9 Next

Next executes the current source statement without entering a called function’s internal steps. Use it when the call is trusted and only its returned effect matters.

If next produces an unexpected result, repeat with step-in at the call boundary.

4.10 Step in

Step in enters a called function when source is available. Use it to inspect argument binding, local scope, branch selection, and intermediate calculations inside the call.

Avoid stepping into every library call. Enter only when evidence points to that call or when its contract is uncertain.

4.11 Step out

Step out runs until the current function returns to its caller. Use it after the function’s behavior is understood or when the caller’s handling of the return value is now the important question.

4.12 Stack frames

A stack frame represents an active function call. The stack shows how execution reached the current point. Inspect:

The innermost frame shows the immediate failure; outer frames explain the calling context.

4.13 Scopes and variables

Inspect the nearest active scope first, then enclosing scopes. Distinguish local shadowing from assignment to an outer binding. For loop iterations, confirm that the iteration variable has the expected value and lifetime.

Record only the variables relevant to the hypothesis. Large unfiltered state dumps can hide the decisive difference and expose sensitive data.

4.14 Expression evaluation

A debugger can evaluate an expression in the paused context. Useful questions include:

service_impact >= high_impact_threshold
valid_count + invalid_count
len(selected_items)
denominator != 0

Prefer side-effect-free expressions. Evaluation that mutates state can change the failure and invalidate the investigation.

4.15 Watches and repeated state

When a value changes across iterations or calls, track the same small set of expressions at each stop. Examples include a counter, accumulator, progress measure, selected count, current key, and invariant result.

A state table often reveals the first incorrect transition faster than inspecting isolated snapshots.

4.16 Debugging branches

4.17 Debugging loops

Track initialization, condition, body state, update, invariant, and progress measure. For while loops, ensure every continuing path advances. For for loops, inspect the iterable and current item.

When the failure appears late, use a conditional investigation strategy: reduce the dataset, break near the suspected iteration, or add a temporary guarded assertion. Do not step manually through thousands of ordinary iterations.

4.18 Debugging exceptions

Pause before the operation expected to throw and again at the catch block. Confirm:

4.19 Debugging assertions

An assertion failure marks the point where an internal assumption became observably false. The root cause may be earlier. Inspect the variables in the assertion, then work backward to the earliest transition that could break the invariant.

Do not remove a correct assertion merely to let execution continue.

4.20 Debugging boundary values

At an exported-function or host-call boundary, inspect:

Do not expose raw host objects, credentials, or unrestricted reflection for debugging convenience.

4.21 Source-level DAP

Start the source-level Debug Adapter Protocol service with:

pea dap

A compatible editor or IDE communicates with the adapter using framed protocol messages over standard input and output. The adapter supports initialization, launch, breakpoints, continue, next, step in, step out, threads, stack traces, scopes, variables, expression evaluation, disconnect, and termination.

4.22 Preserve the protocol channel

DAP traffic uses standard streams. Unrelated print statements from the adapter process can corrupt framing. Send human logs through an approved separate channel and keep protocol output reserved for protocol messages.

This separation is an integration requirement, not merely a formatting preference.

4.23 Source debugger versus VM debugger

SurfaceUse for
pea debugFocused source-file investigation
pea dapSource-level editor integration
pea vm-dapVM-oriented debugging and compiled execution
Disassembly and bytecode inspectionInstruction-level and compiler/VM analysis

Start with source-level tools for application behavior. Escalate to VM tools when the issue is specific to compiled execution, bytecode, or interpreter/VM parity.

4.24 Interpreter/VM differential debugging

When both engines should behave identically:

4.25 Resource-limit debugging

A timeout or resource-limit failure may indicate an infinite loop, unexpectedly large input, recursion, excessive output, repeated host calls, or an intentionally small test budget.

Record which budget failed and the workload that consumed it. Do not solve every limit failure by raising limits. First determine whether the algorithm and input bounds are correct.

4.26 Safe temporary instrumentation

Temporary print statements and assertions can help when they are:

4.27 Common mistakes

4.28 Worked example: Wrong priority at an overlap

A case is security-relevant and also exceeds impact and user thresholds, but the program returns high rather than critical.

4.29 Debugging record

For a nontrivial defect, keep a short investigation record:

4.30 Guided practice

4.31 Hands-on lab: Debug a fault-tolerant scoring pipeline

Scenario: A scoring pipeline validates records, catches per-record provider failures, calculates priority, and maintains accounting totals. A temporary defective version contains:

Requirements:

Deliverable: Defect matrix, reproductions, breakpoint plan, state traces, corrections, regression evidence, engine comparison, and a concise debugging report.

4.32 Review questions

4.33 Applied challenge

Create a debugging playbook for the Chapter 6 fault-tolerant import processor. Cover source errors, invalid data, thrown exceptions, incorrect recovery, broken cleanup, permission denial, instruction exhaustion, interpreter/VM divergence, and editor-based DAP investigation. For each category, specify the first tool, evidence to capture, safe observations, stopping criteria, and required regression test.

Lesson summary

Effective debugging is disciplined evidence gathering. Start with formatting, checking, and a minimal reproduction; predict state; break near the earliest divergence; inspect focused scopes and stack frames; step deliberately; preserve protocol channels; and escalate to VM tools only when the evidence requires it. A correction is complete only when focused and regression tests demonstrate that the root cause is removed.

Next lesson: Chapter 6 Checkpoint — Fault-Tolerant Import Processor

The checkpoint will combine diagnostic categories, structured exception handling, assertions, boundary validation, debugging, recovery accounting, and safe operational evidence in one import-processing project.

Lesson status: Ready for review.

← Previous Next →