A code generation method and system based on logical plan verification and trajectory alignment

CN122593772BActive Publication Date: 2026-09-25QILU UNIVERSITY OF TECHNOLOGY (SHANDONG ACADEMY OF SCIENCES)
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202611079666.X
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-07-21
Publication Date
2026-09-25
Estimated Expiration
2046-07-21

AI Technical Summary

Technical Problem

[0007]为克服上述现有技术的不足,本发明提供了一种基于逻辑计划验证与轨迹对齐的代码生成方法及系统,旨在解决现有代码生成技术中逻辑计划缺乏可靠验证、代码修复缺乏统一逻辑参考、错误定位粒度不足以及验证反馈利用不充分等问题

Benefits of technology

(1)本发明通过在代码生成前对结构化逻辑计划执行逐步推理模拟与自校正验证的双重验证机制,能够有效识别计划中隐含的算术计算错误、逻辑跳跃及状态传递缺陷,在计划层面即阻断错误向代码实现阶段传播的路径,显著降低因计划缺陷导致的代码语义错误风险,从源头保障生成代码的逻辑正确性。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122593772B_ABST
    Figure CN122593772B_ABST
Patent Text Reader

Abstract

The application provides a code generation method and system based on logical plan verification and trajectory alignment, and belongs to the field of artificial intelligence code generation. The method comprises the following steps: obtaining a code generation task and a corresponding test case; generating a structured logical plan according to the code generation task; performing step-by-step reasoning simulation on the structured logical plan by using the test case, generating a verification trajectory, and implementing self-correction verification on the verification trajectory; when the step-by-step reasoning simulation and the self-correction verification are both passed, constructing a logical reference standard based on the verification trajectory, and when any verification fails, reconstructing or locally correcting the structured logical plan and then verifying again; generating target code based on the structured logical plan and the logical reference standard that pass the verification, and implementing multi-granularity verification on the target code to obtain execution feedback corresponding to the verification result. The application can reduce the risk of plan errors propagating to code, and enhance the stability and reliability of code generation.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of artificial intelligence code generation technology, and in particular relates to a code generation method and system based on logical plan verification and trajectory alignment. Background Technology

[0002] The statements in this section are merely background information related to the present invention and do not necessarily constitute prior art.

[0003] Large language model-driven automatic code generation has become a core technology in intelligent software engineering. It can complete function writing, algorithm implementation, code completion, and program migration based on natural language requirements, significantly reducing the development threshold. Current mainstream solutions primarily generate code end-to-end in a single step. To improve reasoning capabilities for complex tasks, the industry has developed optimization techniques such as thought chains, planning before coding, and self-debugging iteration. The planning before coding strategy outputs the problem-solving logic steps first, and then generates code based on the plan; the self-debugging solution relies on feedback from compilation errors, runtime crashes, and mismatched test outputs to repeatedly correct the code.

[0004] Existing technologies suffer from three unavoidable shortcomings. First, the logical planning lacks a pre-verification mechanism, making it easy for errors to propagate to the code generation stage. Current solutions typically use the logic plan generated by the model directly as the basis for coding, without effectively verifying the reasoning process and intermediate states within the logic plan. If the logic plan contains calculation errors, missing steps, logical jumps, or state propagation breaks, these defects will further propagate to the code generation stage. Judging the effectiveness of the plan solely based on the final output result makes it difficult to identify inherent contradictions in the intermediate reasoning steps, easily leading to situations where the code syntax is valid but the business logic does not meet expectations.

[0005] Secondly, the granularity of code defect feedback is too coarse, and the automatic repair process is blind and inefficient. Existing repair methods mainly rely on shallow feedback information such as compilation exceptions, runtime errors, and final test results. This information usually only indicates that there is a defect in the code and is difficult to reflect the intermediate states of various variables, calculation nodes, and logical steps during program execution. When the code can execute normally but the output result is incorrect, the model has difficulty locating the first deviation in the logic and can only use global rewriting or multiple rounds of trial and error to repair it, resulting in a large number of repair iterations and poor stability.

[0006] Third, the lack of a unified logical mapping benchmark makes it difficult to achieve node-level defect localization and targeted repair. Existing solutions fail to effectively establish the correlation between logical plans, abstract syntax tree nodes, and intermediate program execution states, lacking a standardized logical reference system for comparing the actual program execution process. Therefore, when code verification fails, the system struggles to distinguish between execution-related feedback such as syntax errors, runtime exceptions, and timeouts, and logic-related feedback that is executable but outputs errors. It also struggles to further determine whether the output error is caused by numerical precision deviations or logical flow errors. The repair strategy is relatively simplistic, making it difficult to achieve node-level targeted repair based on deviation locations. Summary of the Invention

[0007] To overcome the shortcomings of the prior art, this invention provides a code generation method and system based on logical plan verification and trajectory alignment, aiming to solve the problems in existing code generation technologies such as the lack of reliable verification of logical plans, the lack of unified logical reference for code repair, insufficient granularity of error location, and insufficient utilization of verification feedback.

