Verifying G-Code Programmatically: Simulation, Collision, and Toolpath Checks

Verifying G-Code Programmatically: Simulation, Collision, and Toolpath Checks

G-code is the final instruction set between a design intent and a physical part. A single malformed block can crash a spindle, scrap a workpiece, or, in the worst case, injure an operator. For AI systems generating or reasoning about G-code, verifying G-code programmatically is not optional post-processing. It is the only mechanism that separates a plausible-looking output from a usable one. This post describes the verification stack: simulation, collision detection, and toolpath geometric checks, and how each layer catches a distinct class of failure.

Answer Capsule: Verifying G-code programmatically requires three layered checks: static parsing and syntax validation, kinematic simulation to reconstruct the tool path in 3D space, and collision detection against the stock, fixtures, and machine envelope. Each layer catches failures the others miss. No single check is sufficient. Verification must be re-run against the specific machine, tooling, and material context because G-code is not portable across configurations.

Why G-Code Verification Cannot Be Reduced to Syntax Checking

Syntax validity is necessary but not sufficient. A G-code file can be syntactically correct, parse without errors, and still command the tool to plunge through a fixture clamp at full feed rate. The failure mode is not textual. It is geometric and kinematic.

Verification must operate at three distinct levels:

  1. Lexical and syntax layer: block structure, modal state consistency, address validity, and feed/speed within machine limits.

  2. Kinematic simulation layer: reconstruct the continuous tool path by resolving modal G-codes across all blocks, then check that the path is geometrically coherent.

  3. Collision and envelope layer: intersect the swept tool volume against the stock model, fixture geometry, and machine travel limits.

Each layer is a prerequisite for the next. Skipping simulation and jumping to collision detection against a raw G-code file is not possible: collision detection requires a reconstructed 3D path, not a text stream.

Static Parsing: What It Catches and What It Misses

Static parsing resolves modal state and validates that every commanded value is within declared machine parameters. It is fast, deterministic, and automatable without a geometry kernel.

A minimal static checker should enforce the following:

  • Modal group consistency: G0 and G1 are in the same modal group; both cannot be active simultaneously in a single block.

  • Feed rate presence: any G1, G2, or G3 move must have an active F-word, either in the current block or carried from a prior block.

  • Spindle state: a cutting move must follow an M3 or M4 command; a move with spindle stopped is a crash waiting to execute.

  • Axis limits: commanded XYZ positions must fall within the machine's declared travel envelope.

  • Tool change protocol: T-word and M6 must appear in the correct sequence for the controller dialect.

What static parsing cannot catch: a tool path that is geometrically valid but cuts air for 90 percent of its length, or a finishing pass that re-enters the part at the wrong depth because a Z-retract was omitted.

Kinematic Simulation: Reconstructing the Toolpath in 3D Space

Kinematic simulation is the core of verifying G-code programmatically. It processes the G-code block by block, maintains the full modal state, and outputs a continuous 3D representation of the tool center point (TCP) trajectory and the swept tool volume.

The simulation must handle:

  • Coordinate system offsets: G54 through G59 work offsets transform machine coordinates to part coordinates. A verifier that ignores these will report incorrect absolute positions.

  • Cutter radius compensation: G41 and G42 offset the TCP by the tool radius perpendicular to the direction of travel. The compensated path is what actually cuts; the programmed path is not.

  • Arc interpolation: G2 and G3 arcs are defined by center offsets (I, J, K) or radius (R). Both representations have known ambiguity cases that must be resolved per the controller's documented behavior.

  • Canned cycles: G81 through G89 drilling cycles expand to multi-move sequences. A verifier must expand them, not skip them.

The output of simulation is a polyline or spline approximation of the TCP path, plus the swept volume of the tool geometry along that path. This is the input to collision detection.

Illustrative Example: Cutter Radius Compensation Failure

Illustrative example with constructed values for clarity.

Suppose a pocket finishing pass is programmed with G41 (left compensation) and a tool radius of 6 mm. The programmed path passes within 4 mm of a wall. Without compensation applied, the path clears the wall. With compensation applied, the tool center moves 6 mm to the left of the programmed line, resulting in a 2 mm interference with the wall. A static parser sees no error. Kinematic simulation with compensation applied detects the interference before any metal is cut.

