Manuscript Offprint
arXiv:2610.28675Compilation Is Not Correctness: Scan-by-Scan Evaluation of LLM-Generated PLC Programs
Jinyun Chen , Juntao Hu , Haochen Li , Wentao Song , Ningbo Gu , Jianwei Niu , Qing Gao , Rui Wang
Beihang University, Beijing, China
Hangzhou Innovation Institute, Beihang University, Hangzhou, China
Programmable logic controllers (PLCs) automate industrial processes through repeated scans, each reading inputs, executing control logic, and updating outputs. Engineers typically write this logic in Structured Text (ST), a high-level textual language defined in IEC 61131-3. Large language models (LLMs) can now generate ST from natural-language requirements, yet compilation success and checks on selected properties or sampled scans can leave behavioral errors undetected. To close this evaluation gap, we introduce CycleBench, a benchmark of 301 ST tasks with behavioral requirements, public interfaces, reference programs, and executable scenarios. Its runtime executes each generated program and its reference under aligned inputs, initialization, and logical time, comparing their outputs after every scan. Across eight LLMs and baseline generation methods, execution pass rate trails compilation pass rate by 11.92 percentage points; observed failures include output-update, arithmetic, and timing errors. On fixed traces of programs directly generated by five LLMs, checking outputs only at every fifth scan misses 21.66% of the 157 failures detected by per-scan comparison; across sampling phases, the missed-failure rate ranges from 12.10% to 28.03%. These misses stem from transient output discrepancies, whose detection depends on the sampling phase. Building on this evaluation, we propose CycleGen, which generates multiple candidate ST programs, repairs their compilation errors with bounded compiler feedback, and selects one using runtime self-tests generated in a separate model context. CycleGen improves the execution pass rate over direct generation by 8.68 percentage points. Component ablations distinguish repair and self-test selection; candidate-count analysis shows diminishing returns, with no execution-pass-rate improvement beyond five candidates in our experiments despite 38.8% higher token consumption at eight.
CCS Concepts: • Software and its engineering → Software testing and debugging; Automatic programming.
Additional Key Words and Phrases: Structured Text, programmable logic controllers, large language models, LLMs for software engineering, code generation, benchmarking
1 Introduction
Programmable logic controllers (PLCs) serve as core control devices in industrial manufacturing, automating industrial processes in repeated scans: each scan reads inputs, executes control logic, and updates outputs. Structured Text (ST) [15], a high-level textual language defined by IEC 61131-3, is widely used for PLC programming. ST's Pascal-like syntax supports control algorithms, computation, and data processing; function-block instances retain state across calls [39]. ST is also a target of model-based code generation: Simulink PLC Coder generates ST from Simulink models, Stateflow charts, and MATLAB functions [36]. With advances in large language models (LLMs), generating code from natural-language requirements has become an active research direction [7]. This progress has also motivated research on ST code generation for PLCs. However, reliably translating control requirements into behaviorally correct ST programs remains an important challenge [23, 37].
To address this challenge, existing LLM-based PLC generation methods incorporate compilation, formal verification, or runtime testing into their workflows. LLM4PLC [12] and Agents4PLC [29] use formal-verification feedback, AutoPLC [40] repairs code using vendor-compiler diagnostics, and SemaPLC combines specification, compilation, and runtime checks [38]. These mechanisms provide
Corresponding author.
different kinds of evidence: compilation establishes that a program builds, property checking addresses the encoded properties, and runtime testing checks behavior on the executions and scans observed. However, differences in task sets and acceptance criteria make their reported success rates difficult to compare directly. Moreover, agreement at selected scans can conceal incorrect intermediate outputs in stateful PLC programs. This motivates a common benchmark that evaluates generated programs on shared tasks and checks their outputs against the same behavioral requirements after every scan.
Specifically, Fig. 1 illustrates how compilation and checks on selected properties or scans can miss incorrect intermediate outputs. On a rising edge, a shift register copies D0 into Q0 and the previous Q0-Q2 into Q1-Q3; set and reset override shifting. The reference assigns outputs in reverse order to preserve old values. A program generated directly by GPT-4o assigns them forward, starting with Q0 := D0, so the new value propagates through all four bits. After set yields 1111 at scan 11, a shift with D0= 0 produces 0000 instead of 0111 at scan 12 (bits ordered Q0-Q3); reset at scan 14 restores agreement. The program compiles, completes execution, and ends with the reference's outputs, yet scans 12–13 differ. A specification of the shift relation could also detect this error: the verdict depends on which behavior is checked and when.
Prompt: Implement a four-stage shift register.

Fig. 1. A shift-register failure. The reference preserves old bits; forward assignments propagate a new value. Panel A illustrates a property-checking pipeline, not a measured model-checker result. Panel B shows set, shift, hold, and reset; reset conceals intermediate disagreement. Bits are ordered Q0–Q3.
To measure these differences consistently, we introduce CycleBench: 301 ST tasks with reviewed public specifications, hidden references, and 684 scenarios spanning 61,424 scans. A separate evaluator compares every declared output after each scan under aligned inputs, initialization, and logical time. Across eight LLMs and four baseline configurations, 83.99% of 9,632 outcomes compile but only 72.07% pass execution, a gap of 11.92 percentage points. On fixed traces of 157 Direct behavioral failures from five models, final-scan checking misses 98 failures; checking every fifth scan at phase zero misses 34, even with scenario endpoints retained. We then investigate whether runtime feedback can improve ST code generation when the generator does not have access to hidden references or evaluation scenarios. Therefore, we propose CycleGen, which adapts generated-test selection and feedback-guided repair [6, 8]. It generates multiple candidates, repairs compilation failures, and selects one using runtime self-tests authored beforehand in a separate model context. The tests are withheld from code generation, and the reference evaluator stays hidden. CycleGen raises execution pass rate from Direct's 74.63% to 83.31%; controlled-pool ablations and candidate-count analyses separate component effects and inference cost.
In particular, this work makes the following contributions:
• CycleBench. To our knowledge, the first benchmark for LLM-based Structured Text generation with comprehensive per-scan behavioral evaluation against hidden references, comprising 301 tasks with reviewed specifications.
• CycleGen. A framework combining multiple candidates, compiler repair, and runtime self-tests, with shared-pool component comparisons and analyses of candidate-count gains and inference cost.
• Empirical evidence. An eight-model comparison of Direct and three adaptations (9,632 outcomes) quantifying the compile-execution gap, plus a five-model fixed-trace analysis showing how transient discrepancies and sampling phase hide behavioral failures.
2.1 Scan Semantics and PLC Verification
A cyclic PLC task invokes its program at a configured interval [11]. Each scan reads inputs, executes the control program, and updates outputs. ST statements follow the program's control flow, so assignment order can affect later statements in the same scan. ST organizes code into program organization units (POUs): functions, function blocks, and programs. Their interfaces declare inputs (VAR_INPUT), outputs (VAR_OUTPUT), and read/write arguments (VAR_IN_OUT, or inouts). Function-block instances retain internal state across calls [15, 39]; timer blocks also depend on elapsed time [5]. Thus, behavioral testing must fix the input sequence, initialization, time progression, and observed scans.
PLC verification provides several forms of evidence. STbmc performs bounded temporal-property checking [25]; SymPLC explores paths and task interleavings symbolically [14]; K-ST gives executable ST semantics and validates implementations differentially [39]; and PLC simulation can step through scan cycles [34]. These techniques analyze a given program against properties or formal semantics. Comparing generators also requires a shared task suite with expected behavior, which CycleBench provides.
2.2 LLM Generation, Testing, and Repair
General-purpose benchmarks evaluate function synthesis [7], library use [44], contest problems [16], and repository changes [18]. EvalPlus expands test coverage [27], and DPIaC-Eval tests infrastructure code for deployability [43]. Reference-based execution also appears in other code domains: VerilogEval compares simulated hardware outputs with golden designs [28], and SolBench uses differential fuzzing against original smart-contract functions [10]. CycleBench applies reference comparison to PLC scan execution under controlled initialization and logical time, and RQ4 isolates the effect of which scans are observed.
Execution feedback can also guide generation. CodeT selects among candidates using generated tests [6], Self-Debugging feeds execution results into repair [8], and MBR-EXEC and DOCE study execution-based selection and refinement [26, 35]. Generated expectations and self-repairs can themselves be wrong [9, 30]. This motivates measuring selection and repair separately from the reference-based final verdict.
2.3 LLM-Based PLC Methods
Early studies examine direct generation of PLC control logic [23, 37]. Later approaches add retrieval, specialized training, or structured control representations [13, 22, 24, 33]. PLC test generation and mutation datasets provide further ways to examine test quality [19, 21].
The closest workflows combine generation with feedback. LLM4PLC uses user-guided iteration with grammar, compiler, and SMV checks [12]. Agents4PLC integrates retrieval, planning, coding, debugging, and validation agents with formal specifications [29]. AutoPLC retrieves vendor-specific cases and APIs and uses vendor-toolchain diagnostics for repair [40]. SemaPLC combines project or interface context with specification, compilation, and runtime checks; its native verification gate controls delivery [38]. Its runtime strategy combines sampled traces with persistent assertions.
3 Benchmark: CycleBench
Under PLC scan semantics (Section 2.1), program outputs can depend on input history, retained state, and timing. Successful compilation or agreement at selected scans can therefore leave intermediate behavioral errors undetected. To assess generated ST programs under a common behavioral criterion, we construct CycleBench. Its core idea is to pair reviewed public specifications with reference programs and input scenarios, and compare candidate and reference outputs after every scan under aligned inputs, public initialization, and logical time. CycleBench contains 301 ST function blocks and programs, with references and evaluation scenarios hidden from generation. This protocol exposes output discrepancies within the supplied scenarios.
3.1 Benchmark Construction
CycleBench turns existing ST implementations into reference programs and adds a public specification and input scenarios to each. Fig. 2 shows the four construction stages: data collection, preprocessing, dataset construction, and review and selection.