[0008] To achieve the above objectives, one or more embodiments of the present invention provide the following technical solutions: The first aspect of this invention provides a code generation method based on logical plan verification and trajectory alignment; A code generation method based on logical plan verification and trajectory alignment includes: Obtain code generation tasks and corresponding test cases; Generate a structured logical plan based on the code generation task; The test cases are used to perform stepwise reasoning simulation on the structured logic plan to generate a verification trajectory including the intermediate states corresponding to each logic step, and the verification trajectory is self-correcting verified. When both the stepwise reasoning simulation and the self-correcting verification pass, a logic reference standard is constructed based on the verification trajectory. When any verification fails, the structured logic plan is reconstructed or partially modified and then re-verified. Target code is generated based on the validated structured logic plan and logic reference standard, and multi-granularity validation is performed on the target code to obtain execution feedback corresponding to the validation results.

[0009] As a further technical solution, the structured logic plan is used to describe the problem-solving steps, variable or data state changes, key operations, and logical execution order corresponding to the code generation task; each logical step is associated with at least one or more of the following: step identifier, input state, processing operation, and output state.

[0010] As a further technical solution, the test cases are used to perform step-by-step reasoning simulation on the structured logic plan, generating a verification trajectory including intermediate states corresponding to each logic step, and performing self-correction verification on the verification trajectory, including: Obtain the input data of the current test case, and in accordance with the execution order of the structured logic plan, take the output state of the previous logic step as the input state of the next logic step, perform simulation calculations step by step, record the intermediate state after the execution of each logic step, and generate a verification trajectory. After the stepwise reasoning simulation is completed, the simulation result of the final step in the verification trajectory is compared with the expected output of the test case. If the two are inconsistent, the structured logic plan is determined to have failed the stepwise reasoning simulation. When the simulation results are consistent with the expected output, self-correction verification is performed on the verification trajectory. Following the same execution order as the stepwise inference simulation, forward independent recalculation or reverse stepwise verification is performed on the verification trajectory to check the calculation correctness of each intermediate state one by one; verify whether the input and output states between adjacent logic steps match, whether the state types are consistent, and whether the data transmission is complete. When the self-correction verification passes, the structured logic plan is deemed to have passed the double verification.

[0011] As a further technical solution, the logical reference standard includes test case identifiers, logical step identifiers, corresponding expected intermediate states, key decision paths, and expected output results; the logical reference standard is used to provide a unified basis for expected states in subsequent code generation, code verification, exception diagnosis, and code repair.

[0012] As a further technical solution, target code is generated based on the verified structured logic plan and logic reference standard, and multi-granularity verification is performed on the target code to obtain execution feedback corresponding to the verification results, including: The step identifiers, processing operation descriptions, and expected intermediate states corresponding to the logical reference standards of each logical step in the structured logic plan are used as prompt word constraint information and input into the code generation model to generate the initial target code. The initial target code is loaded in the isolated execution environment, and the input data of the test cases is used as the program input. Multi-granularity verification is executed in a preset order. The multi-granularity verification includes at least syntax verification, runtime verification, timeout verification and functional output verification. When a syntax error, runtime exception, or timeout occurs and a complete execution trace cannot be obtained, direct repair is performed based on the corresponding execution feedback; when the target code passes syntax verification, runtime verification, and timeout verification but fails functional output verification, node-level abstract syntax tree trace alignment analysis is performed.

[0013] As a further technical solution, when the target code passes syntax verification, runtime verification, and timeout verification but fails functional output verification, node-level abstract syntax tree trajectory alignment analysis is performed, including: The target code is parsed using an abstract syntax tree to identify key abstract syntax tree nodes. These nodes are then instrumented to collect one or more pieces of information, including node identifier, node type, code location, runtime variable values, intermediate calculation results, branch execution results, and execution order, thus forming the actual execution trajectory of the program. The abstract syntax tree nodes in the actual execution trajectory of the program are mapped to the corresponding logical steps of the structured logic plan, and the actual execution trajectory of the program is compared with the logical reference standard at the node level to locate the first deviation node and determine the exception type. A diagnostic report is generated based on the first deviation node and the anomaly type. The target code is then targeted for repair and iterative verification based on the diagnostic report until the target code that meets the preset correctness requirements is output, or the preset number of iterations is reached.

[0014] A second aspect of the present invention provides a code generation system based on logical plan verification and trajectory alignment.

[0015] A code generation system based on logical plan verification and trajectory alignment includes: The task acquisition module is configured to acquire code generation tasks and corresponding test cases; The plan generation module is configured to generate a structured logical plan based on the code generation task; The dual verification module is configured to: perform step-by-step reasoning simulation on the structured logic plan using the test cases, generate a verification trajectory including intermediate states corresponding to each logic step, and perform self-correction verification on the verification trajectory; when both the step-by-step reasoning simulation and the self-correction verification pass, construct a logical reference standard based on the verification trajectory; when any verification fails, reconstruct or partially modify the structured logic plan and then re-verify. The target code generation and verification repair module is configured to generate target code based on the verified structured logic plan and logic reference standard, perform multi-granularity verification on the target code, and obtain execution feedback corresponding to the verification results.