Collision Detection: Three Intersection Problems

Collision detection in G-code verification is three distinct intersection problems, each requiring different geometry and different reference models.

Collision Type

What Is Intersected

Reference Geometry Required

Consequence if Missed

Tool-stock collision

Swept tool volume vs. remaining stock

Stock solid model, updated per operation

Incorrect material removal, dimensional error

Tool-fixture collision

Swept tool volume vs. fixture and clamp geometry

Fixture solid model in work coordinates

Broken tool, damaged fixture, machine crash

Machine envelope violation

TCP trajectory vs. machine travel limits

Machine kinematic model and travel limits

Hard limit fault, axis crash

Tool-stock collision is the most computationally intensive because the stock geometry changes with each operation. Accurate detection requires a dexel model or a constructive solid geometry (CSG) representation that is updated incrementally as material is removed. Using the raw stock solid for every operation produces false positives on every cut that correctly removes material.

Fixture collision detection is frequently omitted in lightweight verifiers. It is also the most likely cause of a machine crash in a real shop, because fixtures are set up by the operator and their geometry is not always captured in the CAM system. For AI-generated G-code, fixture collision is a primary failure mode: the model has no reliable way to infer fixture geometry from the part drawing alone.

Toolpath Geometric Checks Beyond Collision

Collision absence does not confirm toolpath correctness. A collision-free path can still fail to produce the intended part. Geometric correctness checks compare the simulated material removal result against the target geometry.

Key checks include:

  • Undercut detection: regions of the target geometry that the programmed path never reaches, leaving excess material.

  • Overcut detection: regions where the tool removes material that should remain, producing a dimensional violation.

  • Surface normal deviation: for 3-axis finishing passes, the angle between the tool axis and the surface normal determines scallop height; paths that deviate from the intended stepover produce surface finish failures.

  • Re-entry gouge: when the tool re-enters the part after a retract, the entry angle and feed rate must not produce a gouge at the re-entry point.

  • Rapid move over stock: G0 rapid moves should not pass through or near the stock; a rapid that grazes the stock is a crash at the highest possible feed rate.

For AI-generated toolpaths, undercut and overcut detection are the highest-signal checks. Frontier models frequently produce paths that are geometrically plausible but miss features or violate tolerances on complex surfaces. These failures are invisible to syntax parsers and are only detected by comparing the simulated result against the target solid. The post on process supervision in engineering workflows describes how intermediate verification steps can be embedded into the generation loop rather than applied only at the end.

Common Failure Modes in Programmatic G-Code Verification

The following failure modes appear repeatedly in verification pipelines, both in production CAM systems and in AI-evaluation harnesses.

1. Modal state not initialized before parsing begins. G-code files often assume a known machine state from a prior program or operator setup. A verifier that starts with an undefined modal state will misinterpret early blocks. Detection: check whether the program opens with a full initialization block (G17 G21 G40 G49 G80 G90 or equivalent). Fix: inject a canonical initialization state before parsing, and document the assumption.

2. Controller dialect mismatch. Fanuc, Heidenhain, Siemens, and Haas controllers implement G-code differently. Arc center interpretation, canned cycle behavior, and macro syntax all vary. Detection: confirm the target controller dialect before running simulation. Fix: maintain a dialect configuration layer in the verifier, not hardcoded assumptions.

3. Tool geometry not matched to the program. A verifier using a default 10 mm flat endmill when the program was written for a 6 mm ball endmill will produce incorrect swept volumes. Detection: cross-reference the T-word and tool table against the actual tool geometry used in the CAM setup. Fix: require a tool library file as a mandatory input to the verifier, not an optional one.

4. Fixture geometry absent from the collision model. Lightweight verifiers check tool-stock intersection only. Detection: run a deliberate test case with a known fixture interference and confirm the verifier flags it. Fix: require fixture geometry as a mandatory input; if it is unavailable, document the gap explicitly rather than silently omitting the check.

5. Incremental coordinate mode not tracked. G91 switches the interpreter to incremental coordinates. A verifier that does not track this transition will compute absolute positions incorrectly for all subsequent blocks. Detection: include a test case with a G91/G90 transition. Fix: modal state tracking must include the distance mode as a first-class variable.

