Manuscript Offprint

arXiv:2610.25616

Better Specifications, Better Code: Fine-Tuning LLMs for Behavioral Contract Generation

Brhane Team, Tiantian Yang, Nikta Akbarpour, Simone Bartucci, Francesco Calimeri, Song Wang

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

BRHANE TEAMRAT GIDEY, York University, Canada

TIANTIAN YANG, York University, Canada

NIKTA AKBARPOUR, York University, Canada

SIMONE BARTUCCI, University of Calabria, Italy

FRANCESCO CALIMERI, University of Calabria, Italy

SONG WANG, York University, Canada

Large language models (LLMs) show strong code-generation capabilities but still struggle with functional correctness. Natural-language tasks often leave behavioral requirements, constraints, and corner cases implicit, forcing LLMs to infer both what the program should do and how to implement it simultaneously. Misinterpreting these implicit requirements can therefore propagate directly into functional errors. This motivates separating behavioral specification from implementation by first making the intended behavior explicit before generating code.

We present CG2CG^{2}, a contract-guided code generation framework that uses behavioral contracts to bridge natural-language descriptions and code. CG2CG^{2} fine-tunes an LLM on pairs of task descriptions and contracts to generate structured behavioral specifications that explicitly capture program interfaces, preconditions, postconditions, and invariants, which then guide an unchanged downstream code-generation model. To mitigate errors in generated contracts, CG2CG^{2} further introduces an iterative semantic validation and repair process. Using the original task description as the semantic reference, CG2CG^{2} validates generated contracts to identify incorrect, vague, or missing clauses, as well as inconsistencies between machine-readable expressions and their natural-language descriptions. Identified defects are used as feedback to repair the contract, and repaired contracts are revalidated before being used for downstream code generation.

We evaluate CG2CG^{2} on 1,007 held-out algorithmic code-generation tasks using five code LLMs: DeepSeek-Coder-V2-Lite-Instruct, Ministral-3-14B-Instruct-2512, Qwen2.5-Coder-14B-Instruct, Qwen2.5-Coder-32B-Instruct, and Qwen3.5-27B. Across all models, contract guidance consistently improves pass@1 over direct code generation, contract-specific fine-tuning provides further gains, and semantic validation and repair yield additional aggregate improvements. Overall, CG2CG^{2} improves pass@1 over direct generation by 1.49–3.27 percentage points, corresponding to relative improvements of 7.58%–22.45%, and over contract guidance without fine-tuning by 1.19–2.38 percentage points, corresponding to relative improvements of 7.04%–14.65%. Our manual contract-quality analysis further shows that contracts classified as semantically correct are consistently associated with stronger downstream code-generation performance than contracts containing semantic defects. These results provide evidence that explicitly translating natural-language requirements

Authors' Contact Information: Brhane Teamrat Gidey, York University, Department of Electrical Engineering and Computer Science, North York, Canada, brhane.teamrat.gidey@gmail.com; Tiantian Yang, York University, Department of Electrical Engineering and Computer Science, North York, Canada, yang11@my.yorku.ca; Nikta Akbarpour, York University, Department of Electrical Engineering and Computer Science, North York, Canada, niktakbr@yorku.ca; Simone Bartucci, University of Calabria, Computer Science, Arcavacata, Italy, simone.bartucci@unical.it; Francesco Calimeri, University of Calabria, Computer Science, Arcavacata, Italy, francesco.calimeri@unical.it; Song Wang, York University, Department of Electrical Engineering and Computer Science, North York, Canada, wangsong@yorku.ca.

Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org.

© 2026 Copyright held by the owner/author(s). Publication rights licensed to ACM.

ACM XXXX-XXXX/2026/10-ART

https://doi.org/10.1145/nnnnnnn.nnnnnnn

Brhane Teamrat Gidey, Tiantian Yang, Nikta Akbarpour, Simone Bartucci, Francesco Calimeri, and Song Wang

into validated behavioral contracts can improve functional correctness without modifying the downstream code-generation model.

CCS Concepts: • Software and its engineering → Software maintenance tools; Software verification and validation.

Additional Key Words and Phrases: Code Generation, LLMs, Program Specifications, Supervised Fine-Tuning

ACM Reference Format:

Brhane Teamrat Gidey, Tiantian Yang, Nikta Akbarpour, Simone Bartucci, Francesco Calimeri, and Song Wang. 2026. Better Specifications, Better Code: Fine-Tuning LLMs for Behavioral Contract Generation. 1, 1 (October 2026), 20 pages. https://doi.org/10.1145/nnnnnnn.nnnnnnn

1 Introduction