[0016] A third aspect of the present invention provides a computer-readable storage medium having a program stored thereon, which, when executed by a processor, implements the steps of a code generation method based on logical plan verification and trajectory alignment as described in the first aspect of the present invention.

[0017] A fourth aspect of the present invention provides an electronic device, including a memory, a processor, and a program stored in the memory and executable on the processor, wherein the processor executes the program to implement the steps of a code generation method based on logical plan verification and trajectory alignment as described in the first aspect of the present invention.

[0018] The fifth aspect of the present invention provides a computer program product, including a computer program / instruction that, when executed by a processor, implements the steps of the code generation method based on logical plan verification and trajectory alignment described in the first aspect of the present invention.

[0019] The above one or more technical solutions have the following beneficial effects: (1) This invention effectively identifies arithmetic calculation errors, logical jumps and state transmission defects hidden in the plan by performing a dual verification mechanism of step-by-step reasoning simulation and self-correction verification on the structured logic plan before code generation. It blocks the path of error propagation to the code implementation stage at the plan level, significantly reduces the risk of code semantic errors caused by plan defects, and ensures the logical correctness of the generated code from the source.

[0020] (2) This invention constructs a unified expected state basis for connecting the problem-solving logic and the program execution process by structuring the expected intermediate state, key decision path and expected output after double verification into a logical reference standard, providing precise constraints for code generation, providing a traceable reference benchmark for subsequent error diagnosis, and realizing the effective connection between the logical planning layer and the code execution layer.

[0021] (3) This invention obtains the actual execution trajectory of the program by parsing the abstract syntax tree and instrumenting key nodes in the target code, and compares the node-level states in conjunction with the logical reference standard. It can accurately locate the first abstract syntax tree node that deviates from the expected logic during the program operation, refine the error location granularity from the function level or statement level to the node level, and effectively reduce the blind global rewriting caused by the comparison of the final result.

[0022] (4) This invention distinguishes different verification feedbacks such as syntax errors, runtime anomalies, timeouts and functional output errors through multi-granularity verification. When the complete execution trajectory can be obtained and the functional output is inconsistent, it further distinguishes two types of node-level anomalies: numerical precision anomalies and logical anomalies. Combined with the structured diagnostic report of the first deviated node, targeted local repair is implemented, avoiding multiple rounds of indiscriminate trial and error, significantly improving the pertinence and success rate of automatic repair. At the same time, no additional training or fine-tuning of the basic large language model is required, which has good versatility and engineering deployment value.

[0023] Advantages of additional aspects of the invention will be set forth in part in the description which follows, and in part will be obvious from the description, or may be learned by practice of the invention. Attached Figure Description

[0024] The accompanying drawings, which form part of this invention, are used to provide a further understanding of the invention. The illustrative embodiments of the invention and their descriptions are used to explain the invention and do not constitute an improper limitation of the invention.

[0025] Figure 1 This is a flowchart of the method in the first embodiment.

[0026] Figure 2 This is a schematic diagram of node-level abstract syntax tree trajectory alignment and navigational repair in the first embodiment.

[0027] Figure 3 This is a system structure diagram of the second embodiment. Detailed Implementation

[0028] It should be noted that the following detailed descriptions are exemplary and intended to provide further illustration of the invention. Unless otherwise specified, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this invention pertains.

[0029] It should be noted that the terminology used herein is for the purpose of describing particular implementations only and is not intended to limit the exemplary implementations of the present invention.

[0030] Where there is no conflict, the embodiments and features in the embodiments of the present invention can be combined with each other.

[0031] Example 1 This embodiment discloses a code generation method based on logical plan verification and trajectory alignment. By performing dual verification on the plan and its reasoning trajectory before code generation, a logical reference standard including expected intermediate states is established. After code generation, the first deviation node is located through multi-granularity verification, abstract syntax tree instrumentation, and node-level trajectory alignment, thereby providing a structured diagnostic basis for targeted code repair.

[0032] like Figure 1 As shown, a code generation method based on logical plan verification and trajectory alignment can include a task planning phase and a code implementation phase. The task planning phase is used to convert natural language code requirements into a verified structured logical plan and a logical reference standard; the code implementation phase is used to generate target code based on the structured logical plan, and to implement navigational repair using a node-level abstract syntax tree trajectory alignment mechanism when verification fails.

[0033] The method provided by this invention will be described in detail below with reference to specific steps.

[0034] Step S1: Obtain the code generation task and corresponding test cases.

[0035] In this embodiment, the code generation task Q and its corresponding test case set T are first obtained. The code generation task Q can be a function generation task, algorithm implementation task, program completion task, code migration task, or other software development task, specifically manifested as a requirement text described in natural language, such as "Write a Python function to calculate the average of the absolute deviations of each element in the input list from the mean of the list".

[0036] The test case set T contains at least one test case, each represented as t=(x, y), where x represents the input data and y represents the corresponding expected output result. The test case set T can be represented as:

[0037] in, This represents the input data for the j-th test case. This represents the expected output result for the j-th test case, where m represents the number of test cases and is a positive integer. The input data x for the test cases can contain one or more parameters, and their data types include, but are not limited to, numeric, string, boolean, list, character, or custom object types; the expected output result y is the standard output that meets the task requirements given the input x.