6. Verification result treated as machine-independent. A program verified against one machine configuration is not verified for another. Different machines have different travel limits, spindle orientations, and fixture offsets. Detection: re-run verification whenever the target machine changes. Fix: encode the machine identity as part of the verification record, and invalidate prior results on machine change.

Designing verifiers that catch these failure modes reliably is non-trivial. The post on hybrid verifiers combining programmatic checks and expert rubrics addresses cases where programmatic checks are necessary but not sufficient, and where human expert review must be layered in.

Where Programmatic Verification Breaks Down

Programmatic verification is reliable within its scope. That scope has hard limits.

Verification cannot confirm that the programmed part matches the engineering intent if the input geometry or drawing was incorrect to begin with. Garbage-in, garbage-out applies at the design level, not only the G-code level.

Verification cannot assess machinability: whether the programmed feeds and speeds will produce acceptable surface finish, tool life, or chip evacuation for the specific material and tooling combination. These require physics-based process simulation or expert judgment, not geometric checking.

Verification against a nominal fixture model does not account for setup variation. If the operator places the part 2 mm off the nominal position, a verified program may still crash.

For AI-generated G-code used in training or evaluation pipelines, these limits matter. A task that is marked correct by a programmatic verifier may still be wrong in ways the verifier cannot see. The post on verifying synthetic data through expert spot audits describes how sampling-based human review can catch the residual failures that automated checks miss. Similarly, for AI systems reasoning over CAD geometry upstream of G-code generation, verifiable geometry checks for LLM-generated CAD scripts addresses the upstream verification problem.

Frequently Asked Questions

What is the minimum viable G-code verifier for an AI evaluation task?

A minimum viable verifier for AI evaluation must cover: syntax and modal state validation, kinematic simulation with cutter radius compensation and canned cycle expansion, and tool-stock collision detection using an updated stock model. Fixture collision and geometric accuracy checks against the target solid are required for tasks that claim to evaluate full toolpath correctness. A syntax-only verifier is insufficient for evaluation purposes.

Can a language model verify its own G-code output?

Not reliably. Language models can perform lexical checks and flag obvious syntax errors, but they cannot simulate kinematics or perform geometric intersection. Self-verification by the generating model is not a substitute for a deterministic simulation-based verifier. The failure modes that matter most, collision and undercut, are geometric problems that require a geometry kernel, not a language model.

How should G-code verification results be used as a reward signal in RL training?

Verification results can serve as a binary or graded reward: syntax-valid, collision-free, and dimensionally correct are three separable conditions that can be weighted. Process reward models can assign partial credit for reaching each verification layer. The verifier must be deterministic and fast enough to run at training throughput. Results vary by machine configuration, so the reward signal must be tied to a specific machine context.

What makes G-code evaluation tasks hard for frontier models?

G-code is hard because correctness is contextual: the same block is correct on one machine and incorrect on another. Models must reason about modal state across hundreds of blocks, resolve cutter compensation geometry, and produce paths that are collision-free in 3D space. These are not language tasks. They require spatial and kinematic reasoning that current frontier models handle unreliably, particularly for multi-setup programs and complex surface finishing.

How do you calibrate the difficulty of a G-code evaluation task?

Difficulty is measured empirically by running the task against several frontier models and recording pass rates per verification layer. A task where all models pass syntax validation but none produce a collision-free path is a well-calibrated hard task. Difficulty is not fixed: it drifts as models improve, so calibration must be repeated periodically against current model versions.

What This Means in Practice

Verifying G-code programmatically requires a layered stack: static parsing catches modal and syntax errors, kinematic simulation reconstructs the actual tool path, and collision detection confirms the path is safe in 3D space. Each layer is necessary. None is sufficient alone. For AI systems generating or evaluating G-code, the verifier design determines the quality of the signal, not the volume of examples.

The hardest tasks are not the ones with complex syntax. They are the ones where the G-code is syntactically clean, kinematically valid, and still wrong because the toolpath misses a feature or violates a tolerance that only a dimensional check against the target solid would catch. Building verifiers that reach that layer is where the real work is.

Chiron Data Labs builds expert-authored G-code and CNC/CAM tasks with verification stacks designed to catch failures at every layer. If you are building evals or RL environments in this domain, get in touch with Chiron Data Labs.