Large language models (LLMs) have made substantial progress in code generation, with code-specialized models demonstrating strong performance across a wide range of programming benchmarks [6, 27]. Nevertheless, functional correctness remains challenging for programming tasks with multiple interacting requirements, constraints, and corner cases [21, 30].

Existing approaches attempt to reduce this problem by introducing intermediate reasoning before code generation. Chain-of-Thought [31], structured reasoning [14], and self-planning approaches [10] encourage models to reason about a task or construct an implementation plan before producing code. More specifically, approaches such as μ\muFiX [30] explicitly improve an LLM's understanding of programming specifications through natural-language reasoning and test-case-driven feedback. These approaches demonstrate that separating requirement understanding from immediate implementation can improve code generation. However, the resulting understanding is typically represented as informal natural-language reasoning. Such representations can remain ambiguous, omit important behavioral requirements, or introduce assumptions that are not supported by the original task. Moreover, approaches that use execution feedback or execution-based verification [23] assume that suitable test cases or other behavioral signals are available.

We explore a different direction: rather than representing requirement understanding only through informal reasoning, can an LLM explicitly translate a programming task into a structured behavioral specification before generating its implementation?

Behavioral contracts provide a natural representation for this purpose [20]. A contract expresses program behavior through explicit conditions and constraints, separating the specification of expected behavior from the details of its implementation. Recent work has demonstrated the potential of LLMs for synthesizing formal specifications. SpecGen uses LLMs together with mutation and verification to generate formal program specifications [18]; NL2ACSL translates natural-language requirements into ACSL function contracts using retrieval and multiple agents [28]; and VeriSpecGen decomposes natural-language requirements and iteratively validates and repairs generated formal specifications [33]. These studies demonstrate that LLMs can recover useful specifications from natural language or code. However, specification generation has primarily been studied as an end goal for program analysis and verification, rather than as an active intermediate reasoning step to guide LLMs. Furthermore, relying on zero-shot prompting to generate these intermediate contracts is risky. As we observe in our experiments, generated contracts can introduce unsupported constraints or misrepresent task requirements, producing flawed specifications that may mislead downstream implementation. More generally, prior work has highlighted limitations in the ability of LLMs to reliably identify and correct their own reasoning errors [8]. Therefore, how to systematically generate, validate, and specialize intermediate contracts to reliably improve functional correctness remains a critical open challenge.

Task ID: taco_train_14835 | Model: DeepSeek-Coder-V2-Lite-Instruct

For each of t test cases, given a sequence a of n integers, define its weight as the number of unordered index pairs (i,j) satisfying i < j and a_i = a_j, and define a subsegment as any contiguous portion of a; output the sum of the weights of all subsegments, where 1≤t,n≤1051 \leq t, n \leq 10^5, 1≤ai≤1091 \leq a_i \leq 10^9, and the sum of n across all test cases does not exceed 10510^5.

Vanilla Generation

Original task only; no generated contract.

def calculate_weight(a): count = {} for value in a: count[value] = count.get(value, 0) + 1

weight = 0 for value, freq in count.items(): weight += freq * (freq - 1) // 2 return weight

Base-Contract Guidance

Postcondition clause: { "expression": "output == sum(sum(i for i in range(n)) for j in range(i+1, n) if a[i] == a[j]) for a in test_cases", "description": "The output should be the sum of the weight of all subsegments of each sequence." }

def sum_of_weights(test_cases): results = [] for a in test_cases: total_weight = 0 for value in set(a): freq = a.count(value) total_weight += freq * (freq - 1) // 2 results.append(total_weight) return results

SFT-Contract Guidance

Postcondition clause: { "expression": "output == sum(count_weights(a) for a in test_cases", "description": "The output is the sum of the weights of all subsegments of each test case." }

def count_weights(a): n = len(a) result = 0 for i in range(n): count = {} for j in range(i, n): count[a[j]] = count.get(a[j], 0) + 1 pairs = 0 for value in count: pairs += count[value] * (count[value] - 1) // 2 result += pairs return result

Fig. 1. Motivating example from the held-out TACO evaluation set (task ID: taco_train_14835). The Vanilla implementation fails, while the Base-Contract-guided implementation fails due to a semantic mismatch. The SFT-Contract-guided implementation succeeds with a semantically consistent contract.

