AI-Assisted Debugging for LLM-Generated Code: A Complete Fix Workflow from Broken Code to Runnable Programs

    This article presents a practical two-round workflow for repairing LLM-generated code that fails to compile or run. It covers structured code review, resolving dangling pointer issues after graphics protocol calls, matching protocol GUIDs across environments, and first-round acceptance criteria based on repeatable startup and observability. It then explains optimization techniques such as event queues, double buffering, and graceful fallback, followed by four principles for AI-assisted debugging. The goal is to turn AI from a code generator into a controllable engineering partner.

    1. When AI Coding Moves into Deep Water: From “Can It Generate?” to “Can It Run?”

    LLM-driven coding tools are evolving from code completion toward end-to-end task delivery. Developers increasingly care about one core question: when AI-generated code fails to compile or run, can it repair itself through multiple rounds of interaction instead of being rewritten from scratch? In real projects, the code pass rate on the first attempt, the first-run success rate, and the efficiency of crash localization often affect final delivery more than generation speed.

    This article starts with a typical scenario: an AI generated a structurally complete game program, but it never launched in the target hardware environment. Another model was asked to take over this “mess” and complete the repair and refinement without rewriting it. The practice is divided into two rounds: the first focuses on “making the program run,” and the second focuses on “making it stable and well-behaved.”

    2. Round One: From Dead Code to Runnable — Building a “Discover-Fix-Verify” Loop for AI-Assisted Debugging

    2.1 Code Review: Make the AI Answer “Can This Code Run?” First

    After moving the failed code into a new environment unchanged, the first step is not to rush into edits, but to have the model perform a structured review. An effective prompt should include three elements: review scope, output format, and risk priority. For example:

    1. Please review this code, module by module: entry point, main loop, game logic, rendering, input.
    2. Output a list of issues, sorted by "whether it blocks execution," and provide a fix suggestion for each issue.

    The issue list returned by the model typically includes: null pointer or dangling pointer risks, unchecked return values, timing errors in the hardware state machine, incorrect resource initialization order, and inconsistent macro definitions between compile time and runtime. The value of this step is to turn “guessing wrong” into “guessing right,” providing direction for subsequent debugging instead of forcing developers to inspect every function manually.

    2.2 Memory and Dangling Pointers: Resource Invalidation After Graphics Interface Calls

    After startup, the program enters the main loop but crashes shortly afterward. After having the model add logs and breakpoints, the problem was located after a graphics protocol call: the struct pointer returned by the mode query became invalid after the mode was set, and subsequent access triggered an exception.

    The essence of this type of issue is “cross-interface lifecycle management”: the buffer description obtained during the query phase is no longer guaranteed to be valid after the mode switch. There are two repair strategies: one is to re-fetch the latest framebuffer information after each state switch; the other is to proactively cache necessary fields before switching to avoid relying on subsequent calls. In real engineering, the former is recommended because it aligns with the state machine semantics of the hardware/firmware and reduces hidden assumptions.

    Illustrative fix logic:

    1. status = query_mode(handle, want_mode, &info);
    2. status = set_mode(handle, want_mode);
    3. /* Re-fetch to avoid dangling pointer */
    4. status = query_mode(handle, want_mode, &info);
    5. framebuffer = info->frame_buffer;

    2.3 No Graphical Interface Appears: GUID and Protocol Mismatch

    The program no longer crashes, but there is no output on screen. Logs show that the graphics protocol handle was obtained successfully, but the actual drawing took a fallback path. Further investigation revealed that the protocol GUID used during initialization did not match the interface version exposed by the current environment, causing the call to be silently downgraded.

    The solution is “probe first, then match”: during startup, enumerate the graphics protocols that actually exist in the system table, and record their versions and capability bits; then select the drawing backend (hardware framebuffer, pseudo-linear framebuffer, or text output) based on the capability bits. Avoiding hardcoding a single GUID is key to cross-environment compatibility.

    1. Initialization flow:
    2. 1. Enumerate available graphics protocols
    3. 2. Read version and pixel format
    4. 3. If version < expected, switch to compatibility mode
    5. 4. Bind drawing callback

    2.4 Round One Acceptance Criteria: Repeatable Startup and Observability

    The end of round one is not marked by “it happened to run once,” but by “multiple consecutive cold starts all enter the main loop and keep running.” It is recommended to add three observability measures: tiered serial log output, instrumentation at key state machine transitions, and automatic stack trace or error code output on crash. This way, even if round-two optimizations introduce regressions, they can be located quickly.

    3. Round Two: Refinement and Optimization — From “Runs” to “Stable and Long-Running”

    3.1 Input Latency and Feel: Event Queue and Polling Frequency

    Game programs are sensitive to input latency. In the refinement phase, an event queue can be introduced to decouple input collection from logic updates: interrupts or polling are only responsible for enqueueing, and the main loop consumes them uniformly. This avoids time-consuming waits on the critical drawing path and prevents lost keypresses.

    3.2 Frame Rate and Tearing: Double Buffering and Present Timing

    If the runtime environment supports it, prefer double buffering: draw in the background and present in the foreground to avoid tearing from “drawing while displaying.” If not supported, fall back to dirty rectangle refresh, updating only changed regions to reduce bandwidth pressure.

    3.3 Resources and Exceptions: Turning “Occasional Crashes” into “Diagnosable Errors”

    The refinement phase should add: tiered fallback for initialization failures (downgrade to text mode when graphics are unavailable), out-of-bounds access protection (clamp coordinates for boundary balls and blocks), and timeout and retry mechanisms (add limited retries for protocol calls and record error codes).

    4. Methodology: Four Principles of AI-Assisted Debugging

    1. Review first, act later: Have the model output an “issue list + priority” to turn debugging from blind scanning into targeted investigation.
    2. Fix one class of issues at a time: Verify crashes, display, and input separately to avoid attribution failure caused by changing multiple variables at once.
    3. Logs first: Add logs at key state machines and interface boundaries so the model can reason based on facts rather than guesses.
    4. Keep it rollback-able: Retain snapshots and change notes for each round of modifications to facilitate comparison and review.

    5. Conclusion: The Next Stop for AI Coding Is “Controllable Engineering Collaboration”

    From failed code to a runnable program, and then to an optimizable, maintainable engineering artifact, the value of LLMs is not just “writing more,” but “fixing accurately, repairing quickly, and explaining clearly.” When developers distill their experience in review, debugging, and verification into prompts and workflows, AI upgrades from a “code generator” to an “engineering collaboration partner.” In R&D practice on cloud platforms such as Baidu AI Cloud, combining such workflows with log services, monitoring alerts, and containerized deployment can further turn individual experience into reusable team-level capabilities, bringing AI-assisted coding into a controllable, measurable, and reproducible engineering stage.