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:
- choose the cheapest tool that can answer the current debugging question;
- reduce a failure to a focused, reproducible case;
- start a debug session and place useful source-line breakpoints;
- inspect variables, scopes, stack frames, and control flow;
- evaluate expressions without confusing observation with mutation;
- use step, next, continue, and step-out deliberately;
- explain the role of the Debug Adapter Protocol;
- separate source-level and VM-oriented debugging;
- preserve protocol channels and sensitive data; and
- produce evidence that a correction fixes the root cause without regression.
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:
- format the source;
- run static checking;
- read the complete diagnostic;
- reproduce the problem with the smallest relevant input;
- predict the expected control flow and state;
- add temporary safe observations or assertions when sufficient; and
- open a debugger when the remaining question requires execution state.
4.2 Classify the question
| Question | Best 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:
- the exact source version;
- the command or host entry point;
- the smallest input that triggers the issue;
- expected behavior;
- actual behavior;
- relevant permissions and limits;
- whether the interpreter, VM, or both are affected; and
- whether the result is deterministic.
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:
- which branch should be active;
- which loop iteration is running;
- which names should exist in each scope;
- which values should have changed; and
- which invariants should hold.
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:
- the first line of a suspicious function;
- a conditional that selects the wrong branch;
- an update that breaks an invariant;
- the first statement inside a catch block;
- the statement before a failing host call;
- the iteration where observed state first diverges; or
- the return that produces an invalid boundary value.
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 current function;
- its arguments and locals;
- the caller that supplied them;
- the source location in each frame; and
- the point where a value first became incorrect.
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
- Pause before the condition.
- Inspect every operand used by the condition.
- Evaluate the complete boolean expression.
- Confirm precedence and short-circuit behavior.
- Step into the selected block.
- Verify related outputs are updated together.
- Check that later branches are skipped.
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:
- the exception originates where expected;
- statements after the failing operation are skipped;
- the catch binding contains safe source context;
- recovery state is complete and consistent;
- finally runs exactly once; and
- unrecoverable failures still propagate.
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:
- the converted input shape;
- required and optional fields;
- permissions;
- resource limits;
- the selected export or host function;
- the returned portable value; and
- output validation before side effects.
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
| Surface | Use for |
|---|---|
| pea debug | Focused source-file investigation |
| pea dap | Source-level editor integration |
| pea vm-dap | VM-oriented debugging and compiled execution |
| Disassembly and bytecode inspection | Instruction-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:
- use the same source and inputs;
- capture deterministic outputs;
- compare success or error category;
- compare boundary values and side effects;
- reduce the program to the smallest divergence;
- inspect compiled instructions when needed; and
- add a conformance regression test.
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:
- focused on one hypothesis;
- free of secrets and sensitive records;
- deterministic;
- removed or converted into tests afterward; and
- kept away from protocol channels.
4.27 Common mistakes
- Opening a debugger before reproducing the issue: first establish a stable case.
- Stepping without a hypothesis: predict state before observing it.
- Setting breakpoints on comments or blank lines: choose executable statements.
- Watching too much state: focus on variables that can disprove the hypothesis.
- Mutating state through evaluation: prefer side-effect-free expressions.
- Continuing past the first divergence: investigate where state first becomes wrong.
- Printing to the DAP channel: preserve protocol framing.
- Raising resource limits immediately: inspect workload and termination first.
- Fixing the symptom only: add a regression test for the root cause.
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.
- Reproduce with one record that makes all conditions true.
- Check formatting and static diagnostics.
- Place a breakpoint before the first branch.
- Inspect security_relevant, impact, users, and named boolean intermediates.
- Evaluate each condition.
- Step through the branch chain.
- Observe whether a broad high-impact rule appears before the security rule.
- Restore approved precedence.
- Run overlap and boundary tests.
- Add a regression test requiring SECURITY to win.
4.29 Debugging record
For a nontrivial defect, keep a short investigation record:
- symptom;
- reproduction;
- expected and actual result;
- hypothesis;
- breakpoints and observations;
- first divergent state;
- root cause;
- correction;
- regression tests; and
- remaining uncertainty.
4.30 Guided practice
- Choose format, check, run, debug, DAP, or VM tools for ten scenarios.
- Select a useful breakpoint for a wrong branch result.
- Explain when to use next instead of step in.
- Trace a three-frame call stack and locate the first bad argument.
- Design side-effect-free watch expressions for a loop.
- Explain why debugger evaluation should not mutate state.
- Create an interpreter/VM comparison plan.
- Write a regression test from a root-cause finding.
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:
- one reversed precedence rule;
- one exact-threshold operator error;
- one counter updated after a possible continue;
- one selected total omitted from a category aggregate;
- one catch path that fails to set item status; and
- one finally block that incorrectly marks success.
Requirements:
- Format and check before execution.
- Create the smallest dataset that exposes each defect.
- Write a state hypothesis.
- Choose breakpoints and watch expressions.
- Identify the first divergent state.
- Correct one root cause at a time.
- Run focused and full regression tests.
- Compare interpreter and VM results for the corrected source.
- Record no sensitive data in output or the investigation log.
Deliverable: Defect matrix, reproductions, breakpoint plan, state traces, corrections, regression evidence, engine comparison, and a concise debugging report.
4.32 Review questions
- Why should formatting and checking precede debugging?
- What makes a reproduction useful?
- Why write a state hypothesis before stepping?
- What makes a source line a useful breakpoint?
- How do next and step in differ?
- What does a stack frame explain?
- Why should debugger evaluation avoid side effects?
- Why must standard streams remain clean for DAP?
- When should VM-oriented tools be used?
- Why is a regression test part of debugging completion?
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.