Have questions or want personalised guidance? Contact us and we'll be happy to help.

G-code is the final instruction set between a design intent and a physical part. A single malformed block can crash a spindle, scrap a workpiece, or, in the worst case, injure an operator. For AI systems generating or reasoning about G-code, verifying G-code programmatically is not optional post-processing. It is the only mechanism that separates a plausible-looking output from a usable one. This post describes the verification stack: simulation, collision detection, and toolpath geometric checks, and how each layer catches a distinct class of failure.

Answer Capsule: Verifying G-code programmatically requires three layered checks: static parsing and syntax validation, kinematic simulation to reconstruct the tool path in 3D space, and collision detection against the stock, fixtures, and machine envelope. Each layer catches failures the others miss. No single check is sufficient. Verification must be re-run against the specific machine, tooling, and material context because G-code is not portable across configurations.

Why G-Code Verification Cannot Be Reduced to Syntax Checking

Syntax validity is necessary but not sufficient. A G-code file can be syntactically correct, parse without errors, and still command the tool to plunge through a fixture clamp at full feed rate. The failure mode is not textual. It is geometric and kinematic.

Verification must operate at three distinct levels:

  1. Lexical and syntax layer: block structure, modal state consistency, address validity, and feed/speed within machine limits.

  2. Kinematic simulation layer: reconstruct the continuous tool path by resolving modal G-codes across all blocks, then check that the path is geometrically coherent.

  3. Collision and envelope layer: intersect the swept tool volume against the stock model, fixture geometry, and machine travel limits.

Each layer is a prerequisite for the next. Skipping simulation and jumping to collision detection against a raw G-code file is not possible: collision detection requires a reconstructed 3D path, not a text stream.

Static Parsing: What It Catches and What It Misses

Static parsing resolves modal state and validates that every commanded value is within declared machine parameters. It is fast, deterministic, and automatable without a geometry kernel.

A minimal static checker should enforce the following:

  • Modal group consistency: G0 and G1 are in the same modal group; both cannot be active simultaneously in a single block.

  • Feed rate presence: any G1, G2, or G3 move must have an active F-word, either in the current block or carried from a prior block.

  • Spindle state: a cutting move must follow an M3 or M4 command; a move with spindle stopped is a crash waiting to execute.

  • Axis limits: commanded XYZ positions must fall within the machine's declared travel envelope.

  • Tool change protocol: T-word and M6 must appear in the correct sequence for the controller dialect.

What static parsing cannot catch: a tool path that is geometrically valid but cuts air for 90 percent of its length, or a finishing pass that re-enters the part at the wrong depth because a Z-retract was omitted.

Kinematic Simulation: Reconstructing the Toolpath in 3D Space

Kinematic simulation is the core of verifying G-code programmatically. It processes the G-code block by block, maintains the full modal state, and outputs a continuous 3D representation of the tool center point (TCP) trajectory and the swept tool volume.

The simulation must handle:

  • Coordinate system offsets: G54 through G59 work offsets transform machine coordinates to part coordinates. A verifier that ignores these will report incorrect absolute positions.

  • Cutter radius compensation: G41 and G42 offset the TCP by the tool radius perpendicular to the direction of travel. The compensated path is what actually cuts; the programmed path is not.

  • Arc interpolation: G2 and G3 arcs are defined by center offsets (I, J, K) or radius (R). Both representations have known ambiguity cases that must be resolved per the controller's documented behavior.

  • Canned cycles: G81 through G89 drilling cycles expand to multi-move sequences. A verifier must expand them, not skip them.

The output of simulation is a polyline or spline approximation of the TCP path, plus the swept volume of the tool geometry along that path. This is the input to collision detection.

Illustrative Example: Cutter Radius Compensation Failure

Illustrative example with constructed values for clarity.

Suppose a pocket finishing pass is programmed with G41 (left compensation) and a tool radius of 6 mm. The programmed path passes within 4 mm of a wall. Without compensation applied, the path clears the wall. With compensation applied, the tool center moves 6 mm to the left of the programmed line, resulting in a 2 mm interference with the wall. A static parser sees no error. Kinematic simulation with compensation applied detects the interference before any metal is cut.

Collision Detection: Three Intersection Problems

Collision detection in G-code verification is three distinct intersection problems, each requiring different geometry and different reference models.