Fig. 2. CycleBench construction: source collection, program preprocessing, task construction, and joint review by two PLC engineers with scenario validation and selection. Reference execution supplies the expected outputs for the evaluation scenarios; the final evaluation roster contains 301 tasks.
Data collection. We collect ST through six routes (Table 2(b)): two GitHub collections, AutoPLC's library, the Agents4PLC dataset, and Matiec and OpenPLC examples [29, 40]. Broad GitHub uses a wide search for ST code, whereas Curated GitHub uses a selected set of PLC-related repositories. We recursively inspect the repositories in both collections. The collected source files provide function blocks, programs, and dependencies for the preprocessing stage.
Preprocessing. We extract function blocks and programs with their input, output, and inout declarations, assemble dependencies, and check compilation with the Matiec IEC-to-C toolchain. Deduplication and program-family review reduce repeated implementations [1]. Execution screening checks whether references run under the benchmark harness, and interface checks require observable outputs. Of 591 candidate reference programs, 12 fail execution screening, leaving 579. Program-family deduplication and manual selection then exclude 274, retaining 305 reference programs with structured interfaces for dataset construction.
Dataset construction. For these 305 selected programs, we adapt existing task requirements or draft them from reference ST with LLM assistance. They describe state transitions, priorities, initialization, and timing; interfaces specify public signal names, directions, and IEC types. We use DeepSeek-V3.2 and Grok-4.6 to assist requirement drafting, and Grok-4.6 and Qwen3-Coder-Next to generate scenario inputs. Scenario authors receive requirements, interfaces, and reference ST, but supply no expected outputs: these come from reference execution. Scenarios specify input sequences, scan intervals, and resets, targeting relevant state changes, boundaries, edges, timing, and priority conflicts.
Review and selection. Two PLC engineers jointly review the behavioral requirements alongside the reference ST, checking clarity, agreement with reference behavior, interface completeness, and scenario suitability. Through discussion and consensus, they refine some task prompts and the corresponding reference code, supported by reference replay and automated checks. This review excludes four of the 305 constructed tasks because of reference-execution or public-interface contract issues. The resulting 301-task benchmark is used uniformly across all methods and models. Benchmark specification. Table 1 separates the public generation specification from the hidden evaluation suite. A method returns one complete ST function block or program that implements the requirement through the declared interface. The evaluator observes all declared outputs and inout members after each scan; private variables and internal representations may differ.
Table 1. Content specification for CycleBench.
| Category | Element | Purpose |
|---|---|---|
| Generation specification | Behavioral requirementPOU identityInput/output interfacePublic initial valuesFunctional parameters | Control logic, state transitions, priorities, and timing.Name and kind of the function block or program.Signal names, directions, and IEC data types.Starting values specified for public signals.Task-defined constants, such as thresholds or delays. |
| Evaluation suite | Reference programInput scenariosExecution settingsExpected output traces | Executable implementation supplying expected behavior.Ordered input values for successive scans.Scenario reset policy and scan interval.Reference outputs recorded after each scan. |
3.2 Benchmark Evaluation
Because ST behavior unfolds over scans (Section 2.1), CycleBench compares candidate and reference outputs after every scan, exposing early, late, or temporary discrepancies even when final outputs agree. Our runtime translates both from ST to C with a fixed Matiec build, then compiles and links the generated C with GCC. It drives both programs with identical inputs, initialization, scan intervals, and reset boundaries.
State and logical time. Each scenario starts the reference and candidate in separate fresh runtime sessions with the same public initial values; each initializes its own private state. At every scan, the harness writes the specified inputs, advances virtual time by one scan interval, invokes the target POU once, and records all declared outputs and inout values. State persists between scans; the next scenario starts afresh. Comparison includes the first scan and does not shift traces. Logical time follows this schedule rather than host elapsed time, so physical timing guarantees require separate measurements. Fig. 1 illustrates a transient disagreement.
Task-level decision. Formal task passes require preserving the public interface and POU identity, successful compilation and execution, and matching every observed reference value after every scan. Decoded types and values must match exactly; arrays are rebuilt at declared bounds and compared recursively. Surviving rounding differences fail without necessarily implying control-logic defects; RQ2 labels them separately. All tasks remain in the denominator. Missing candidates, interface violations, and compilation, deployment, or runtime failures fail and are classified by stage. Evaluation may stop at the first mismatch; passing requires complete traces for every scenario. Each task has nonempty scenarios and outputs. RQ3's unconstrained oracle counts behavioral matches; interface-invalid witnesses remain formal failures.
Isolation and validity. Generation, selection, and repair cannot access references, hidden inputs, or reference outputs. The candidate is frozen before hidden scoring. Passing establishes agreement on the supplied finite scenarios, subject to reference validity, rather than complete functional correctness, termination, or physical safety [4, 27].
3.3 Benchmark Characteristics
CycleBench contains 287 function blocks and 14 programs, with 684 scenarios and 61,424 scans (Table 2). The median task has two inputs, two outputs, 29 reference LOC, one scenario, and 15 scans. Repository origin is known for 259 tasks, and the three largest repositories contribute of tasks. Loops, timers, edge-trigger blocks, multiway selection, and arrays occur in 54, 32, 25, 31, and 24 tasks, respectively; these overlapping syntax features do not establish semantic coverage. Most tasks have short scenarios; six exceed 1,000 scans in total.
Table 2. Benchmark characteristics and collection routes for 301 evaluated tasks.
(a) Task and suite size
| Characteristic | Min. | Med. | Max. |
|---|---|---|---|
| Input size | 0 | 2 | 20 |
| Output size | 1 | 2 | 18 |
| Reference LOC | 2 | 29 | 170 |
| Scenarios/task | 1 | 1 | 5 |
| Scans/scenario | 1 | 15 | 10,000 |
| Scans/task | 4 | 15 | 17,606 |
| Total tasks | 301 | ||
| Total scenarios | 684 | ||
| Total scans | 61,424 |
(b) Source collection
| Group | Tasks | LOC (mean/med.) | Mean in/out |
|---|---|---|---|
| Broad GitHub | 118 | 35.46/26 | 2.78/2.15 |
| Curated GitHub | 53 | 47.28/38 | 3.81/3.45 |
| AutoPLC library | 33 | 24.52/22 | 4.58/2.97 |
| Agents4PLC | 90 | 39.83/34 | 2.87/2.96 |
| Matiec examples | 4 | 22.25/22.5 | 5.25/1.75 |
| OpenPLC examples | 3 | 30.67/25 | 3.33/1.00 |
LOC excludes blank and comment lines. Inout counts on both interface sides; an array counts as one variable. Scan totals may span resets. AutoPLC contributes 36 tasks across routes, including 33 in its library group.
3.4 Comparison with the Agents4PLC Benchmark
Agents4PLC's ST benchmark evaluates generated code against formal properties [29], rather than comparing all declared outputs after every scan. CycleBench includes 90 tasks derived from
Agents4PLC, alongside other sources, under one per-scan evaluator. SemaPLC combines sampled runtime traces and persistent assertions; Section 5 describes our interface-adapted comparison.
3.5 Formative Study
We first examine the quality of LLM-generated PLC Structured Text under scan-by-scan execution. Using the eight-model Direct results of RQ1 (settings in Section 5), Table 3 groups the 301 tasks by source collection and reference LOC. Pooled execution pass rate decreases from 87.17% in the shortest group to 48.61% in the longest, while the compile-execution gap grows from 3.67 to 24.07 points. All eight models perform worse in the longest group than in the shortest, although intermediate rates need not decrease monotonically. Every source group has a positive pooled gap, although the Matiec and OpenPLC groups contain only four and three tasks. Execution failures thus remain in every group, motivating CycleGen's use of behavioral evidence during candidate selection (Section 4).
Table 3. Direct characterization by source collection (a) and reference length (b). Bars show each model's execution pass rate; pooled rates appear below panel (a).
(a) Source collection
| Group | n | Comp. | Exec. | Gap |
|---|---|---|---|---|
| Broad GitHub | 118 | 87.39 | 79.77 | 7.63 |
| Curated GitHub | 53 | 74.76 | 63.21 | 11.56 |
| AutoPLC library | 33 | 94.32 | 90.53 | 3.79 |
| Agents4PLC | 90 | 84.58 | 71.11 | 13.47 |
| Matiec examples | 4 | 78.12 | 43.75 | 34.38 |
| OpenPLC examples | 3 | 83.33 | 45.83 | 37.50 |
Pooled rates by reference length
| LOC | 1–20 | 21–40 | 41–80 | >80 |
|---|---|---|---|---|
| Exec. | 87.17 | 80.43 | 54.63 | 48.61 |
| Comp. | 90.83 | 88.62 | 72.92 | 72.69 |
| Gap | 3.67 | 8.19 | 18.29 | 24.07 |
(b) Reference length