Figure 1 illustrates this challenge using a real example, taco_train_14835, from the TACO algorithmic code-generation dataset [15]. To ensure a controlled comparison, we use the same model, DeepSeek-Coder-V2-Lite-Instruct [34], as the downstream code generator across all settings, with the natural-language task description as input. The three settings differ only in how the contract is introduced. In Vanilla, the model generates code directly from the task description without any contract. In Base Contract, the original DeepSeek-Coder-V2-Lite-Instruct first generates a behavioral contract from the task description, which is then provided together with the task to guide code generation. In SFT-Contract, the contract is instead generated by DeepSeek-Coder-V2-Lite-Instruct fine-tuned using our contract-specific approach, while the downstream code generator remains the original, unchanged model. This controlled setup allows us to isolate the effect of introducing behavioral contracts and, more importantly, improving their quality through contract-specific fine-tuning.

As shown in Figure 1, the quality of the intermediate contract can affect the generated solution. In the Vanilla setting, the model fails to correctly capture the required behavior and produces an incorrect implementation. Introducing a Base Contract makes the behavioral requirements more explicit; however, the generated contract contains a semantic mismatch: although its natural-language description correctly describes the required aggregation over all contiguous subsegments, the corresponding machine-readable expression computes the metric only once. This incorrect specification propagates to the downstream code, resulting in another failed implementation. In contrast, the SFT Contract correctly and consistently captures the required behavior in both its natural-language description and machine-readable expression. Guided by this higher-quality contract, the same downstream model generates an implementation that passes the test suite. This example highlights that simply introducing a contract is not sufficient; the semantic quality and consistency of the generated contract are critical to its effectiveness in guiding code generation.

Motivated by these observations, we present CG2CG^{2}: Contract-Guided LLM Code Generation, a framework that introduces automatically generated behavioral contracts as intermediate representations between natural-language programming tasks and their implementations. Rather than adapting the downstream code-generation model, CG2CG^{2} specializes the intermediate contract-generation step through supervised fine-tuning (SFT). To construct the contract-specific SFT dataset,

Brhane Teamrat Gidey, Tiantian Yang, Nikta Akbarpour, Simone Bartucci, Francesco Calimeri, and Song Wang

we first use GPT-4o-mini [24] exclusively for training-data construction to generate candidate contracts, which are subsequently filtered, reviewed, and cleaned by the authors. Because even fine-tuned models may generate contracts that omit or misrepresent task requirements, CG2CG^{2} further performs semantic validation and repair before using the contracts for code generation. Specifically, generated contracts are checked against the original programming task, identified semantic defects are used to guide contract repair, and repaired contracts are revalidated before being accepted. Throughout this process, the original task serves as the primary semantic reference, while the downstream code-generation model remains unchanged.

We evaluate CG2CG^{2} on a fixed set of 1,007 held-out programming tasks from TACO, a large-scale competitive-programming benchmark with executable test cases and difficulty annotations [15].

Our evaluation covers five code LLMs under four controlled conditions: Vanilla, Base Contract, SFT, and Validated SFT. The downstream code-generation model and settings remain fixed while only contract generation and refinement vary. Section 4 provides the complete methodology.

Across all five models, pass@1 increases from Vanilla to Base Contract, SFT, and Validated SFT. Overall, CG2CG^{2} improves pass@1 over direct generation by 1.49–3.27 percentage points, corresponding to relative improvements of 7.58%–22.45%, and over contract guidance without fine-tuning by 1.19–2.38 percentage points, corresponding to relative improvements of 7.04%–14.65%. This paper makes the following contributions:

• Behavioral contracts as an intermediate representation for code generation. We formulate contract-guided code generation, in which an LLM first translates a natural-language programming task into a structured behavioral contract and then uses the contract to guide implementation. This formulation explicitly separates reasoning about what behavior a program should satisfy from how that behavior should be implemented.

• Learning to generate contracts for downstream code generation. We develop a contract-specific supervised fine-tuning approach that specializes LLMs to synthesize structured contracts. Unlike approaches that adapt the code generator itself, our approach improves the intermediate specification while keeping the downstream code-generating model unchanged.

• Semantic quality control for generated contracts. We introduce an iterative validation and repair procedure that checks synthesized contracts against the original programming task, identifies semantic defects, and repairs them before code generation, without relying on reference implementations, generated code, or execution feedback.

• Large-scale empirical analysis of contract-guided code generation and contract quality. We evaluate CG2CG^{2} on 1,007 held-out TACO tasks across five LLMs under four controlled conditions. Beyond overall code-generation performance, we manually analyze the semantic quality of generated contracts, examine the relationship between contract-quality categories and downstream pass@1, and study the contribution of individual contract components.

The remainder of this paper is organized as follows. Section 2 reviews the related work. Section 3 presents CG2CG^{2}. Section 4 describes the research questions and experimental methodology. Section 5 reports the empirical results. Section 6 discusses the key findings. Section 7 presents the threats to validity, and Section 8 concludes the paper.

References (24)