[0038] Preferably, the test case set T is provided by the user along with the code generation task, or automatically generated based on the input and output format description of the code generation task. For automatic generation, multiple sets of test cases are generated by identifying data type constraints and value range constraints in the task description, using strategies such as boundary value coverage, equivalence class partitioning, or random sampling, to ensure that the test case set can fully cover normal scenarios, boundary scenarios, and abnormal scenarios. The number of test cases in the test case set T can be one or more, preferably three to ten, to balance verification sufficiency and computational efficiency.

[0039] Step S2: Generate a structured logical plan based on the code to generate the task.

[0040] In this embodiment, the basic large language model is invoked to decompose and plan the code generation task Q obtained in step S1, and output a structured logical plan. The structured logic plan This describes the problem-solving steps, variable or data state changes, key operations, and logical execution order corresponding to the code generation task. The structured logical plan... It can be represented as:

[0041] in, Let represent the i-th logical step, and n represent the number of logical steps, where n is a positive integer. Specifically, each logical step... It associates at least one or more of the following information: step identifier, input state, processing operation, and output state, and can be represented as:

[0042] in, Indicates step identifier, Indicates the input status. Indicates a processing operation. The output state is indicated by the step identifier, which uniquely distinguishes different logical steps; the input state describes the data or variable state required before executing the step; the processing operation describes the specific calculation or transformation action performed in the step; and the output state describes the data or variable state after the step is executed.

[0043] In a preferred implementation of this embodiment, a planning prompt strategy is used to guide the large language model in generating a structured logical plan. Specifically, prompt words containing task descriptions and planning instructions are constructed, whereby the planning instructions explicitly require the model to output the logical plan in the format of "step identifier: operation description (input → output)". For example, for the mean absolute deviation calculation task, the generated logical plan includes: : Calculate the mean of the input list (Input: original list X; Output: mean μ); : Calculate the absolute difference between each element and the mean (Input: original list X, mean μ; Output: list of absolute differences D); : Calculate the average of the absolute differences (Input: list of absolute differences D; Output: mean absolute deviation MAD); : Return result (Input: Mean Absolute Deviation (MAD); Output: Final result (Y)).

[0044] The generated structured logic plan is format-validated, checking that each logical step contains the necessary step identifiers, input states, processing operations, and output state information. If any information is missing or the format does not meet the requirements, a correction instruction is sent to the large language model to regenerate until the format requirements are met.

[0045] Step S3: Use the test cases to perform stepwise reasoning simulation on the structured logic plan, generate a verification trajectory including the intermediate states corresponding to each logic step, and perform self-correction verification on the verification trajectory; when both stepwise reasoning simulation and self-correction verification pass, construct a logic reference standard based on the verification trajectory; when any verification fails, reconstruct or partially modify the structured logic plan and re-verify.

[0046] In this embodiment, the structured logic plan generated in step S2 is tested using the test case set T. The dual verification process consists of two phases: stepwise inference simulation verification and self-calibration verification.

[0047] In this embodiment, the structured logic plan generated in step S2 is tested using the test case set T. The dual verification process consists of two phases: stepwise inference simulation verification and self-calibration verification.

[0048] Step S31, obtain the current test case. Input data Following the execution order of the structured logic plan π, starting from the first logical step... Initially, the output state of the previous logical step is used as the input state of the next logical step. Simulation calculations are performed step by step, and the intermediate states after each logical step are recorded to generate a verification trajectory. The verification trajectory It can be represented as:

[0049] in, This represents the intermediate state obtained after executing the i-th logical step in the j-th test case. For the first logical step... Its input state is the input data of the test case. After the step-by-step reasoning simulation is completed, the trajectory will be verified. Final logical steps Simulation results Expected output of the test cases The comparison is performed. The step-by-step reasoning simulation for this test case is considered passed if the difference between the two conditions is met:

[0050] in, This represents the difference measurement function. This indicates a preset tolerance threshold. If neither of these conditions is met, the structured logic plan is determined. Without step-by-step reasoning simulation, the reasons for failure were recorded and the process was transferred to the plan refactoring process. The structured logic plan was refactored or partially modified and then re-verified.

[0051] Step S32: When the simulation results match the expected output, verify the trajectory. Implement self-calibration verification to independently check the accuracy of the trajectory calculation, the consistency between adjacent logical steps, and the integrity of intermediate state transmission.

[0052] In a preferred implementation, the self-calibrating verification performs a forward independent recalculation of the verification trajectory according to the same execution order as the step-by-step inference simulation. Specifically, using a different computational path or a different computational precision than the step-by-step inference simulation, the intermediate states of each logical step are calculated independently, and the independent calculation results are compared with the corresponding recorded intermediate states in the verification trajectory. If the comparison results are consistent, the calculation of that step is confirmed to be correct; if the comparison results are different, it is further determined whether the difference is within the preset acceptable error range of numerical precision deviation; if it exceeds the acceptable error range, the logical step is determined to have a calculation error.