Collision Type

What Is Intersected

Reference Geometry Required

Consequence if Missed

Tool-stock collision

Swept tool volume vs. remaining stock

Stock solid model, updated per operation

Incorrect material removal, dimensional error

Tool-fixture collision

Swept tool volume vs. fixture and clamp geometry

Fixture solid model in work coordinates

Broken tool, damaged fixture, machine crash

Machine envelope violation

TCP trajectory vs. machine travel limits

Machine kinematic model and travel limits

Hard limit fault, axis crash

Tool-stock collision is the most computationally intensive because the stock geometry changes with each operation. Accurate detection requires a dexel model or a constructive solid geometry (CSG) representation that is updated incrementally as material is removed. Using the raw stock solid for every operation produces false positives on every cut that correctly removes material.

Fixture collision detection is frequently omitted in lightweight verifiers. It is also the most likely cause of a machine crash in a real shop, because fixtures are set up by the operator and their geometry is not always captured in the CAM system. For AI-generated G-code, fixture collision is a primary failure mode: the model has no reliable way to infer fixture geometry from the part drawing alone.

Toolpath Geometric Checks Beyond Collision

Collision absence does not confirm toolpath correctness. A collision-free path can still fail to produce the intended part. Geometric correctness checks compare the simulated material removal result against the target geometry.

Key checks include:

  • Undercut detection: regions of the target geometry that the programmed path never reaches, leaving excess material.

  • Overcut detection: regions where the tool removes material that should remain, producing a dimensional violation.

  • Surface normal deviation: for 3-axis finishing passes, the angle between the tool axis and the surface normal determines scallop height; paths that deviate from the intended stepover produce surface finish failures.

  • Re-entry gouge: when the tool re-enters the part after a retract, the entry angle and feed rate must not produce a gouge at the re-entry point.

  • Rapid move over stock: G0 rapid moves should not pass through or near the stock; a rapid that grazes the stock is a crash at the highest possible feed rate.

For AI-generated toolpaths, undercut and overcut detection are the highest-signal checks. Frontier models frequently produce paths that are geometrically plausible but miss features or violate tolerances on complex surfaces. These failures are invisible to syntax parsers and are only detected by comparing the simulated result against the target solid. The post on process supervision in engineering workflows describes how intermediate verification steps can be embedded into the generation loop rather than applied only at the end.

Common Failure Modes in Programmatic G-Code Verification

The following failure modes appear repeatedly in verification pipelines, both in production CAM systems and in AI-evaluation harnesses.

1. Modal state not initialized before parsing begins. G-code files often assume a known machine state from a prior program or operator setup. A verifier that starts with an undefined modal state will misinterpret early blocks. Detection: check whether the program opens with a full initialization block (G17 G21 G40 G49 G80 G90 or equivalent). Fix: inject a canonical initialization state before parsing, and document the assumption.

2. Controller dialect mismatch. Fanuc, Heidenhain, Siemens, and Haas controllers implement G-code differently. Arc center interpretation, canned cycle behavior, and macro syntax all vary. Detection: confirm the target controller dialect before running simulation. Fix: maintain a dialect configuration layer in the verifier, not hardcoded assumptions.

3. Tool geometry not matched to the program. A verifier using a default 10 mm flat endmill when the program was written for a 6 mm ball endmill will produce incorrect swept volumes. Detection: cross-reference the T-word and tool table against the actual tool geometry used in the CAM setup. Fix: require a tool library file as a mandatory input to the verifier, not an optional one.

4. Fixture geometry absent from the collision model. Lightweight verifiers check tool-stock intersection only. Detection: run a deliberate test case with a known fixture interference and confirm the verifier flags it. Fix: require fixture geometry as a mandatory input; if it is unavailable, document the gap explicitly rather than silently omitting the check.

5. Incremental coordinate mode not tracked. G91 switches the interpreter to incremental coordinates. A verifier that does not track this transition will compute absolute positions incorrectly for all subsequent blocks. Detection: include a test case with a G91/G90 transition. Fix: modal state tracking must include the distance mode as a first-class variable.

6. Verification result treated as machine-independent. A program verified against one machine configuration is not verified for another. Different machines have different travel limits, spindle orientations, and fixture offsets. Detection: re-run verification whenever the target machine changes. Fix: encode the machine identity as part of the verification record, and invalidate prior results on machine change.