Comp. and Exec. are rates (%); Gap = Comp. – Exec. (pp), computed before rounding. n is the number of tasks. Each partition covers all 301 tasks; pooled rows contain eight model outcomes per task. Panel (b) uses the same four groups (75/145/54/27 tasks per model). LOC groups describe reference size, not model-derived difficulty.
4 Generation Framework: CycleGen
The formative study (Section 3.5) shows that compilable ST programs can still produce incorrect outputs. Runtime observations can provide additional evidence for candidate selection, but reference programs and evaluation scenarios must remain hidden during generation. The core idea of CycleGen is to supplement bounded compiler-guided repair with behavioral comparison of multiple candidates using one shared suite of model-generated scan-level tests [6, 8, 43]. The suite is fixed before code generation and provides a fallible selection signal; the selected program is frozen before hidden evaluation. Fig. 3 shows four modules implementing this design: Context & Generation, Compile-Fix, Self-Test, and Selection Gate.

Fig. 3. CycleGen's four modules use public specifications, compiler diagnostics, and model-generated tests to select one program. Selection ranks candidates without requiring all self-tests to pass. Reference-based scoring is separate from generation and selection.
4.1 Candidate and Test Generation
CycleGen receives the behavioral requirement, public interface, initial values, and ST dialect rules. The same model authors tests and code in separate contexts. Tests are fixed first and withheld from code generation; both stages precede candidate execution.
This ordering makes the suite candidate-blind: test authorship cannot respond to an observed implementation or its execution results. Withholding the suite also keeps candidate generation from directly targeting its assertions. However, both contexts use the same model and specification, so a shared misunderstanding can still appear in code and predicted outputs. Candidate-blind authorship therefore controls information flow, not semantic independence. Reusing one unchanged suite makes candidates comparable on the same input histories and assertions; it does not turn model predictions into a correctness oracle. RQ3 measures the consequences of this distinction through controlled selection contrasts and a separate self-test diagnostic.
Test generation. Each case specifies a reset, an input sequence, predicted scan outputs, and a requirement anchor: a model-authored quotation of, or reference to, the public requirement clause that the case is intended to test. For example, a retention test may cite a clause requiring an output to remain active after an input is withdrawn. Its scan sequence then activates and withdraws that input. This annotation describes the intended behavior; it is distinct from the input/output declarations. Every scored scan specifies all ordinary inputs and expected observable outputs, including inout members. An explicit inout write overwrites its current value; an omitted write leaves the current value unchanged. One suite serves the entire pool.
Before execution, validation checks the test format, declared input/output names and types, budgets, and consistent expectations for identical input histories. Well-formed cases with an anchor contribute assertions to the selection score; cases without one contribute only execution-completion evidence. The anchor check tests whether this textual link is present, not whether the cited clause justifies the predicted outputs. Interface validation is a separate structural check. Suites must satisfy the extent and variation rules in Section 5; at most one validation-guided revision is allowed before code generation.
Candidate generation. The model generates k = 5 complete ST programs using distinct seeds (Section 5). Empty responses and compilation failures consume their sampling attempt. Generation order supplies the final tie-breaker during selection.
4.2 Compiler-Guided Repair
Compile-Fix uses Matiec's iec2c front end to translate ST to C. Each nonempty candidate that fails this check receives at most one repair request containing the public specification, its code, and front-end diagnostics. A revised POU replaces the original only if it preserves the exact public interface and passes the same check; otherwise the original candidate and failure status are kept. A successful repair keeps its sampling slot. A candidate is eligible when it preserves the interface and passes ST-to-C translation. Interface preservation is checked separately from compilation and requires the specified POU name and public input/output declarations. This gate does not perform native GCC compilation or linking. All eligible candidates use the same fixed tests.
4.3 Runtime Self-Testing
Front-end acceptance does not establish executability or correct behavior. Self-Test attempts to build each eligible program with GCC and run the shared test inputs in the benchmark runtime (Section 3.2). Build failures yield incomplete self-test execution. Each case starts fresh, retaining state between scans; inputs precede each scan and logical time advances by its interval. Self-test uses Python value equality with boolean/numeric normalization; the final evaluator uses recursive type-and-value equality. A scored case passes only on complete matching execution. Runtime-valid means every scored and unscored case completes, not that predictions are correct. Only scored cases contribute pass and mismatched output-field counts; infrastructure faults and incomplete traces have separate statuses. Wrong predictions can penalize correct or favor incorrect code [9, 21]; RQ3 checks this signal against the hidden oracle.
4.4 Candidate Selection
Following execution-based selection [26, 35], CycleGen ranks eligible programs lexicographically: complete execution first, more passing scored cases next, then fewer mismatched output-field assertions. Exact ties are resolved by generation order. In the figure’s example, C3 wins its tie with C4 because it was generated earlier.
Fallback and termination. With no usable scored suite, selection returns the earliest eligible program. With no eligible program after repair, it returns the first original candidate and its observed status, including an empty response. If every eligible program has incomplete self-test execution, the remaining ranking criteria still select one while preserving that status.
Excluding transport retries, the budget is one test-authoring call, at most one suite revision, k code generations, and at most k compiler repairs.
5 Experimental Settings
To evaluate CycleBench and CycleGen, we study four research questions:
• RQ1: How Effective Is CycleGen at Generating Executable ST Programs?
• RQ2: Which Failures Occur During Compilation and Execution?
• RQ3: How Do CycleGen’s Modules Contribute to Execution Correctness?
• RQ4: How Much Does Observation Granularity Change Correctness Verdicts?
We evaluate the 301-task roster on eight model deployments accessed in September 2026: GPT-5.5, GPT-4o, Claude Sonnet 4, Claude Haiku 4.5, and GLM-5.2 through OpenRouter; Qwen3-Coder-Next and MiniMax-M2.5 through Bailian Beijing; and Qwen3.6-27B through a local compatible API [2, 3, 31, 32, 42]. Provider-routed aliases identify deployments rather than immutable checkpoints. Throughout the results, baseline names denote the adapted configurations in Table 4. Each returns one program per task/model; unsuccessful attempts remain in the denominator. CycleGen uses pretrained models at inference time without task-example retrieval or benchmark fine-tuning; the full roster serves as the evaluation set.
OpenRouter upstream providers were unpinned, with default reasoning mode; Coder-Next is non-thinking, MiniMax uses mandatory thinking, and local Qwen disables it. RQ1/RQ3 use all eight deployments; build failures and fixed-budget timeouts score zero.
All methods use the same 301 tasks and public interfaces, including inout members. Direct generation and CycleGen's self-tests support inout state updates; the three baseline adaptations receive the same declarations.
Direct uses the public requirement and interface. Table 4 specifies three configurations from pinned public material: Agents4PLC's paper/demo agent sequence [29], LLM4PLC's prompts and grammar checker [12], and AutoPLC's framework and AutoDebugger [40]. They retain compiler-feedback repair but omit formal-property checking: the inspected releases lack a validated, task-aligned property set, and LLM4PLC lacks end-to-end model-checker orchestration. AutoPLC's native service checks builds and deployment. Agents4PLC does not release its retrieval implementation and private vector store, so we reconstruct its retrieval workflow with TF-IDF over public material. Retrieval corpora are fixed, exclude reference-overlapping and aliasing documents before indexing, and are checked through recorded retrievals. AutoLearn is disabled. Results characterize these adaptations, not complete native reproductions.
SemaPLC reconstruction. We run SemaPLC's released agent core and native verifier through an interface adapter on all 301 tasks with GPT-4o [38]. We retain trajectory checkpoints allowing at most failure-driven repairs per native check. The common evaluator scores the stopped candidate regardless of native acceptance; RQ1 reports its single-model results. Each task is bounded by 12 provider calls, 180,000 tokens, US$2, and 1,200 seconds. Generation stops at native acceptance or the first applicable budget or repair limit; the resulting candidate is frozen before common-evaluator scoring.
Table 4. Baseline configurations from pinned public material. Listed methods use a 16,384-token output cap per request; budgets differ.
| Method | Retained structure and substitutions | Budget |
|---|---|---|
| Agents4PLC | Reconstructed retrieval, planning, coding, and compiler-feedback debugging; private vector store replaced by public TF-IDF; PLCverif/nuXmv not run. | At most one debug repair. |
| LLM4PLC | Official scan/FSM planning and code prompts with compiler-feedback repair; SMV/plant-model loop, LoRA adapters, and interactive engineer loop not reconstructed. | One plan, at most one clarification and three code attempts. |
| AutoPLC | Released framework with native AutoDebugger; CODESYS service redirected to Matiec; private online KB replaced by local BM25; AutoLearn disabled. | At most three compiler-check/debug iterations. |
Table 4 lists configured limits, not observed repair counts; LLM4PLC's attempt limit is our study setting.
Initial code generation uses temperature 0.7 for Direct, CycleGen, and the three adaptations; planning, test authoring, and repair use 0 except AutoPLC's code editor (0.7). The adaptations use top-p 1 and seed 42; five-candidate calls use seeds 42–46, provider-default top-p, and share candidate one with Direct. Candidates 6–8 use seeds 47–49, respectively, with temperature 0.7, top-p 1.0, and a 16,384-token output cap, while preserving each model's original deployment route. Ablations share initial candidates and candidate-blind tests; invalid suites invoke fallback (Section 4.4). These settings do not isolate temperature effects.
Model-generated self-test suites have at most six cases, ten scans per case, and forty scans total. Admission requires at least two scored cases, four scored scans, complete ordinary inputs and expected outputs/inouts, and two distinct written values per writable input; omitted inout writes retain state. These fixed filters bound cost and exclude degenerate suites.
Compilation rate (Comp.) is the fraction of task-model pairs whose returned program completes the common evaluator's ST-to-C translation and native GCC compilation and linking. It is distinct from CycleGen's front-end eligibility check. Execution pass rate is the fraction of tasks whose returned program preserves the public interface, compiles and completes all scenarios, and matches all declared outputs/inouts at every scan; the gap subtracts it from compilation rate. Post-compilation deployment and runtime failures remain distinct from behavioral mismatches. Each condition scores one returned program, unlike pass@k [7]; five candidate slots are not independent workflow runs, so this matrix cannot estimate reliability@k or seed variance [17].
RQ2 classifies the first compiler diagnostic per Direct compilation failure. One reviewer used prompts, reference/candidate code, and mismatch evidence to assign one primary category to each of 157 Direct behavioral failures (69 tasks, 156 distinct programs, with one program shared by two outcomes); numerical disagreements are separate. To assess labeling consistency, a second ST-experienced annotator, blinded to the original labels, independently classified one outcome from each of 40 randomly sampled failing tasks using the same codebook. RQ2 reports agreement and unweighted Cohen's .
RQ2 and RQ4 use GPT-5.5, GPT-4o, Claude Sonnet 4, Claude Haiku 4.5, and GLM-5.2, yielding 6,020 baseline outcomes and 1,505 Direct outcomes. RQ4 holds programs and traces fixed, comparing every scan against strides two, five, and ten (including scenario endpoints), and final-scan-only observation. All 157 failure traces have validated observations. Missed failures and apparent pass rates isolate observation granularity.
Beyond benchmark drafting, AI coding assistants supported script development, analysis, and manuscript editing. Task admission and RQ2 failure classification were performed by human reviewers.
Overall results weight models equally. Primary RQ1/RQ3 intervals use 20,000 paired task-cluster bootstrap samples, seed 20260911, retaining all eight model outcomes within each resampled task [20]; they are pointwise rather than multiplicity-adjusted simultaneous bounds. For seven CycleGen contrasts and the unrepaired-pool selector contrast, we sum paired pass differences across models within each task and compute two-sided exact sign-flip p-values over nonzero task sums, with Holm correction across eight tests. The 20,000 bootstrap draws estimate confidence intervals, not these p-values. The tests assume independent task clusters and sign exchangeability under the null; related tasks may violate independence. These analyses are exploratory estimates on the evaluated task set. For RQ4, we use 20,000 task-cluster resamples, seed 20260927, retaining the five-model diagnostic clusters.
We count the model calls and input-plus-output tokens used by Direct and CycleGen across all eight models, including test authoring and repairs. Shared generations are counted once. RQ3 reports mean calls and tokens per task–model pair; local compilation and execution are excluded.
Table 5. Compilation, execution pass rate, and their gap across eight models.
| Model | Direct | Agents4PLC [29] | LLM4PLC [12] | AutoPLC [40] | CycleGen (Ours) | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Comp. | Exec. | Gap | Comp. | Exec. | Gap | Comp. | Exec. | Gap | Comp. | Exec. | Gap | Comp. | Exec. | Gap | |
| GPT-5.5 | 96.68 | 84.39 | 12.29 | 97.67 | 85.05 | 12.62 | 99.34 | 84.05 | 15.28 | 97.34 | 83.72 | 13.62 | 99.00 | 86.71 | 12.29 |
| GPT-4o | 84.39 | 72.76 | 11.63 | 88.70 | 75.75 | 12.96 | 89.37 | 70.43 | 18.94 | 72.43 | 60.80 | 11.63 | 93.69 | 82.72 | 10.96 |
| Sonnet 4 | 90.70 | 82.72 | 7.97 | 93.69 | 82.06 | 11.63 | 95.02 | 77.74 | 17.28 | 76.74 | 66.11 | 10.63 | 96.01 | 86.38 | 9.63 |
| Haiku 4.5 | 89.04 | 78.07 | 10.96 | 87.38 | 76.08 | 11.30 | 87.04 | 71.10 | 15.95 | 91.69 | 79.73 | 11.96 | 94.68 | 83.06 | 11.63 |
| GLM-5.2 | 89.04 | 79.73 | 9.30 | 95.68 | 84.39 | 11.30 | 99.00 | 82.72 | 16.28 | 55.81 | 50.83 | 4.98 | 98.67 | 87.71 | 10.96 |
| Qwen3-Coder-Next | 69.10 | 58.47 | 10.63 | 77.08 | 63.79 | 13.29 | 76.41 | 62.46 | 13.95 | 70.43 | 62.46 | 7.97 | 86.05 | 73.75 | 12.29 |
| MiniMax-M2.5 | 80.40 | 71.10 | 9.30 | 82.06 | 71.10 | 10.96 | 86.05 | 71.10 | 14.95 | 52.16 | 44.85 | 7.31 | 96.35 | 83.39 | 12.96 |
| Qwen3.6-27B | 80.07 | 69.77 | 10.30 | 83.39 | 72.43 | 10.96 | 92.03 | 75.75 | 16.28 | 61.79 | 54.82 | 6.98 | 94.68 | 82.72 | 11.96 |
| All models | 84.93 | 74.63 | 10.30 | 88.21 | 76.33 | 11.88 | 90.53 | 74.42 | 16.11 | 72.30 | 62.92 | 9.39 | 94.89 | 83.31 | 11.59 |
Comp. and Exec. are compilation and execution pass rates (%); Gap = Comp. – Exec. (pp), computed before rounding. Each method uses 301 tasks per model (2,408 task-model pairs in the final row). Execution requires a complete scan-by-scan runtime match; all unsuccessful outcomes remain in the denominator. The gap includes every post-compilation failure stage as well as completed executions with behavioral failures. External-baseline names denote the public-material adaptations in Table 4.
6 Evaluation
We answer the four research questions on the 301-task roster using the common evaluator of Section 3.2; model scopes follow Section 5.
6.1 RQ1: How Effective Is CycleGen at Generating Executable ST Programs?
Table 5 reports compilation and execution pass rates for each model and method. Across 9,632 baseline outcomes, yield compilable programs and pass the complete execution criterion, a difference of 11.92 percentage points (95% task-cluster bootstrap interval [9.63, 14.43]). The gap appears in every model-method combination, including combinations with compilation rates above .
Baseline outcomes comprise 1,542 without a successful compilation result (including delivery, interface, translation, and native-build failures), 1,148 post-compilation execution failures, and 6,942 passes. The frozen binary results do not separate all post-compilation causes across eight models. Compilation can also change method rankings: LLM4PLC has the highest pooled baseline compilation rate (90.53%), but Agents4PLC has the highest execution pass rate (76.33%). Agents4PLC's paired gain over Direct is 1.70 points (95% task-cluster bootstrap CI [-0.33, 3.65]).
CycleGen uses the program returned by Direct as the first candidate in its pool. Its end-to-end comparisons include inference-budget differences; RQ3 controls the pools to examine component effects.
Comparison with baselines. Table 5 reports execution pass rate under the common final evaluator. CycleGen reaches , exceeding Direct by 8.68 points, adapted Agents4PLC by 6.98 points, adapted LLM4PLC by 8.89 points, and adapted AutoPLC by 20.39 points. The task-cluster bootstrap intervals are [7.23, 10.22] points against Direct and [5.02, 9.01] against Agents4PLC, the strongest pooled baseline. CycleGen exceeds the best baseline for each model by 1.66–12.29 points. Per-model differences are descriptive; budgets differ across methods and statistical inference is reported for pooled paired contrasts. CycleGen compiles in 2,285 of 2,408 outcomes (94.89%), leaving an 11.59-point compile-execution gap. Thus, higher execution pass rates do not eliminate the need for execution-based evaluation.
SemaPLC reconstruction and single-model scope. On the same 301 tasks with GPT-4o, our SemaPLC reconstruction reaches , , and execution pass rate at repairs per native check. At , it uses 38.07 million recorded tokens, 12.82 times CycleGen's 2.97 million on that model under their respective budgets. Native delivery accepts 75 targets; six fail the common evaluator. Of its 138 passes, 69 are native-accepted, 42 have same-hash native rejections, 14 are unchecked (no full native verification record), and 13 are stale (no fresh candidate/envelope verdict). The second repair adds tokens and rescues three outcomes while harming three. Scaling this reconstruction to all eight models would require a costly additional campaign, while the observed budget and delivery-gate differences would still prevent it from forming a directly comparable method condition. We therefore report the GPT-4o reconstruction as single-model process evidence, rather than as an eight-model baseline ranking or a complete reproduction claim.
Source and scenario-length sensitivity. Excluding all 126 tasks originating from Agents4PLC or AutoPLC leaves 175 tasks: the four-baseline compile-execution gap remains 11.04 points, and CycleGen improves on Direct by 8.86 points. Separately, excluding the six tasks with more than 1,000 scans leaves a gap of 11.33 points and a CycleGen gain of 8.56 points. Both findings therefore persist beyond these source groups and unusually long scenarios.
Answer to RQ1. Across four baselines and eight models, execution trails compilation by 11.92 points. CycleGen raises execution pass rate from to , but retains an 11.59-point gap: generation improvements do not replace execution-based evaluation.
6.2 RQ2: Which Failures Occur During Compilation and Execution?
For GPT-5.5, GPT-4o, Claude Sonnet 4, Claude Haiku 4.5, and GLM-5.2, the diagnostic subset comprises 6,020 baseline outcomes. Here, delivery failures account for , interface violations for , compilation and build failures for , deployment or runtime failures after compilation for , and completed executions with behavioral failures for . The remaining pass. For Direct, compilation failures and behavioral failures account for similar proportions of all 1,505 outcomes: and , respectively; delivery failures account for .
Table 6(a) groups all Direct compilation failures by their first diagnostic, avoiding repeated counts of cascading messages. These are reported symptoms, not definitive root causes [41].
Table 6. Direct failure categories among compiler errors (a, ) and completed executions with mismatched outputs (b, ).
(a) First compiler diagnostic
| Category | n (%) |
|---|---|
| Malformed statements | 41 (28.08) |
| Malformed declarations | 37 (25.34) |
| Type incompatibility | 21 (14.38) |
| Malformed expressions | 21 (14.38) |
| Invalid variable references | 21 (14.38) |
| Block-interface misuse | 4 (2.74) |
| Unresolved syntax diagnostic | 1 (0.68) |
(b) Reviewed behavior mismatch
| Category | n (%) |
|---|---|
| Public-output updates | 43 (27.4) |
| Arithmetic / boundary logic | 35 (22.3) |
| Timing / call order | 25 (15.9) |
| Reset / priority | 15 (9.6) |
| State retention / overwrite | 14 (8.9) |
| Edge detection | 13 (8.3) |
| Initialization | 9 (5.7) |
| Numerical precision / boundary | 3 (1.9) |
Panel (a) assigns the first compiler diagnostic to each of 146 failures; these are symptoms, not established root causes. Panel (b) gives one reviewer-assigned primary category to each of 157 behavioral failures. Its three numerical cases retain the mismatch verdict but are separate from the 154 implementation-error cases.
Malformed statements and declarations account for 53.42% of compiler failures; type incompatibility accounts for 14.38%. The remaining categories cover expressions, references, block interfaces, and one unresolved diagnostic. These symptoms alone cannot establish behavioral correctness.
Table 6(b) covers all 157 Direct behavioral failures: 154 reviewer-attributed implementation errors and three numerical cases. Public-output updates (43, 27.4%), arithmetic or boundary logic (35, 22.3%), and timing or call order (25, 15.9%) together account for 65.6%. Numerical cases retain their mismatch verdicts separately from implementation mechanisms. RQ4's Fig. 6 relates all categories to observation policies.
The independent annotation check agrees on 33 of 40 outcomes (82.5%), with unweighted Cohen's (95% bootstrap CI [0.61, 0.91]). Public-output updates are the largest category in both labelings. Six of the seven disagreements concern this broad category versus a more specific mechanism, illustrating the difficulty of assigning one primary label to programs that may contain several defects.
Timing/call-order failures include invoking a stateful block before its current-scan inputs are assigned, so it consumes previous input values. RQ4 presents a traced example (Fig. 5).
Answer to RQ2. Statements and declarations account for 53.42% of Direct compilation failures; output-update, arithmetic, and timing/call-order errors account for 65.6% of behavioral failures. Runtime checks reveal state and value errors that compiler feedback cannot establish.
6.3 RQ3: How Do CycleGen's Modules Contribute to Execution Correctness?
RQ1 measures overall effectiveness; here we examine which parts of CycleGen produce its gains and at what token cost. Table 7 ablates pool repair and self-test selection on the same five initial candidates. Removing Compile-Fix retains the shared suite and selector; removing self-test selection retains the repaired pool but returns the first eligible candidate. Self-Test and Selection Gate are evaluated jointly, since runtime observations guide the gate's ranking; their individual effects are not separately identified. We call these variants Self-test only and Repair only, respectively: “only” refers to the two optional components added to the multiple-candidate configuration, and Self-test only includes execution-based selection.
Table 7. CycleGen ablations on 2,408 task-model pairs.
| Configuration | k | Repair | Selection | Comp. | Exec. | Tokens |
|---|---|---|---|---|---|---|
| Direct | 1 | No | First | 84.93 | 74.63 | 1,929 |
| Multiple candidates | 5 | No | First | 92.23 | 79.94 | 9,740 |
| Self-test only | 5 | No | Self-test | 92.23 | 81.02 | 16,015 |
| Repair only | 5 | Yes | First | 94.85 | 81.69 | 11,922 |
| CycleGen | 5 | Yes | Self-test | 94.89 | 83.31 | 18,197 |
Comp. measures complete builds in the common evaluator; Exec. measures execution passes (%). Tokens is mean recorded input plus output tokens per task–model pair, rounded to integers. First selects the first candidate preserving the interface and passing ST-to-C translation; Direct returns the first generated candidate. All five-candidate configurations reuse the same initial samples, and self-test configurations reuse the same suite. Counts include unsuccessful outcomes.
Context & Generation: Supplying candidate alternatives. First-eligible selection from five unrepaired candidates reaches 79.94%, a 5.32-point gain over Direct, while mean tokens increase from 1,929 to 9,740. This contrast changes sampling budget, not context or prompt. The remaining modules rescue 95 outcomes and break 14, adding 3.36 points on these pools (95% task-cluster bootstrap CI [2.37, 4.40]).
Compile-Fix: Repairing front-end failures. Removing compiler-guided repair [41] while fixing the suite and selector lowers execution pass rate by 2.28 points (95% CI [1.45, 3.16]) and compilation from 94.89% to 92.23%. Repair admits rejected candidates to runtime testing without establishing correct behavior; its mean-token increment is 2,183.
Self-Test and Selection Gate: Selecting by execution feedback. Self-test selection [6, 26] rescues 49 outcomes and breaks ten versus first-eligible selection on repaired pools: a 1.62-point gain (95% CI [0.91, 2.37]; Holm-adjusted ), for mean tokens rising from 11,922 to 18,197. Its one-outcome compilation gain occurs when the first eligible candidate passes ST-to-C translation but fails native building; completed self-tests favor another candidate. The contrast therefore includes build validation as well as behavioral ranking. On unrepaired pools, selection adds 1.08 points ([0.50, 1.70]).
Candidate count and token trade-offs. Fig. 4 follows frozen generation-order prefixes and their token costs. Repaired already includes Compile-Fix and differs from Direct. CycleGen rises from 78.53% at to 83.31% at . From to 5, it gains 21 passes (0.87 points) for 35.6% more tokens (13,419.9 to 18,197.2). Extending to raises tokens to 25,256.6 (+38.8%) but loses four selected passes (0.17 points). Observed dominates its extensions; this does not establish a generally optimal or equal-resource budget.
At k = 5, CycleGen averages 7 model calls and 18,197 tokens per task-model pair; Direct averages 1 call and 1,929 tokens. CycleGen's 16,864 calls comprise 12,040 candidate generations, 3,124 test-authoring calls, and 1,700 repairs. Counts include shared Direct dependencies and each suite once per pool; local execution, dollar costs, and latency are outside this measure.
Multiple candidates Self-test only Repair only CycleGen
(a) Execution pass rate