[0053] In another preferred implementation, self-calibrating verification employs a reverse, step-by-step verification method. Specifically, it starts from the final step of the verification trajectory. Initially, the output state of the (i-1)th logical step is derived by reverse deducing the input state and processing operation of the i-th logical step. The reverse deduction result is compared with the intermediate states recorded in the verification trajectory to verify the correctness of the intermediate states and the logical consistency between adjacent steps.

[0054] Regardless of whether forward independent recalculation or reverse step-by-step verification is used, adjacent step state transfer verification is performed on the verification trajectory. Specifically, for the output state of the i-th logical step and the input state of the (i+1)-th logical step in the verification trajectory, at least the following checks are performed: data type consistency check to verify whether the data type is consistent with the input data type declared by the (i+1)-th logical step; data structure integrity check to verify whether the data fields on which the input state of the (i+1)-th logical step depends are completely present in the intermediate state when the data type is list or character; and numerical range consistency check to verify whether the value in the input state of the (i+1)-th logical step is within the valid range of the corresponding value in the intermediate state.

[0055] If arithmetic errors, missing steps, discontinuous states, or logical contradictions are found during self-correction verification, the structured logic plan is determined to have failed self-correction verification. The reason for failure is recorded, and the process is redirected to the plan reconstruction process to reconstruct or partially correct the structured logic plan before re-executing the verification process of step S3.

[0056] Step S33: When both the stepwise reasoning simulation and self-correction verification pass, the structured logic plan is determined to have passed dual verification, and a logic reference standard R is constructed based on the verification trajectory. The logic reference standard R is structured expected state data saved for each test case, used to characterize the logical steps, expected intermediate states, key decision paths, and expected output results after passing dual verification. For each test case... The logical reference standard R includes at least the following fields: test case identifier, logical step identifier, corresponding expected intermediate state, key decision path, and expected output result, which are used to provide a unified basis for expected states in subsequent code generation, code verification, exception diagnosis, and code repair.

[0057] If any verification fails, the structured logic plan is restructured or partially modified, and the verification process of step S3 is re-executed until the double verification passes or the preset maximum number of verification attempts is reached. Restructuring methods include deleting redundant steps, adding missing steps, correcting arithmetic operation errors, or adjusting the execution order of steps; partial modification methods include correcting calculation logic errors in specific steps, correcting variable reference errors in state passing, or adjusting the judgment conditions of conditional branches.

[0058] Step S4: Generate target code based on the verified structured logic plan and logic reference standard, perform multi-granularity verification on the target code, and obtain execution feedback corresponding to the verification results.

[0059] Step S41: Input the step identifiers, processing operation descriptions, and expected intermediate states corresponding to each logical step in the structured logic plan π into the code generation model as prompt word constraint information to generate the initial target code C0.

[0060] Specifically, a structured prompt word is constructed containing the following information: a sequence of logical steps, a lookup table of expected intermediate states, target programming language and version information, function signature specifications, and code style constraints. The code generation model is preferably a large-scale language model, including but not limited to GPT series models, Claude series models, Codex series models, or large open-source code models.

[0061] Based on the above-mentioned prompt word constraint information, the code generation model generates target code C0 that conforms to the target language syntax and is consistent with the structured logic plan logic.

[0062] Step S42: Load the current target code Ck in the isolated execution environment, and use the input data x of each test case in the test case set T as the program input, and execute multi-granularity verification in a preset order; where k represents the current repair iteration round, and initially the current target code Ck is the initial target code C0.

[0063] For syntax validation, the target language's parser is invoked to parse the syntax tree of the current target code Ck. If parsing is successful, the syntax validation is deemed passed, and the process proceeds to the next validation level; if parsing fails, syntax error information and error location are captured, the first execution feedback is generated, and the direct repair process begins.

[0064] Once the syntax validation passes, the initial target code Ck is run in the isolated execution environment. If an exception is thrown during execution, the exception type, exception message, and exception stack information are captured, a second execution feedback is generated, and the process jumps to the direct repair flow. If no exception is thrown during execution, the execution validation is considered successful, and the process proceeds to the next validation level.

[0065] Once the execution verification passes, the time taken for the initial target code Ck to run from start to finish is recorded. If the time exceeds a preset time threshold (which can be dynamically adjusted according to task complexity), the program is forcibly terminated and a timeout indication is generated as the third execution feedback, and the process jumps to the direct repair process; if the time does not exceed the preset time threshold, the timeout verification is considered successful, and the process proceeds to the next verification level.

[0066] Once the timeout verification passes, the execution output of the initial target code Ck is obtained and compared with the expected output of the test case. If they match, the functional output verification is deemed successful, the target code Ck meets the preset correctness requirements, the target code is output, and the process ends; if they do not match, the functional output verification is deemed unsuccessful, and the difference between the actual output and the expected output is recorded as the fourth execution feedback.

[0067] Step S43: Based on the execution feedback of the above multi-granularity verification, perform differentiated traffic splitting.

[0068] Specifically, when syntax errors, runtime exceptions, or timeouts occur—that is, syntax validation fails, runtime validation fails, or timeout validation fails—the system cannot obtain a complete execution trajectory covering key nodes. In this case, the error message, exception stack, input information, and available local context are compiled into direct execution feedback, and based on this, a direct repair process is initiated. The code generation model performs repairs on the specific error type, generating the repaired target code Ck+1, and then returns to step S42 to re-execute multi-granularity validation.

