Testing Procedural Correctness in Code Generation with Geometric Construction Tasks

    Geometric construction tasks provide a rigorous way to evaluate whether generated code follows a required process rather than merely producing a visually correct result. This article explains how to translate natural-language requirements into executable steps, implement construction animations with Canvas 2D, validate geometric constraints numerically, avoid common failure modes, export deterministic GIFs, and design a more reliable evaluation framework for code-generation systems.

    1. Background

    When evaluating the coding capabilities of generative models, a common approach is to ask the model to produce a web page, such as an animation, chart, or interactive utility. These tasks are easy to inspect visually, but they do not reliably show whether the implementation is correct internally. A page can look right while its underlying logic violates the requirements.

    Geometric construction tasks are well suited to testing this distinction. Their rules are explicit: each step may use only a specified set of tools, and every point must be derived from objects that have already been established. Evaluators can verify the construction step by step, distinguishing between something that merely looks correct and something that was produced correctly according to the rules.

    2. Breaking Down the Task: From Natural Language to Executable Steps

    A typical requirement description contains three types of information:

    1. Objects: a square, the perpendicular bisector of a base, or a circle centered at a specified point.
    2. Operations: draw a circle with a given center and a line segment as its radius, or position a marked ruler so that it passes through a specified line.
    3. Output requirements: retain only the necessary traces and export the result as an animation file.

    Before implementation, organize these elements into an ordered step table. Each step should specify its input objects, constraints, and output objects. This table serves both as the basis for coding and as the basis for later validation.

    For example, a regular heptagon cannot be constructed exactly using only a compass and an unmarked straightedge. This follows from the constructibility criterion established by Gauss and Wantzel. Such tasks therefore typically introduce a marked ruler and use a method in which the ruler is slid until two marked points satisfy the required constraints. This method is known as neusis construction.

    The implementation challenge is that this step is not a closed-form formula. It is a numerical solving process.

    3. Rendering and Animation

    Canvas 2D is a practical choice for rendering. The scene should be divided into two types of elements:

    • Static elements: coordinate axes, the square, and perpendicular bisectors that have already been established.
    • Dynamic elements: the position of the marked ruler, controlled by a parameter t. For each frame, recompute the relevant intersection points from t and update the scene.

    Preserving construction traces is an error-prone part of the implementation. Intermediate states from auxiliary motion should remain hidden, while only the segments that must be retained should be written to a persistent canvas.

    A common approach is to maintain two canvases:

    1. An offscreen canvas that stores permanent construction traces.
    2. A main canvas that redraws the offscreen content on every frame and then overlays the current dynamic elements.

    The following example calculates the vertices of a regular polygon:

    1. // Calculate the vertices of a regular n-gon.
    2. // (cx, cy) is the center and r is the circumradius.
    3. function polygonVertices(cx, cy, r, n) {
    4. const pts = [];
    5. for (let k = 0; k < n; k++) {
    6. const theta = (2 * Math.PI * k) / n - Math.PI / 2;
    7. pts.push({ x: cx + r * Math.cos(theta), y: cy + r * Math.sin(theta) });
    8. }
    9. return pts;
    10. }

    4. Constraint Validation: More Important Than the Final Image

    Validation should cover the geometric condition at every step, not only the final shape. Two basic checks are shown below:

    1. // Check whether point p lies on the circle centered at c with radius r.
    2. function onCircle(p, c, r, eps = 1e-6) {
    3. return Math.abs(Math.hypot(p.x - c.x, p.y - c.y) - r) < eps;
    4. }
    5. // Check whether point p lies on the line passing through a and b.
    6. // The check uses the point-to-line distance.
    7. function onLine(p, a, b, eps = 1e-6) {
    8. const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
    9. const len = Math.hypot(b.x - a.x, b.y - a.y);
    10. return Math.abs(cross) / len < eps;
    11. }

    The object of validation is the construction process. Every intermediate point should record its source, such as “the intersection of circle E and line l.” This makes it possible to detect a rule violation even when the final figure appears correct.

    The correctness of the polygon can also be verified numerically. In a regular polygon, all side lengths should be equal, and all vertices should be at the same distance from the center:

    1. // Calculate the lengths of consecutive sides.
    2. function sideLengths(pts) {
    3. return pts.map((p, i) => {
    4. const q = pts[(i + 1) % pts.length];
    5. return Math.hypot(q.x - p.x, q.y - p.y);
    6. });
    7. }
    8. const sides = sideLengths(polygonVertices(0, 0, 1, 7));
    9. const isEquilateral = sides.every(s => Math.abs(s - sides[0]) < 1e-9);

    5. Common Failure Modes

    Failures in these tasks generally fall into several categories:

    • Visually correct, procedurally incorrect: the program directly calls a polygon-drawing function and skips the required construction steps. The image is the same, but the implementation does not satisfy the task.
    • Incorrect step order: a later step uses an object that has not yet been established, relying on a default value or an approximation instead.
    • Incorrect trace retention: intermediate auxiliary circles are not removed, or a segment that should be preserved is omitted.
    • Animation stuttering or stopping: reasoning or numerical solving takes too long, causing discontinuous frame updates.

    Assertions can be added to the code to address these issues, along with validation logs for every step. Logs make it easier to locate the exact failure than simply inspecting the final image.

    6. Exporting the Animation

    Animation export typically follows this process: render the canvas frame by frame at a fixed frame rate, extract the pixel data from each frame, and pass the frames to a general-purpose GIF encoding library.

    Three points require particular attention:

    1. Dimensions and frame rate: larger dimensions or higher frame rates significantly increase file size and encoding time.
    2. Color palette: GIF supports up to 256 colors. Smooth gradients and antialiased edges may produce banding, so color quantization may be required before encoding.
    3. Synchronization: export should use a fixed time parameter t rather than a real-time clock. This ensures that repeated exports produce the same frame sequence.

    7. Evaluation and Engineering Recommendations

    When using these tasks to evaluate code-generation capabilities, consider the following principles:

    1. Use layered scoring: evaluate structural completeness, procedural compliance, numerical error, and rendering/export quality separately instead of assigning only one overall score.
    2. Run multiple trials: execute the same prompt multiple times and measure the success rate and failure types. Do not draw conclusions from a single output.
    3. Record the environment: preserve the prompt version, execution time, and output length to support reproduction and comparison.
    4. Retain logs: validation logs should be saved as part of the evaluation artifacts so that failure patterns can be analyzed later.

    8. Conclusion

    Geometric construction tasks break the question of “is this correct?” into conditions that can be checked one step at a time. In engineering practice, the key is to convert requirements into an explicit step table, validate every step with numerical assertions, and distinguish a correct result from a correct process.

    The same approach can be applied to other visual tasks that must follow strict rules.