Debugging Legacy Code with Large Language Models: A Practical Workflow

    This article shares a practical workflow for using large language models to debug legacy code that has never run successfully. It explains why taking over existing code is harder than generating from scratch, then walks through two rounds of work: an initial code review that moves the program from unrunnable to basically runnable, and a refinement pass focused on input handling, rendering performance, robustness, and maintainability. It includes typical failure patterns such as early exit caused by stale framebuffer pointers and protocol identifier mismatches, along with acceptance criteria and five constraints that make AI-assisted troubleshooting reliable.

    1. Why Taking Over Legacy Code Is Harder Than Generating From Scratch

    Writing a program from scratch and taking over code left by someone else that has never run successfully are two very different tasks. The first only requires generation ability. The second requires the model to understand the existing structure first, then locate the problem, validate hypotheses, and converge step by step.

    The scenario behind this practice was a low-level program related to graphical output. A previous round generated by an AI coding tool left seven files with a clear modular structure, but the build environment was never set up and no runnable artifact was produced. Another AI coding tool, used through a command-line assistant workflow, took over with a simple goal: get the program running first, then refine it.

    This kind of situation is common in real engineering work. Staff turnover, outsourced delivery, assembled open-source snippets, and internal tool migrations all produce assets that have code but do not run. For developers, what matters is not which model writes it correctly on the first try, but whether the model has a verifiable troubleshooting loop.

    2. Round One: From Unrunnable to Basically Runnable

    2.1 Review the Code First, Do Not Modify It Immediately

    The first instruction after taking over should be a review, not a change. Ask the model to inspect module by module: entry point, main loop, business logic, rendering, and input handling, then output a problem list with priorities.

    This has three benefits:

    • It builds a global understanding and avoids treating symptoms in isolation.
    • It classifies problems as environment, logic, or resource issues, which makes ordering easier.
    • It produces a trackable fix list that helps prevent regressions.

    In practice, solve “can it start” first, then “can it display”, and only then handle interaction and experience.

    2.2 Typical Problem One: Immediate Exit and Memory Lifetime

    A program that prints its startup log and then exits immediately is a classic early-exit failure. Adding serial debug output narrowed the exit point to just after a certain protocol call.

    A common root cause in low-level graphics programming is this: a mode query returns a pointer to mode information, then the mode is switched, but the memory that pointer refers to is no longer valid, so continuing to use it is a wild pointer access. The correct approach is to re-fetch the framebuffer information after the mode switch instead of reusing the pointer from before it.

    Illustrative code (conceptual only, not a specific API):

    1. // Wrong approach: reuse the info pointer from before the switch
    2. info = query_mode(handle, mode);
    3. set_mode(handle, mode);
    4. use_framebuffer(info); // info may already be invalid
    5. // Correct approach: re-fetch after the switch
    6. set_mode(handle, mode);
    7. info = query_mode(handle, mode);
    8. use_framebuffer(info);

    The general lesson is that for any “query, change, then use” chain, you must confirm whether the change invalidated the handle, pointer, or descriptor.

    2.3 Typical Problem Two: Wrong Protocol Identifier Configuration

    When the program runs but no interface appears, the problem is often not in the rendering logic but in failing to obtain the correct capability object. Low-level frameworks usually define a set of identifier constants related to graphical output, and choosing the wrong one causes protocol lookup failures or abnormal behavior.

    Troubleshooting suggestions:

    1. Print the result of every handle acquisition to confirm whether the failure happens during lookup or during the call.
    2. Check whether the identifiers used match the framework version.
    3. Add null and status-code validation to key return values to avoid silent failures.

    2.4 Round One Acceptance Criteria

    • The build passes in one go with no hidden pile-up of warnings.
    • The process does not crash and the main loop runs stably.
    • Key resource acquisitions all have error-handling branches.
    • Serial output or logs can fully reconstruct the startup path.

    3. Round Two: Refinement and Experience Optimization

    Running is only the starting point. Common work in the second round includes:

    • Input handling: key debouncing, repeat-trigger suppression, focus and event dispatch.
    • Rendering performance: dirty rectangle updates, avoiding full-screen redraws, double buffering and tearing handling.
    • Logic robustness: boundary checks, collision detection, completeness of state machine transitions.
    • Maintainability: replacing magic numbers with constants, extracting repeated flows into functions, adding comments and log levels.

    During refinement, use a rhythm of small commits plus verification at each step. Change only one class of problem at a time, so that stacking multiple changes does not make attribution impossible.

    4. Five Constraints That Make AI Troubleshooting Reliable

    1. Fix the environment first: lock the toolchain, build scripts, and dependency versions in one pass to reduce variables.
    2. Keep a minimal reproduction: compress the problem to the smallest input and shortest path.
    3. Observability before guessing: logs and breakpoints come before speculation; measure first, then optimize.
    4. Make hypotheses explicit: require the model to state what it thinks the cause is and how it will verify it.
    5. Keep a regression checklist: after fixing one problem, run the existing acceptance items again.

    If you use a cloud development environment, you can combine a container platform to standardize the build environment, object storage to keep build artifacts, and logging services with monitoring alerts to track runtime metrics, making the troubleshooting process reproducible and auditable. The general cloud product categories offered by Baidu AI Cloud in this kind of development support scenario can serve as a reference for environment standardization and observability work.

    5. Conclusion

    Which model writes it correctly on the first try is not the key engineering metric. What matters is whether a loop of review, hypothesis, verification, and regression can be formed. Legacy code is not the real problem; a lack of observability and acceptance criteria is. Once those two are in place, any AI coding tool can become a reliable troubleshooting assistant.