[0069] If the current target code Ck passes syntax verification, runtime verification, and timeout verification, but fails functional output verification, it indicates that the program can execute completely and obtain runtime output, but the output result is inconsistent with expectations. At this time, node-level abstract syntax tree trajectory alignment analysis is performed. Through abstract syntax tree parsing, key node instrumentation, actual program execution trajectory acquisition, node-logic step mapping, and node-level state comparison, the first deviation node is located and the exception type is determined. A diagnostic report is generated based on the first deviation node and the exception type. Based on the diagnostic report, navigation-style targeted repair is performed on the current target code Ck. After generating the repaired target code Ck+1, the process returns to step S42 to re-execute multi-granularity verification until the target code meets the preset correctness requirements or reaches the preset maximum number of repair iterations.

[0070] like Figure 2As shown, when the target code Ck passes syntax verification, runtime verification, and timeout verification, but fails the function output verification, the current target code Ck that failed the function output verification is parsed into an abstract syntax tree. The abstract syntax tree is used to represent the syntax structure and computational structure of the target code, and its nodes can include variable assignment nodes, arithmetic operation nodes, function call nodes, condition judgment nodes, loop control nodes, set construction nodes, and return nodes.

[0071] Based on the node type, the code location of the node, the variable names involved in the node, the operator corresponding to the node, and whether the node affects the final output result, the key abstract syntax tree nodes that need to be state-captured are determined. For the key abstract syntax tree nodes, a tracking probe is injected so that the current target code Ck can record one or more of the following information during execution: node identifier, node type, code location, runtime variable values, intermediate calculation results, branch execution results, and execution order, thereby forming the actual execution trajectory of the program. The actual execution trajectory of the program. It can be represented as:

[0072] in, This represents the j-th test case. This represents the l-th abstract syntax tree node collected according to the program execution order. Represents a node The actual intermediate state or actual output value generated during runtime, where p represents the number of nodes collected, and p is a positive integer.

[0073] Further analyze the actual execution trajectory of the program Abstract syntax tree nodes and structured logic plans in The logical steps in the code establish a mapping relationship. Specifically, this relates to the actual execution trajectory of the program. Nodes in Based on one or more of the following information: node operation type, variable source and destination, input-output state correspondence, data flow context, control flow location, and semantic similarity, the node is mapped to a structured logical plan. The corresponding logical steps in the process. The mapping relationship can be expressed as:

[0074] Where Map represents the node mapping function. This represents the abstract syntax tree node to be mapped. Representing a structured logic plan The i-th logical step in.

[0075] The purpose of establishing the mapping relationship between abstract syntax tree nodes and logical steps is to correspond the actual node-level state generated during the actual execution of the program with the expected state stored in the logical reference standard R. This enables the system to determine from which abstract syntax tree node the execution process of the current target code Ck deviates from the double-verified structured logical plan, thereby providing a basis for subsequent location of the first deviation node, exception type determination, and targeted repair.

[0076] For the actual execution trajectory of the program Each node in Obtain the corresponding logical steps based on the mapping function Map. And read the logical steps from the logic reference standard R in the test case. The corresponding expected state The actual states are compared sequentially according to the program execution order. Compared with the expected state If the two nodes match, the comparison continues to the next node; if they do not match, the first node in the abstract syntax tree where the inconsistency occurs is identified as the first deviation node. The first deviation node can be represented as:

[0077] in, Indicates the first off-node. This represents the actual state corresponding to the first deviation node. This indicates the logical step to which the node is mapped. This represents the expected state in the logical reference standard R corresponding to this logical step.

[0078] After determining the first deviation node, based on the actual state of the first deviation node... Compared with the expected state Determine the exception type. When and Both are numerical data, and the absolute value of the difference between them is less than the preset tolerance. When this occurs, the anomaly type is determined to be a numerical precision anomaly. The criteria for determining the numerical precision anomaly can be expressed as follows:

[0079] in, This represents a function for determining the numeric type. This indicates a logical AND, which can also be understood as "and"; This indicates a preset tolerance threshold. When the difference between the two is greater than or equal to the preset tolerance... In cases where there are data type mismatches, inconsistent Boolean judgment results, missing paths, missing critical operations, or differences in control logic, the exception type will be determined as a logical exception.

[0080] Finally, after obtaining the first deviation node and the exception type, a structured diagnostic report is generated. This report may include the test case identifier, the code location of the first deviation node, the node type, the mapped logical step, the actual state, the expected state, the state deviation, the exception type, the relevant abstract syntax tree context, possible causes, and remediation suggestions. The structured diagnostic report, along with the current target code Ck, the structured logic plan π, and the logic reference standard R, is input into the repair module. This allows the repair module to prioritize local modifications to the first deviation node and its associated context, rather than indiscriminately regenerating all code, thus generating the repaired target code Ck+1.