(b) Token-accuracy trade-off

Fig. 4. Ordered-prefix component sensitivity (301 tasks × eight models). The left panel shows the four controlled configurations, Direct, and the unconstrained repaired-pool Oracle@k. Self-test only retains the shared suite and selector without pool repair; Repair only repairs the pool and selects its first eligible candidate. Both use multiple candidates. The right panel plots pass rate against mean input-plus-output tokens; point labels give k, and the dotted curve marks the observed Pareto frontier. For Oracle@k, percentages count hidden behavioral matches among frozen pool candidates without public-interface eligibility, not formal task passes; this unconstrained diagnostic is not a deployable selector.
Candidate availability and selection limits. Oracle@k retrospectively counts hidden behavioral matches without public-interface eligibility; these diagnostic labels neither guide selection nor denote formal task passes. The unconstrained repaired-pool oracle in Fig. 4(a) rises from 2,081/2,408
(86.42%) at k = 5 to 87.58% at k = 8, although CycleGen's selected rate does not improve. At k = 5, 75 pools contain unselected recorded behavioral matches, while 327 lack any documented match. Six unconstrained-oracle witnesses violated the public interface contract and were therefore ineligible for deployment; we retain them only to distinguish feasibility losses from selection-stage misses. The remaining 69 involve the selection stage: 15 score ties, 21 cases favoring a failing candidate with more passing self-test cases, seven favoring one with fewer output mismatches, 16 with invalid self-test execution, and ten without a scored suite. Thus, the oracle gap includes both interface-contract violations and limitations of self-test coverage, execution availability, and ranking. In 13 of 15 tied pools, the passing witness and selected failure have identical public binding observations; changing expected outputs alone cannot separate them. This motivates the following diagnostic of self-test agreement and discrimination, which is supporting process evidence rather than an additional module ablation.
Self-test agreement and discrimination. A separate 24-task pilot examines the quality of the self-test signal. Tasks were selected by source rotation and reference-length/static-feature strata, independently of candidate success and self-test outcomes. The pilot covers 192 task-model suite slots: 144 pass the suite-validity checks, 46 are invalid, and two are missing or unparseable. Of the 144 valid suites, 138 complete repeatable reference execution. The other six reach a specified nonterminating input on one task; that task's hidden evaluation scenario exercises only terminating inputs. Among the 138 repeatable suites, original assertions match 2,242/2,673 binding scans (83.88%) but accept all binding cases in only 75/138 suites (54.35%). We apply 50 single-site changes to comparison boundaries, equality, logical connectives, and Boolean literals across 18 tasks, with at most three mutants per task. A detection requires the same suite to accept the reference and reject the mutant after complete stable execution. Among 135 stable suite-mutant pairs whose reference is accepted, 99 reject the mutant (73.33%; 95% CI [51.04, 91.30]); only 43/192 original suite slots detect any mutant.
Scope of the ablations. These exploratory comparisons fix pools and stated controls, not total inference resources.
Answer to RQ3. Multiple candidates raise execution pass rate from 74.63% to 79.94% with front-end-based selection. On controlled pools, Compile-Fix adds 2.28 points with self-test selection fixed, while Self-Test and Selection Gate add 1.62 points with repair fixed. These conditional gains show the roles of candidate diversity, front-end repair, and execution-based selection. Increasing k from five to eight adds 38.8% tokens without improving selected pass rate, despite a higher unconstrained pool-oracle rate.
6.4 RQ4: How Much Does Observation Granularity Change Correctness Verdicts?
We subsample Direct traces with programs, inputs, output sets, and decoded type-and-value equality fixed. Unlike expanding test inputs [27], this asks when outputs must be observed within the same execution.
Validated replays cover all 157 Direct behavioral failures detected by per-scan comparison. Here, a missed failure means a disagreement detected by that criterion but not by the coarser policy. Exact passes also pass every subset of the same observations.
Checking every second, fifth, or tenth scan misses 11, 34, or 47 of 157 behavioral failures (7.01%, 21.66%, and 29.94%), respectively, even when each scenario's first and final scans are always checked. The apparent execution pass rate across 1,505 Direct outcomes rises from 79.53% with every-scan checking to 80.27%, 81.79%, and 82.66%. Final-scan-only observation misses 98 failures (62.42%; 95% task-cluster CI 50.00–74.14%) and raises the apparent pass rate to 86.05%. These comparisons use the same complete traces; only the observation positions change.
Transient disagreements hidden by later outputs. The shift register in Fig. 1 illustrates how reset conceals incorrect intermediate values. Fig. 5 shows the same observation problem for a timer: the candidate invokes the off-delay block before assigning its current sensor input. The light is wrong at scan 7 but matches again at scans 8–9. Observing only these later matching outputs misses the earlier disagreement; comparing each scan exposes the one-scan delay.
(* Candidate: uses previous input ) TOF0(IN := pir_active, PT := T#20s); ( ... manual-control updates ... *) pir_active := stairs_pir_sensor AND NOT lights_buttons_state; stairs_light := lights_buttons_state OR TOF0.Q;
| Scan | 6 | 7 | 8 | 9 |
|---|---|---|---|---|
| Motion input | 0 | 1 | 1 | 0 |
| Reference light | 0 | 1 | 1 | 1 |
| Candidate light | 0 | 0 | 1 | 1 |
| Output match | Yes | No | Yes | Yes |
Fig. 5. A transient timer disagreement missed by later observations. The candidate calls its off-delay timer before updating the current input. With manual mode off, the recorded Boolean trace (0/1) differs at scan 7 and agrees at scans 8–9. Code is excerpted; bold marks the disagreement.
Mechanisms and within-scenario re-agreement. Joining the 157 failures to audited labels by task, model, and candidate hash shows that final-scan-only checking misses 9/14 state-retention, 8/13 edge-detection, and 31/43 output-update failures (Fig. 6). Overall, 144/157 failures exhibit within-scenario output re-agreement (95% task-cluster interval: 85.31–96.84%), including all 98 final-scan misses; in 115/157 failures, no mismatch run exceeds five consecutive scans, though some final-scan misses have longer runs. Cross-scenario resets do not count as re-agreement; visible agreement does not establish internal-state equivalence.
Sensitivity to sampling phase. For each stride , we apply every possible phase uniformly across scenarios, retaining their endpoints. Phase zero yields 11, 34, and 47 missed failures; across phases, these counts range over 11–17, 19–44, and 25–56, respectively. Equally weighting the s phases gives mean missed counts of 14.0, 31.0, and 44.9 of the same 157 failures, respectively. Every fixed phase misses failures. Endpoint retention slightly changes observation
(a) Missed behavioral failures by category

(b) Phase sensitivity (endpoints retained)
Fig. 6. Observation-granularity mechanisms on 157 five-model Direct behavioral failures. Left: missed/total within each audited category; color denotes percentage. Right: all fixed sampling phases, retaining each scenario's endpoints. This post-hoc analysis keeps program traces fixed.
budgets. Full-trace dominance is structural; these results quantify its magnitude, mechanisms, and phase sensitivity on fixed traces.
Implications for execution-based evaluation. RQ4 changes observation positions, not programs or input histories. Higher apparent pass rates therefore reflect missed evidence rather than better code. Endpoint retention and phase changes leave failures undetected on these traces. Per-scan observation preserves exposed disagreements; broader input scenarios address a separate coverage question. Neither establishes correctness on executions that were not run.
Answer to RQ4. Every-second and every-fifth-scan checking miss 7.01% and 21.66% of behavioral failures. Transient discrepancies can disappear before an observation; sampling phase changes which failures are missed. Per-scan comparison detects them on the supplied executions.
7 Threats to Validity
Construct validity. Execution pass rate measures reference agreement on supplied scenarios, not full requirement coverage, unseen inputs, physical behavior, or termination. Exact equality may count numerical rounding differences as failures. Two PLC engineers checked requirements against sources, interfaces, and available reference behavior. RQ2 assigns one primary label to each behavioral failure; independent annotation assesses consistency, not unique root causes or sparse-category accuracy (Section 6.2).
Baseline fidelity. Agents4PLC and LLM4PLC retain compiler-feedback repair but omit described formal-verification loops; common scoring cannot restore generation-time verification. Results characterize these adaptations, not native systems. Sampling and inference budgets differ; shared pools narrow but do not remove this limitation.
Internal validity. Reference self-checks, fresh state, aligned logical time, hidden-data isolation, and versioned images constrain initialization, timing, and evaluator effects.
External validity. Eight deployments cover 301 tasks; taxonomy and observation analyses cover five models. Source concentration and limited scenarios constrain diversity and coverage [1] (Table 2). Baseline-derived tasks and Qwen3-Coder-Next's roles in scenario authoring and evaluation may affect results; training exposure remains unknown. Fixed budgets, one runtime, and provider-specific reasoning limit transfer to other dialects and physical controllers (Section 5). AutoPLC's lower compilation under our adapter cannot be attributed to individual components.
Conclusion validity. Task-level paired resampling preserves method–model correlation. The CycleGen configuration was developed using this benchmark. Independent tasks and repeated generations are needed to assess generalization and sampling stability. Ablations estimate conditional effects under the reported controls.
8 Conclusion
CycleBench evaluates LLM-generated ST through scan-by-scan execution on 301 PLC tasks. Across eight models and four baseline methods, execution trails compilation by 11.92 percentage points. Every-fifth-scan checking misses 21.66% of 157 behavioral failures in the five-model Direct analysis, even with scenario endpoints retained; transient discrepancies and sampling phase explain these misses. CycleGen combines multiple candidates, compiler-guided repair, and runtime self-tests, raising execution pass rate from 74.63% to 83.31%. Controlled-pool ablations support repair and self-test selection, while increasing the candidate count beyond five adds token cost without improving execution pass rate. These findings motivate scan-by-scan evaluation and behavioral feedback for generated PLC programs.
Data Availability
We plan to publicly release the code and data after the peer-review process is complete.
References
[1] Miltiadis Allamanis. 2019. The Adverse Effects of Code Duplication in Machine Learning Models of Code. In Proceedings of the 2019 ACM SIGPLAN International Symposium on New Ideas, New Paradigms, and Reflections on Programming and Software. Association for Computing Machinery, 143–153. doi:10.1145/3359591.3359735
[2] Anthropic. 2025. Introducing Claude 4. Retrieved October 1, 2026 from https://www.anthropic.com/news/claude-4
[3] Anthropic. 2025. Introducing Claude Haiku 4.5. Retrieved October 1, 2026 from https://www.anthropic.com/news/claude-haiku-4-5
[4] Earl T. Barr, Mark Harman, Phil McMinn, Muzammil Shahbaz, and Shin Yoo. 2015. The Oracle Problem in Software Testing: A Survey. IEEE Transactions on Software Engineering 41, 5 (2015), 507–525. doi:10.1109/TSE.2014.2372785
[5] Beckhoff Automation. [n. d.]. TOF. Retrieved September 19, 2026 from https://infosys.beckhoff.com/content/1033/tcpclib_tc2_standard/74405003.html TwinCAT Tc2_Standard library documentation.
[6] Bei Chen, Fengji Zhang, Anh Nguyen, Daoguang Zan, Zeqi Lin, Jian-Guang Lou, and Weizhu Chen. 2023. CodeT: Code Generation with Generated Tests. In The Eleventh International Conference on Learning Representations. https://openreview.net/forum?id=ktrw68Cmu9c
[7] Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde de Oliveira Pinto, Jared Kaplan, Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, Alex Ray, Raul Puri, Gretchen Krueger, Michael Petrov, Heidy Khlaaf, Girish Sastry, Pamela Mishkin, Brooke Chan, Scott Gray, Nick Ryder, Mikhail Pavlov, Alethea Power, Lukasz Kaiser, Mohammad Bavarian, Clemens Winter, Philippe Tillet, Felipe Petroski Such, Dave Cummings, Matthias Plappert, Fotios Chantzis, Elizabeth Barnes, Ariel Herbert-Voss, William Hebgen Guss, Alex Nichol, Alex Paino, Nikolas Tezak, Jie Tang, Igor Babuschkin, Suchir Balaji, Shantanu Jain, William Saunders, Christopher Hesse, Andrew N. Carr, Jan Leike, Josh Achiam, Vedant Misra, Evan Morikawa, Alec Radford, Matthew Knight, Miles Brundage, Mira Murati, Katie Mayer, Peter Welinder, Bob McGrew, Dario Amodei, Sam McCandlish, Ilya Sutskever, and Wojciech Zaremba. 2021. Evaluating Large Language Models Trained on Code. arXiv:2107.03374 doi:10.48550/arXiv.2107.03374
[8] Xinyun Chen, Maxwell Lin, Nathanael Schärli, and Denny Zhou. 2024. Teaching Large Language Models to Self-Debug. In The Twelfth International Conference on Learning Representations. https://proceedings.iclr.cc/paper_files/paper/2024/hash/2460396f2d0d421885997dd1612ac56b-Abstract-Conference.html
[9] Xiancai Chen, Zhengwei Tao, Kechi Zhang, Changzhi Zhou, Xinyu Zhang, Wanli Gu, Yuanpeng He, Mengdi Zhang, Xunliang Cai, Haiyan Zhao, and Zhi Jin. 2025. Revisit Self-Debugging with Self-Generated Tests for Code Generation. In Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). Association for Computational Linguistics, 18003–18023. doi:10.18653/v1/2025.acl-long.881
[10] Zaoyu Chen, Haoran Qin, Nuo Chen, Xiangyu Zhao, Lei Xue, Xiapu Luo, and Xiao-Ming Wu. 2026. Towards Automated Smart Contract Generation: Evaluation, Benchmarking, and Retrieval-Augmented Repair. Proceedings of the ACM on Software Engineering 3, FSE (2026), 116–137. doi:10.1145/3797068
[11] CODESYS Group. [n. d.]. Configuring a Task. Retrieved September 19, 2026 from https://content.helpme-codesys.com/en/CODESYS%20Development%20System/_cds Creating_task_configuration.html CODESYS Development System documentation.
[12] Mohamad Fakih, Rahul Dharmaji, Yasamin Moghaddas, Gustavo Quiros, Oluwatosin Ogundare, and Mohammad Abdullah Al Faruque. 2024. LLM4PLC: Harnessing Large Language Models for Verifiable Programming of PLCs in Industrial Control Systems. In Proceedings of the 46th International Conference on Software Engineering: Software Engineering in Practice. Association for Computing Machinery, 192–203. doi:10.1145/3639477.3639743
[13] Ofek Glick, Vladimir Tchuiev, Marah Ghoummaid, Michal Moshkovitz, and Dotan Di-Castro. 2025. LLM4SFC: Sequential Function Chart Generation via Large Language Models. arXiv:2512.06787 doi:10.48550/arXiv.2512.06787
[14] Shengjian Guo, Meng Wu, and Chao Wang. 2017. Symbolic Execution of Programmable Logic Controller Code. In Proceedings of the 2017 11th Joint Meeting on Foundations of Software Engineering. Association for Computing Machinery, 326–336. doi:10.1145/3106237.3106245
[15] International Electrotechnical Commission. 2025. IEC 61131-3:2025: Programmable Controllers—Part 3: Programming Languages (4 ed.). International Electrotechnical Commission. https://webstore.iec.ch/en/publication/68533
[16] Naman Jain, King Han, Alex Gu, Wen-Ding Li, Fanjia Yan, Tianjun Zhang, Sida I. Wang, Armando Solar-Lezama, Koushik Sen, and Ion Stoica. 2025. LiveCodeBench: Holistic and Contamination Free Evaluation of Large Language Models for Code. In The Thirteenth International Conference on Learning Representations. https://proceedings.iclr.cc/paper_files/paper/2025/hash/94074dd5a072d28ff75a76dabed43767-Abstract-Conference.html
[17] Jiajun Jiang, Sharon Zheng, Natan Vidra, and Spurthi Setty. 2026. Beyond Pass@k: Measuring Reliability and Security of Agentic Code Generation. arXiv:2608.14711 doi:10.48550/arXiv.2608.14711
[18] Carlos E. Jimenez, John Yang, Alexander Wettig, Shunyu Yao, Kexin Pei, Ofir Press, and Karthik Narasimhan. 2024. SWE-bench: Can Language Models Resolve Real-World GitHub Issues?. In The Twelfth International Conference on Learning Representations. https://proceedings.iclr.cc/paper_files/paper/2024/hash/edac78c3e300629acfe6cbe9ca88fb84-Abstract-Conference.html
[19] Md Humaun Kabir, Md Rakibul Islam, and Helen H. Lou. 2026. STMutants: A Mutation Testing Dataset for Structured Text Programs in Industrial Automation. arXiv:2606.05499 doi:10.48550/arXiv.2606.05499
[20] Philipp Koehn. 2004. Statistical Significance Tests for Machine Translation Evaluation. In Proceedings of the 2004 Conference on Empirical Methods in Natural Language Processing. Association for Computational Linguistics, 388–395. https://aclanthology.org/W04-3250/
[21] Heiko Koziolek, Virendra Ashiwal, Soumyadip Bandyopadhyay, and Chandrika K R. 2024. Automated Control Logic Test Case Generation using Large Language Models. In 2024 IEEE 29th International Conference on Emerging Technologies and Factory Automation (ETFA). IEEE, 1–8. doi:10.1109/ETFA61755.2024.10711016
[22] Heiko Koziolek, Thilo Braun, Virendra Ashiwal, Sofia Linsbauer, Marthe Ahlgreen Hansen, and Karoline Grotterud. 2026. Spec2Control: Automating PLC/DCS Control-Logic Engineering from Natural Language Requirements with LLMs—A Multi-Plant Evaluation. In Proceedings of the IEEE/ACM 48th International Conference on Software Engineering: Software Engineering in Practice. Association for Computing Machinery, 566–577. doi:10.1145/3786583.3786897
[23] Heiko Koziolek, Sten Gruener, and Virendra Ashiwal. 2023. ChatGPT for PLC/DCS Control Logic Generation. In 2023 IEEE 28th International Conference on Emerging Technologies and Factory Automation (ETFA). IEEE, 1–8. doi:10.1109/ETFA54631.2023.10275411
[24] Heiko Koziolek, Sten Grüner, Rhaban Hark, Virendra Ashiwal, Sofia Linsbauer, and Nafise Eskandani. 2024. LLM-based and Retrieval-Augmented Control Code Generation. In Proceedings of the 1st International Workshop on Large Language Models for Code. Association for Computing Machinery, 22–29. doi:10.1145/3643795.3648384
[25] Jaeseo Lee, Sangki Kim, and Kyungmin Bae. 2022. Bounded Model Checking of PLC ST Programs Using Rewriting Modulo SMT. In Proceedings of the 8th ACM SIGPLAN International Workshop on Formal Techniques for Safety-Critical Systems. Association for Computing Machinery, 56–67. doi:10.1145/3563822.3568016
[26] Haau-Sing Li, Patrick Fernandes, Iryna Gurevych, and André F. T. Martins. 2024. DOCE: Finding the Sweet Spot for Execution-Based Code Generation. arXiv:2408.13745 doi:10.48550/arXiv.2408.13745
[27] Jiawei Liu, Chunqiu Steven Xia, Yuyao Wang, and Lingming Zhang. 2023. Is Your Code Generated by ChatGPT Really Correct? Rigorous Evaluation of Large Language Models for Code Generation. In Advances in Neural Information Processing Systems, Vol. 36. 21558–21572. doi:10.52202/075280-0943
[28] Mingjie Liu, Nathaniel Pinckney, Brucek Khailany, and Haoxing Ren. 2023. Invited Paper: VerilogEval: Evaluating Large Language Models for Verilog Code Generation. In 2023 IEEE/ACM International Conference on Computer Aided Design (ICCAD). IEEE, 1–8. doi:10.1109/ICCAD57390.2023.10323812
[29] Zihan Liu, Ruinan Zeng, Dongxia Wang, Gengyun Peng, Xiaoxia Liu, Qiang Liu, Peiyu Liu, Wenhai Wang, and Jingyi Wang. 2026. Agents4PLC: Automating Closed-Loop PLC Code Generation and Verification in Industrial Control Systems Using LLM-Based Agents. IEEE Transactions on Software Engineering 52, 5 (2026), 1672–1687. doi:10.1109/TSE.2026.3667895
[30] Theo X. Olausson, Jeevana Priya Inala, Chenglong Wang, Jianfeng Gao, and Armando Solar-Lezama. 2024. Is Self-Repair a Silver Bullet for Code Generation?. In The Twelfth International Conference on Learning Representations. https://proceedings.iclr.cc/paper_files/paper/2024/hash/9ddc141bdbf9d1db510cefff56c586ad-Abstract-Conference.html
[31] OpenAI. 2024. GPT-4o System Card. Retrieved October 1, 2026 from https://openai.com/index/gpt-4o-system-card/
[32] OpenAI. 2026. GPT-5.5 System Card. Retrieved October 1, 2026 from https://openai.com/index/gpt-5-5-system-card/
[33] Lei Ren, Haotian Wang, Jiabao Dong, Haiteng Wang, Shuai Liu, Yuanjun Laili, and Lin Zhang. 2025. MetaIndex-PLC: A Control Logic-Guided LLM for PLC Code Generation in Industrial Control Systems. Applied Soft Computing 184 (2025), 113673. doi:10.1016/j.asoc.2025.113673
[34] Gyula Sallai, Dániel Darvas, and Enrique Blanco Viñuela. 2020. Testing Solutions for Siemens PLC Programs Based on PLCSIM Advanced. In Proceedings of the 17th International Conference on Accelerator and Large Experimental Physics Control Systems. JACoW Publishing, 1107–1110. doi:10.18429/JACoW-ICALEPCS2019-WEPHA018
[35] Freda Shi, Daniel Fried, Marjan Ghazvininejad, Luke Zettlemoyer, and Sida I. Wang. 2022. Natural Language to Code Translation with Execution. In Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing. Association for Computational Linguistics, 3533–3546. doi:10.18653/v1/2022.emnlp-main.231
[36] The MathWorks, Inc. [n. d.]. Simulink PLC Coder. Retrieved September 29, 2026 from https://www.mathworks.com/products/simulink-plc-coder.html Product documentation.
[37] Kilian Tran, Jingxi Zhang, Jérôme Pfeiffer, Andreas Wortmann, and Bianca Wiesmayr. 2024. Generating PLC Code with Universal Large Language Models. In 2024 IEEE 29th International Conference on Emerging Technologies and Factory Automation (ETFA). IEEE, 1–8. doi:10.1109/ETFA61755.2024.10711113
[38] Yanlun Tu, Huacan Wang, Ziyue Zhou, Jie Zhou, Ningyan Zhu, Ge Chen, Wangyi Chen, Tengfei Zhou, Yifan Zhou, Dasheng Yang, Xiaofeng Mou, Hui Zhang, and Yi Xu. 2026. SemaPLC: A Project-Grounded, Verification-Gated Agent Harness for PLC Code Generation. arXiv:2608.18565 doi:10.48550/arXiv.2608.18565
[39] Kun Wang, Jingyi Wang, Christopher M. Poskitt, Xiangxiang Chen, Jun Sun, and Peng Cheng. 2023. K-ST: A Formal Executable Semantics of the Structured Text Language for PLCs. IEEE Transactions on Software Engineering 49, 10 (2023), 4796–4813. doi:10.1109/TSE.2023.3315292
[40] Donghao Yang, Aolang Wu, Tianyi Zhang, Li Zhang, Xiaoli Lian, Fang Liu, Yuming Ren, Jiaji Tian, and Xiaoyin Che. 2025. AutoPLC: Generating Vendor-Aware Structured Text for Programmable Logic Controllers. In 2025 40th IEEE/ACM International Conference on Automated Software Engineering (ASE). IEEE, 3593–3604. doi:10.1109/ASE63991.2025.00297
[41] Michihiro Yasunaga and Percy Liang. 2020. Graph-based, Self-Supervised Program Repair from Diagnostic Feedback. In Proceedings of the 37th International Conference on Machine Learning (Proceedings of Machine Learning Research, Vol. 119). PMLR, 10799–10808. https://proceedings.mlr.press/v119/yasunaga20a.html
[42] Z.ai. 2026. GLM-5.2 Model Card. Retrieved October 1, 2026 from https://huggingface.co/zai-org/GLM-5.2
[43] Tianyi Zhang, Shidong Pan, Zejun Zhang, Zhenchang Xing, and Xiaoyu Sun. 2026. Deployability-Centric Infrastructure-as-Code Generation: Fail, Learn, Refine, and Succeed through LLM-Empowered DevOps Simulation. Proceedings of the ACM on Software Engineering 3, FSE (2026), 321–343. doi:10.1145/3797142
[44] Terry Yue Zhuo, Minh Chien Vu, Jenny Chim, Han Hu, Wenhao Yu, Ratnadira Widyasari, Imam Nur Bani Yusuf, Haolan Zhan, Junda He, Indraneil Paul, Simon Brunner, Chen Gong, Thong Hoang, Armel Zebaze, Xiaoheng Hong, Wen-Ding Li, Jean Kaddour, Ming Xu, Zhihan Zhang, Prateek Yadav, Naman Jain, Alex Gu, Zhoujun Cheng, Jiawei Liu, Qian Liu, Zijian Wang, Binyuan Hui, Niklas Muennighoff, David Lo, Daniel Fried, Xiaoning Du, Harm de Vries, and Leandro von Werra. 2025. BigCodeBench: Benchmarking Code Generation with Diverse Function Calls and Complex Instructions. In The Thirteenth International Conference on Learning Representations. https://proceedings.iclr.cc/paper_files/paper/2025/hash/a6a90bcc2aa470c3871b2d39a67d26e8-Abstract-Conference.html