Designing verifiers that catch these failure modes reliably is non-trivial. The post on hybrid verifiers combining programmatic checks and expert rubrics addresses cases where programmatic checks are necessary but not sufficient, and where human expert review must be layered in.

Where Programmatic Verification Breaks Down

Programmatic verification is reliable within its scope. That scope has hard limits.

Verification cannot confirm that the programmed part matches the engineering intent if the input geometry or drawing was incorrect to begin with. Garbage-in, garbage-out applies at the design level, not only the G-code level.

Verification cannot assess machinability: whether the programmed feeds and speeds will produce acceptable surface finish, tool life, or chip evacuation for the specific material and tooling combination. These require physics-based process simulation or expert judgment, not geometric checking.

Verification against a nominal fixture model does not account for setup variation. If the operator places the part 2 mm off the nominal position, a verified program may still crash.

For AI-generated G-code used in training or evaluation pipelines, these limits matter. A task that is marked correct by a programmatic verifier may still be wrong in ways the verifier cannot see. The post on verifying synthetic data through expert spot audits describes how sampling-based human review can catch the residual failures that automated checks miss. Similarly, for AI systems reasoning over CAD geometry upstream of G-code generation, verifiable geometry checks for LLM-generated CAD scripts addresses the upstream verification problem.

Frequently Asked Questions

What is the minimum viable G-code verifier for an AI evaluation task?

A minimum viable verifier for AI evaluation must cover: syntax and modal state validation, kinematic simulation with cutter radius compensation and canned cycle expansion, and tool-stock collision detection using an updated stock model. Fixture collision and geometric accuracy checks against the target solid are required for tasks that claim to evaluate full toolpath correctness. A syntax-only verifier is insufficient for evaluation purposes.

Can a language model verify its own G-code output?

Not reliably. Language models can perform lexical checks and flag obvious syntax errors, but they cannot simulate kinematics or perform geometric intersection. Self-verification by the generating model is not a substitute for a deterministic simulation-based verifier. The failure modes that matter most, collision and undercut, are geometric problems that require a geometry kernel, not a language model.

How should G-code verification results be used as a reward signal in RL training?

Verification results can serve as a binary or graded reward: syntax-valid, collision-free, and dimensionally correct are three separable conditions that can be weighted. Process reward models can assign partial credit for reaching each verification layer. The verifier must be deterministic and fast enough to run at training throughput. Results vary by machine configuration, so the reward signal must be tied to a specific machine context.

What makes G-code evaluation tasks hard for frontier models?

G-code is hard because correctness is contextual: the same block is correct on one machine and incorrect on another. Models must reason about modal state across hundreds of blocks, resolve cutter compensation geometry, and produce paths that are collision-free in 3D space. These are not language tasks. They require spatial and kinematic reasoning that current frontier models handle unreliably, particularly for multi-setup programs and complex surface finishing.

How do you calibrate the difficulty of a G-code evaluation task?

Difficulty is measured empirically by running the task against several frontier models and recording pass rates per verification layer. A task where all models pass syntax validation but none produce a collision-free path is a well-calibrated hard task. Difficulty is not fixed: it drifts as models improve, so calibration must be repeated periodically against current model versions.

What This Means in Practice

Verifying G-code programmatically requires a layered stack: static parsing catches modal and syntax errors, kinematic simulation reconstructs the actual tool path, and collision detection confirms the path is safe in 3D space. Each layer is necessary. None is sufficient alone. For AI systems generating or evaluating G-code, the verifier design determines the quality of the signal, not the volume of examples.

The hardest tasks are not the ones with complex syntax. They are the ones where the G-code is syntactically clean, kinematically valid, and still wrong because the toolpath misses a feature or violates a tolerance that only a dimensional check against the target solid would catch. Building verifiers that reach that layer is where the real work is.

Chiron Data Labs builds expert-authored G-code and CNC/CAM tasks with verification stacks designed to catch failures at every layer. If you are building evals or RL environments in this domain, get in touch with Chiron Data Labs.

Have questions or want personalised guidance? Contact us and we'll be happy to help.

© 2026 CHIRON, SAN FRANCISCO, CA