[0081] The repaired target code Ck+1 re-enters the multi-granularity verification process in step S42. If the repaired target code passes all verifications, the final target code is output; if it still fails and the preset maximum number of repair iterations has not been exceeded, it re-enters the direct repair process or the node-level abstract syntax tree trajectory alignment process based on the new verification results. By setting the maximum number of repair iterations, infinite loops and overcomputation caused by repeated repairs can be avoided.

[0082] Example 2 This embodiment discloses a code generation system based on logical plan verification and trajectory alignment.

[0083] like Figure 3 As shown, a code generation system based on logical plan verification and trajectory alignment includes: The task acquisition module is configured to acquire code generation tasks and corresponding test cases. The plan generation module is configured to generate a structured logical plan based on the code generation task; The dual verification module is configured to: perform step-by-step reasoning simulation on the structured logic plan using the test cases, generate a verification trajectory including intermediate states corresponding to each logic step, and perform self-correction verification on the verification trajectory; when both the step-by-step reasoning simulation and the self-correction verification pass, construct a logical reference standard based on the verification trajectory; when any verification fails, reconstruct or partially modify the structured logic plan and then re-verify. The target code generation and verification repair module is configured to generate target code based on the verified structured logic plan and logic reference standard, perform multi-granularity verification on the target code, and obtain execution feedback corresponding to the verification results.

[0084] Example 3 The purpose of this embodiment is to provide a computer-readable storage medium.

[0085] A computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the steps of a code generation method based on logical plan verification and trajectory alignment as described in Embodiment 1.

[0086] Example 4 The purpose of this embodiment is to provide an electronic device.

[0087] An electronic device includes a memory, a processor, and a program stored in the memory and executable on the processor. When the processor executes the program, it implements the steps in a code generation method based on logical plan verification and trajectory alignment as described in Embodiment 1.

[0088] Example 5 Embodiment 5 of the present invention provides a computer program product, including a computer program / instruction, which, when executed by a processor, implements the steps in the code generation method based on logical plan verification and trajectory alignment as described in Embodiment 1.

[0089] The steps and methods involved in the apparatuses of Embodiments 2, 3, 4, and 5 above correspond to those in Embodiment 1. For specific implementation details, please refer to the relevant description section of Embodiment 1. The term "computer-readable storage medium" should be understood as a single medium or multiple media including one or more instruction sets; it should also be understood as including any medium capable of storing, encoding, or carrying an instruction set for execution by a processor and enabling the processor to perform any of the methods in this invention.

[0090] Those skilled in the art will understand that the modules or steps of the present invention described above can be implemented using general-purpose computer devices. Optionally, they can be implemented using computer-executable program code, thereby allowing them to be stored in a storage device for execution by a computer device, or they can be fabricated as separate integrated circuit modules, or multiple modules or steps can be fabricated as a single integrated circuit module. The present invention is not limited to any particular combination of hardware and software.

[0091] While the specific embodiments of the present invention have been described above in conjunction with the accompanying drawings, this is not intended to limit the scope of protection of the present invention. Those skilled in the art should understand that various modifications or variations that can be made by those skilled in the art without creative effort based on the technical solutions of the present invention are still within the scope of protection of the present invention.

Claims

1. A code generation method based on logical plan verification and trajectory alignment, characterized in that, include: Obtain code generation tasks and corresponding test cases; Generate a structured logical plan based on the code generation task; The test cases are used to perform step-by-step reasoning simulation on the structured logic plan to generate a verification trajectory including the intermediate states corresponding to each logic step, and the verification trajectory is self-corrected and verified. Specifically, the process includes: obtaining the input data of the current test case, taking the output state of the previous logic step as the input state of the next logic step according to the execution order of the structured logic plan, performing simulation calculation step by step, recording the intermediate state after the execution of each logic step, and generating a verification trajectory. After the stepwise reasoning simulation is completed, the simulation result of the final step in the verification trajectory is compared with the expected output of the test case. If the two are inconsistent, the structured logic plan is determined to have failed the stepwise reasoning simulation. When the simulation results are consistent with the expected output, self-correction verification is performed on the verification trajectory. Following the same execution order as the stepwise inference simulation, forward independent recalculation or reverse stepwise verification is performed on the verification trajectory to check the calculation correctness of each intermediate state one by one; verify whether the input and output states between adjacent logic steps match, whether the state types are consistent, and whether the data transmission is complete. When the self-correction verification passes, the structured logic plan is deemed to have passed the dual verification. When both stepwise inference simulation and self-calibration verification pass, a logical reference standard is constructed based on the verification trajectory. When any verification fails, the structured logic plan is reconstructed or partially modified and then re-verified. Target code is generated based on the validated structured logic plan and logic reference standard. Multi-granularity validation is then performed on the target code, and execution feedback corresponding to the validation results is obtained, including: The step identifiers, processing operation descriptions, and expected intermediate states corresponding to the logical reference standards of each logical step in the structured logic plan are used as prompt word constraint information and input into the code generation model to generate the initial target code. The initial target code is loaded in the isolated execution environment, and the input data of the test cases is used as the program input. Multi-granularity verification is executed in a preset order. The multi-granularity verification includes at least syntax verification, runtime verification, timeout verification and functional output verification. When a syntax error, runtime exception, or timeout occurs and a complete execution trace cannot be obtained, direct repair is performed based on the corresponding execution feedback; when the target code passes syntax verification, runtime verification, and timeout verification but fails functional output verification, node-level abstract syntax tree trace alignment analysis is performed.

2. The code generation method based on logical plan verification and trajectory alignment as described in claim 1, characterized in that, The structured logic plan is used to describe the problem-solving steps, variable or data state changes, key operations, and logical execution order corresponding to the code generation task; each logical step is associated with at least one or more of the following: step identifier, input state, processing operation, and output state.

3. The code generation method based on logical plan verification and trajectory alignment as described in claim 1, characterized in that, The logical reference standard includes test case identifiers, logical step identifiers, corresponding expected intermediate states, key decision paths, and expected output results; the logical reference standard is used to provide a unified basis for expected states in subsequent code generation, code verification, exception diagnosis, and code repair.

4. The code generation method based on logical plan verification and trajectory alignment as described in claim 1, characterized in that, When the target code passes syntax validation, runtime validation, and timeout validation but fails functional output validation, a node-level abstract syntax tree trajectory alignment analysis is performed, including: The target code is parsed using an abstract syntax tree to identify key abstract syntax tree nodes. These nodes are then instrumented to collect one or more pieces of information, including node identifier, node type, code location, runtime variable values, intermediate calculation results, branch execution results, and execution order, thus forming the actual execution trajectory of the program. The abstract syntax tree nodes in the actual execution trajectory of the program are mapped to the corresponding logical steps of the structured logic plan, and the actual execution trajectory of the program is compared with the logical reference standard at the node level to locate the first deviation node and determine the exception type. A diagnostic report is generated based on the first deviation node and the anomaly type. The target code is then targeted for repair and iterative verification based on the diagnostic report until the target code that meets the preset correctness requirements is output, or the preset number of iterations is reached.

5. A code generation system based on logical plan verification and trajectory alignment, characterized in that, include: The task acquisition module is configured to acquire code generation tasks and corresponding test cases; The plan generation module is configured to generate a structured logical plan based on the code generation task; The dual verification module is configured to: use the test cases to perform step-by-step reasoning simulation on the structured logic plan, generate a verification trajectory including the intermediate states corresponding to each logic step, and perform self-correction verification on the verification trajectory. Specifically, it includes: obtaining the input data of the current test case, taking the output state of the previous logic step as the input state of the next logic step according to the execution order of the structured logic plan, performing simulation calculation step by step, recording the intermediate state after the execution of each logic step, and generating a verification trajectory. After the stepwise reasoning simulation is completed, the simulation result of the final step in the verification trajectory is compared with the expected output of the test case. If the two are inconsistent, the structured logic plan is determined to have failed the stepwise reasoning simulation. When the simulation results are consistent with the expected output, self-correction verification is performed on the verification trajectory. Following the same execution order as the stepwise inference simulation, forward independent recalculation or reverse stepwise verification is performed on the verification trajectory to check the calculation correctness of each intermediate state one by one; verify whether the input and output states between adjacent logic steps match, whether the state types are consistent, and whether the data transmission is complete. When the self-correction verification passes, the structured logic plan is deemed to have passed the dual verification. When both stepwise inference simulation and self-calibration verification pass, a logical reference standard is constructed based on the verification trajectory. When any verification fails, the structured logic plan is reconstructed or partially modified and then re-verified. The target code generation, verification, and repair module is configured to: generate target code based on the verified structured logic plan and logic reference standard; perform multi-granularity verification on the target code; and obtain execution feedback corresponding to the verification results, including: The step identifiers, processing operation descriptions, and expected intermediate states corresponding to the logical reference standards of each logical step in the structured logic plan are used as prompt word constraint information and input into the code generation model to generate the initial target code. The initial target code is loaded in the isolated execution environment, and the input data of the test cases is used as the program input. Multi-granularity verification is executed in a preset order. The multi-granularity verification includes at least syntax verification, runtime verification, timeout verification and functional output verification. When a syntax error, runtime exception, or timeout occurs and a complete execution trace cannot be obtained, direct repair is performed based on the corresponding execution feedback; when the target code passes syntax verification, runtime verification, and timeout verification but fails functional output verification, node-level abstract syntax tree trace alignment analysis is performed.

6. A computer-readable storage medium having a program stored thereon, characterized in that, When the program is executed by the processor, it implements the steps in the code generation method based on logical plan verification and trajectory alignment as described in any one of claims 1-4.

7. An electronic device comprising a memory, a processor, and a program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the steps in the code generation method based on logical plan verification and trajectory alignment as described in any one of claims 1-4.

8. A computer program product comprising a computer program / instructions, characterized in that, When the computer program / instruction is executed by the processor, it implements the steps in the code generation method based on logical plan verification and trajectory alignment as described in any one of claims 1-4.

Citation Information

Patent Citations

  • Embedded program integrity multi-granularity verification system and method based on hardware on chip

    CN120180511A

  • Automatic process control program generation method based on multi-agent cooperation and closed-loop feedback

    CN121008526A