alphaFeedback

WorksComputer Science

Validating Autoformalized Specifications via Contrapuntal Languages

AI contributions
Not recorded for this paper
View details
Ancillary data
1 data link
View

Abstract

Formal specifications can make AI-generated code mechanically checkable. Because user intent is typically expressed in natural language rather than formal logic, specifications must first be derived from it, e.g., via LLM-based autoformalization. Yet autoformalized specifications are themselves untrusted, so a key challenge is validating whether they capture user intent without relying on a costly oracle such as human review. In this oracle-free setting, a natural strategy is to vote among model outputs, but because model errors are often correlated, agreement among outputs may reflect shared mistakes rather than correctness. Our key insight is that these errors can be decorrelated through representational diversity. We achieve this diversity with contrapuntal languages: pairs of task-specific formal languages, each designed to express the intended specification, yet admitting no structure-preserving translation between them. An LLM formalizes the intent independently in each language, and we accept a specification only if a solver proves the two formalizations equivalent. To construct such languages, we present a synthesis algorithm that reuses fragments of sampled seed specifications as syntactic sugar over a base specification language. We implement the approach for first-order logic specifications and evaluate it on HumanEval+ and LiveCodeBench using GPT-5.4 mini and Qwen3.6-Flash with and without thinking. Over the strongest baseline, our method increases the proportion of accepted specifications that are correct, i.e., complete and sound, by 12.0% on HumanEval+ and 42.9% on LiveCodeBench. The accepted specifications judged complete reject 98.6% of buggy program variants on HumanEval+ and 96.2% on LiveCodeBench, compared with 92.8% and 78.3% for the strongest baseline.

CCS Concepts: • Software and its engineering → Automatic programming; Formal software verification; • Computing methodologies → Natural language processing.

Additional Key Words and Phrases: Intent Autoformalization, Specification Validation, Large Language Models

Introduction

As large language models (LLMs) generate code faster than humans can review it [7, 27], the central challenge is shifting from generating code to determining whether that code faithfully captures the user’s intent. A promising answer is intent autoformalization: automatically translating natural-language intent into formal specifications against which generated code can be mechanically verified. Yet this only relocates the trust problem: if the specification is itself produced by a fallible autoformalization process, does it capture the user’s intent expressed in natural language? Prior studies on HumanEval tasks show that generating behaviorally correct postconditions and contracts

Authors’ Contact Information: Yihan Dai, Peking University, Beijing, China, [email protected]; Xuanlin Liu, Nankai University, Tianjin, China, [email protected]; Haoxiang Jia, Peking University, Beijing, China, [email protected]; Tianchi Li, Peking University, Beijing, China, [email protected]; Xin Zhang, Peking University, Beijing, China, [email protected]; Sergey Mechtaev, Peking University, Beijing, China, [email protected]. from natural-language intent remains challenging for LLMs [8, 29, 30]. For example, even for Python contracts on HumanEval, the setting most familiar to LLMs, only 39.5% of GPT-5-generated contracts that raised no false alarms on the reference implementation rejected every evaluated mutant [30]. However, validating generated specifications typically requires costly human review, making oracle-free validation a central bottleneck for reliable AI-assisted software development [17].

How can we validate whether autoformalized specifications accurately capture the user’s intent without an external oracle? A straightforward approach is voting. Plurality voting [10, 19] partitions the specifications into equivalence classes and selects the largest, i.e., the most frequently occurring semantics. However, LLM-generated artifacts often exhibit correlated errors [15]; when multiple candidates share the same mistake, plurality voting can reinforce the dominant error rather than identify the correct answer [31]. Also, plurality voting treats each candidate as an indivisible vote, ignoring its internal structure: a candidate need not be correct as a whole for some of its components to be useful. Clause2Inv [3], for example, shows that clauses extracted from invalid invariant candidates can contribute to a valid invariant. Yet reusing such fragments naively would steer the model back toward the same formalizations, and thus the same errors. The challenge is therefore to reuse useful fragments while inducing sufficiently different formalization paths.

To address these challenges, we build on the insight that representational diversity can break the correlation between errors. Inspired by linguistic determinism—the hypothesis that language shapes thought [33]—we introduce contrapuntal languages: pairs of task-specific formal languages, each designed to express the intended specification, yet admitting no structure-preserving translation between them. An LLM formalizes the intent independently in each language, and we accept a specification only if a solver proves the two formalizations equivalent. Because the model must discover separately how to express the intent in each language’s constructs, cross-language agreement is less likely to reflect a correlated error than agreement within a single language.

To construct such languages, we present a synthesis algorithm that builds both languages as syntactic sugar over a base specification language. We first sample seed specifications for the task from the LLM; the algorithm then cuts each seed into fragments and turns them into language constructs, using a solver to choose cuts that carve every seed into differently shaped trees in the two languages. Since the intended specification is unknown, the seeds stand in for it: we call a language pair effectively contrapuntal for a seed set when every seed can be represented in both languages, but no AST-level structure-preserving translation relates its representations across them. This design also addresses the challenge of reusing fragments: seed fragments let the model reuse useful components, even from incorrect seeds, while the structural incompatibility of the two languages still forces separate formalization paths and thus decorrelates errors.

We implement the approach for first-order logic specifications in SMT-LIB and evaluate it on HumanEval+ [21] and LiveCodeBench [12] using GPT-5.4 mini and Qwen3.6-Flash with and without thinking. We compare it against direct generation, plurality voting, and round-trip verification, judging a specification complete if it accepts reference input–output pairs and sound if it rejects the outputs of buggy program variants. Over the strongest baseline, our method increases the proportion of accepted specifications that are both complete and sound by 12.0% on HumanEval+ and 42.9% on LiveCodeBench, and the accepted specifications judged complete reject 98.6% and 96.2% of buggy program variants, respectively, compared with 92.8% and 78.3% for the strongest baseline. An ablation shows that these gains depend on enforcing contrapuntality rather than merely using two languages, and a case study shows that disagreement between contrapuntal languages can surface ambiguity in a task description.

In summary, the paper makes the following contributions:

  • A new approach that automatically validates autoformalized specifications without an oracle through contrapuntal languages.

  • An algorithm to automatically synthesize contrapuntal languages with an SMT solver.

  • An evaluation on HumanEval+ and LiveCodeBench showing that contrapuntal languages accept a higher proportion of complete and sound specifications than three baselines, and that the accepted specifications judged complete detect more bugs.

All code and data are available at https://figshare.com/s/be97e0291c8ce608bcd4.

Motivating Example

To illustrate the difficulty of validating autoformalized specifications without access to any intent oracle, we use HumanEval/135 as a running example. The task asks can_arrange(arr: list[int]) to return the largest index ii such that arr[i]<arr[i−1]\mathit{arr}[i] < \mathit{arr}[i - 1], or −1-1 if no such index exists.

When using Qwen3.6-Flash (thinking=on) to autoformalize this task into an SMT-LIB specification, it has a low success rate: the estimated probability of sampling a correct specification (formula III in Figure 1) is only 0.17, while the dominant incorrect one (the first formula in Figure 1) has the probability 0.27 (8/30) > 0.17 (5/30). This incorrect specification does accept the intended output on every observed positive example, but it also permits r=−1r = -1 when such valid index rr exists. It is therefore complete but unsound.

Plurality voting on HumanEval/135 with $n = 30$ samples

Figure 1. Plurality voting on HumanEval/135 with n=30n = 30 samples. A correlated error (I, 8/30) outnumbers the correct specification (III, 5/30), so Plurality accepts it. Yet the key components of III already appear in the incorrect I and II, motivating language synthesis from such fragments. descend_at(i,a)≜(1≤i<∣a∣)∧(a[i]<a[i−1])\mathit{descend\_at}(i,a) \triangleq(1 \le i < |a|) \land(a[i] < a[i-1]); largest(r,a)≜∀i. (descend_at(i,a)⇒i≤r)\mathit{largest}(r,a) \triangleq\forall i.\,(\mathit{descend\_at}(i,a) \Rightarrow i \le r).

Plurality voting selects the most frequent semantic equivalence class among all sampled specifications. It can be ineffective because LLMs tend to produce correlated errors—a phenomenon observed not only across samples from the same model but even across different models [15]. In challenging cases like HumanEval/135, plurality voting amplifies rather than mitigates mistakes: as shown in Figure 1, it selects the dominant incorrect class over the correct one. Plurality voting also underuses the information in the candidate specifications, using them only to count equivalence classes. Yet a candidate need not be correct as a whole for some of its components to contribute to a correct specification: in Figure 1, the key components of the correct specification already appear in the incorrect ones. We therefore split candidates into small pieces that, like the building bricks in Figure 1, form a small, task-specific vocabulary. We call this process “synthesizing a language from seed formalizations”.

Autoformalization in a single language still suffers from correlated errors. To decorrelate them, we exploit linguistic determinism: we force the model to “think” differently by formalizing the intent in two different languages synthesized from the seeds. Figure 2 illustrates why these languages must be chosen carefully. If both are synthesized from the same seeds (top row), they may be identical, and cross-language validation reduces to plurality voting, preserving the correlated error. A natural remedy is to randomly split the seeds into two subsets and synthesize one language from each (middle row), yielding L1′\mathcal{L}'_1 and L2′\mathcal{L}'_2. This split-seed strategy, however, fails in two ways. First, it makes the languages too different: each exposes the LLM to different fragments, so their outputs diverge. Formalizations under L1′\mathcal{L}'_1 contain no correct specification, whereas those under L2′\mathcal{L}'_2 contain seven, so no correct specification can be accepted. Second, it does not make them different enough: splitting the seeds gives no control over correlated errors, and the incorrect formalization under L2′\mathcal{L}'_2 is equivalent to seven under L1′\mathcal{L}'_1, so the error is accepted anyway. Our ablation study (§ 6.2) shows that these failures are systematic rather than specific to this example.

Autoformalizing in identical, split-seed, and contrapuntal languages

Figure 2. Autoformalizing in identical languages (top) reduces to plurality voting; in languages from split seeds (middle), outputs diverge yet share the error. Contrapuntal languages (bottom) both express the correct formalization but are structurally incompatible, so the LLM does not repeat its mistakes.

These two failures suggest that the languages require a delicate balance: similar enough that correct formalizations can be matched across them, yet different enough that errors do not recur in both. We capture this balance with a property we call contrapuntality (formalized in Definition 4.2), which combines two requirements. Adequacy requires that both languages can express the intended specification; unlike split-seed languages, they thus offer comparable expressive power, so a correct formalization in one language has a counterpart in the other. Non-isomorphism requires that no structure-preserving translation relates formalizations across the two languages; the model therefore cannot reuse the structure of a formalization in one language when writing it in the other, making it less likely to repeat the same error in both. Here, structure refers to the shape of abstract syntax trees (ASTs): languages that differ only in vocabulary produce ASTs of the same shape for the same formula, so validating across them reduces to plurality voting.

With contrapuntal languages (bottom row of Figure 2), the example is handled correctly. On the one hand, the incorrect seeds are cut into different fragments and thus have different AST structures in the two languages, making it difficult for the same error to recur in both. On the other hand, since both languages are synthesized from all seeds, each can extract critical structures from the correct seeds—specifically, structures that prevent the LLM from unconditionally accepting r=−1r=-1. For example, L1′′L_1'' obtains construct 5 and L2′′L_2'' obtains construct 5′. Formalizations in both languages use these structures, form equivalent pairs, and are therefore accepted.

The distinction matters when the validated specification is used to check generated code. Consider this buggy implementation of can_arrange, whose backward scan stops before index 1:

def can_arrange(arr):
    for i in range(len(arr) - 1, 1, -1):
        if not (arr[i] >= arr[i - 1]):
            return i
    return -1

On input arr=[6,0,1,2,3]arr=[6, 0, 1, 2, 3], the mutant returns r=−1r=-1, whereas the intended result is r=1r=1 because arr[1]<arr[0]arr[1] < arr[0]. Formula I, selected by plurality voting, admits the incorrect input–output pair (arr,−1)(arr,-1), so the mutant survives the specification check. In contrast, the specifications accepted by our method realize Formula III, which permits r=−1r=-1 only when no decreasing adjacent pair exists. Because descend_at(1,arr)descend\_at(1,arr) holds, Formula III is unsatisfiable for r=−1r=-1, so it rejects the incorrect behavior and kills the mutant. Thus, more reliable specification validation translates directly into stronger bug detection. Beyond bug detection, disagreement between contrapuntal languages can also surface ambiguity in the task description, as our case study shows (§ 6.6).

Background & Notation

Presenting our approach requires writing formulas in formal languages while also reasoning about these languages. We therefore distinguish the object languages, in which formulas are written, from the meta-language, in which we reason about them. Greek letters are placeholders, called meta-variables: φ\varphi, ψ\psi, χ\chi stand for arbitrary formulas and π\pi, ρ\rho for arbitrary positions. All other symbols stand for themselves, with two exceptions: xx stands for an arbitrary object variable, and the names we define for particular formulas and variables, such as Def⁡i\operatorname{Def}^{i} and cnic^{i}_{n} in § 5.2, stand for what they name. Thus, p(ν)∧q(ν)p(\nu) \land q(\nu) is a concrete formula, whereas φ∧ψ\varphi\land\psi denotes the conjunction of the formulas that φ\varphi and ψ\psi stand for. We also distinguish three kinds of equality: == is meta-level identity, which for formulas means identity of their syntax trees; == is the equality symbol of the object language; and ≡\equiv is semantic equivalence (defined below). For example, φ∧∅≠φ\varphi\land\varnothing\ne\varphi, yet φ∧ψ=φ\varphi\land\psi= \varphi.

Our approach targets specifications written in first-order logic, the common input language of SMT solvers, standardized by SMT-LIB [2]; this lets us check the equivalence of formalizations automatically. These formulas form the base language L0\mathcal{L}_0: they are built as usual from atoms, object equality ≐\doteq, the connectives ¬\neg, ∧\land, ∨\lor, →\to, ↔\leftrightarrow, the constants ⊤\top and ⊥\bot, and the quantifiers ∀\forall and ∃\exists. We interpret formulas over fixed domains, such as the integers and arrays, in which function and predicate symbols have fixed meanings. The denotation ⟦φ⟧\llbracket\varphi\rrbracket of a formula φ\varphi is the set of variable assignments that make φ\varphi true. For example, ⟦r=−1∨r≥1⟧\llbracket r=-1\lor r\ge1\rrbracket consists of the assignments that map rr to −1-1 or to a positive integer. For a specification whose free variables are the inputs and outputs of a program, the denotation is thus the set of input–output pairs that the specification admits. Formulas φ\varphi and ψ\psi are semantically equivalent, written φ≡ψ\varphi\equiv\psi, iff ⟦φ⟧=⟦ψ⟧\llbracket\varphi\rrbracket=\llbracket\psi\rrbracket.

Definition 3.1 (Language). A language L\mathcal{L} consists of (i) an alphabet Λ\Lambda of symbols, each with an arity ar⁡(α)∈N\operatorname{ar}(\alpha) \in\mathbb{N}; (ii) a set of L\mathcal{L}-formulas, written φ∈L\varphi\in\mathcal{L}: finite trees in which every node labeled α∈Λ\alpha\in\Lambda has ar⁡(α)\operatorname{ar}(\alpha) children, possibly subject to further well-formedness constraints; and (iii) a semantics assigning to every L\mathcal{L}-formula ψ\psi a denotation ⟦ψ⟧\llbracket\psi\rrbracket, a set of variable assignments, so that semantic equivalence applies across languages. We write Λi\Lambda_i for the alphabet of a language Li\mathcal{L}_i.

Our approach compares formulas by the shapes of their syntax trees, so we need notation for addressing the parts of a formula. A position is a finite string of positive integers: the empty string ε\varepsilon addresses the root, and πi\pi i addresses the ii-th child of the node at π\pi. For a formula φ\varphi, Pos⁡(φ)\operatorname{Pos}(\varphi) is its set of positions, φ(π)\varphi(\pi) is the label of the node at π\pi, and φ∣π\varphi|_{\pi} is the subtree rooted there. Bound variables are folded into quantifier labels: the root of ∀x. φ\forall x.\,\varphi is a unary node labeled ∀x\forall x, so that positions reflect logical structure only. We write π⊑π′\pi\sqsubseteq\pi' if π\pi is a prefix of π′\pi', that is, if π′\pi' lies in the subtree at π\pi, and π⊏π′\pi\sqsubset\pi' if moreover π≠π′\pi\ne\pi'.

We synthesize new languages as syntactic sugar over the base language L0\mathcal{L}_0. Each construct of a new language abbreviates a fixed pattern of L0\mathcal{L}_0-formulas, so the new languages change how specifications are written but not what they mean.

Definition 3.2 (Sugared language). A sugared language L\mathcal{L} has an alphabet Λ\Lambda of constructs and, for every construct α∈Λ\alpha\in\Lambda of arity kk, a definition DαD_\alpha. The definition is a finite tree over the symbols of L0\mathcal{L}_0 and fresh holes □1,…,□k\Box_1,\ldots,\Box_k, in which each hole occurs at least once and at least one node is not a hole, such that filling the holes with L0\mathcal{L}_0-formulas χ1,…,χk\chi_1,\ldots,\chi_k yields an L0\mathcal{L}_0-formula Dα[χ1,…,χk]D_\alpha[\chi_1,\ldots,\chi_k]. The L\mathcal{L}-formulas are the trees over Λ\Lambda, and desugaring replaces every construct by its definition:

D(χ)≜Dα[D(χ∣1),…,D(χ∣k)],where α=χ(ε) and k=ar⁡(α).D(\chi) \mathrel{\triangleq} D_\alpha[D(\chi|_1),\ldots,D(\chi|_k)], \qquad\text{where } \alpha= \chi(\varepsilon) \text{ and } k = \operatorname{ar}(\alpha).

An L\mathcal{L}-formula denotes what its desugaring denotes, ⟦χ⟧≜⟦D(χ)⟧\llbracket\chi\rrbracket\mathrel{\triangleq} \llbracket D(\chi)\rrbracket; in particular, χ≡D(χ)\chi\equiv D(\chi).

We say that χ\chi desugars to an L0\mathcal{L}_0-formula ψ\psi iff D(χ)=ψD(\chi)=\psi without variable capture: every bound variable occurrence in ψ\psi comes from the same node of χ\chi as its quantifier. The sugarings of ψ\psi in L\mathcal{L} form the set Sug⁡L(ψ)≜{χ∈L∣χ desugars to ψ}\operatorname{Sug}_{\mathcal{L}}(\psi) \mathrel{\triangleq} \{\chi\in\mathcal{L} \mid\chi\text{ desugars to } \psi\}; In our supplementary materials, we illustrate these notions on Formula I of Figure 1.

Finally, we define correctness for autoformalization, the translation of a natural-language specification into a formula. We write η\eta for such an informal specification and NL\mathsf{NL} for the set of all of them. We do not analyze their syntax; we only assume that each η\eta has a denotation ⟦η⟧\llbracket\eta\rrbracket: the set of variable assignments, such as input–output pairs, that the user intends (for ambiguous text, the reading the user has in mind). We write ψ≡η\psi\equiv\eta iff ⟦ψ⟧=⟦η⟧\llbracket\psi\rrbracket= \llbracket\eta\rrbracket. Unlike equivalence between formulas, this cannot be checked automatically, because ⟦η⟧\llbracket\eta\rrbracket is known only to the user.

A formula ψ\psi is sound for η\eta iff ⟦ψ⟧⊆⟦η⟧\llbracket\psi\rrbracket\subseteq\llbracket\eta\rrbracket: every behavior it admits is intended. It is complete for η\eta iff ⟦η⟧⊆⟦ψ⟧\llbracket\eta\rrbracket\subseteq\llbracket\psi\rrbracket: every intended behavior is admitted. A correct formalization of η\eta is both sound and complete, that is, ψ≡η\psi\equiv\eta. For example, Formula I in Figure 1 is complete but unsound: it admits every intended output, but also r=−1r=-1 on the input [6,0,1,2,3][6,0,1,2,3], whose intended output is 11. Conversely, descend⁡π(r,a)\operatorname{descend}_{\pi}(r,a) largest (r,a)(r,a) is sound but incomplete: it rejects the intended output −1-1 on inputs without a descent. Formula III is both sound and complete, and thus a correct formalization.

Definition 3.3 (Realization set). The realization set of an informal specification η\eta in a language L\mathcal{L} collects the correct formalizations of η\eta in L\mathcal{L}:

Real⁡L(η)≜{ψ∈L∣ψ≡η}.\operatorname{Real}_{\mathcal{L}}(\eta) \mathrel{\triangleq} \{\psi\in\mathcal{L} \mid\psi\equiv\eta\}.

The language L\mathcal{L} is adequate for η\eta iff Real⁡L(η)≠∅\operatorname{Real}_{\mathcal{L}}(\eta) \ne\varnothing.

Contrapuntal Languages

As § 2 showed, cross-checking formalizations in two languages is useful only if the languages are chosen well. First, both languages must be able to express the specification correctly; we call this adequacy. Second, the languages must differ enough that the LLM is unlikely to make the same mistake in both; we call this non-isomorphism. We refer to a pair of languages with both properties as contrapuntal, after musical counterpoint, where independent melodies combine into one harmony. In this section, we define these properties formally and then relax them to a version that can be checked automatically; § 5 shows how to synthesize languages that satisfy it.

Definition 4.1 (Structure-preserving translation). A structure-preserving translation from χ1∈L1\chi_1 \in\mathcal{L}_1 to χ2∈L2\chi_2 \in\mathcal{L}_2 is a one-to-one map τ\tau from the labels of χ1\chi_1 to the labels of χ2\chi_2 that turns χ1\chi_1 into χ2\chi_2 by relabeling: Pos⁡(χ1)=Pos⁡(χ2)\operatorname{Pos}(\chi_1) = \operatorname{Pos}(\chi_2) and χ2(π)=τ(χ1(π))\chi_2(\pi) = \tau(\chi_1(\pi)) for every π∈Pos⁡(χ1)\pi\in\operatorname{Pos}(\chi_1).

Definition 4.2 (Contrapuntal languages). Languages L1\mathcal{L}_1 and L2\mathcal{L}_2 are contrapuntal for an informal specification η∈NL\eta\in NL iff

(i) adequacy: both L1\mathcal{L}_1 and L2\mathcal{L}_2 are adequate for η\eta; and

(ii) non-isomorphism: no formula in Real⁡L1(η)\operatorname{Real}_{\mathcal{L}_1}(\eta) has a structure-preserving translation to a formula in Real⁡L2(η)\operatorname{Real}_{\mathcal{L}_2}(\eta).

Definition 4.2 captures our intuition, but it cannot be checked algorithmically, for two reasons. First, both clauses refer to realization sets, and hence to ⟦η⟧\llbracket\eta\rrbracket, which is known only to the user. Second, even with known semantics, non-isomorphism requires proving that synthesizing a translation is unrealizable, which is undecidable in general [11].

We make the problem tractable by weakening it in two ways. First, in place of the inaccessible semantics of η\eta, we use a finite set of seed formalizations: candidate formalizations of η\eta sampled from the LLM in the base language. The seeds stand for the candidate meanings of η\eta—the intended formalization together with its plausible near-miss variants. Second, we restrict the synthesized languages to syntactic sugar over the base language, and constrain only the sugarings of the seeds.

Definition 4.3 (Effective contrapuntality). Sugared languages L1\mathcal{L}_1 and L2\mathcal{L}_2 are effectively contrapuntal for a finite, nonempty set Ψ\Psi of L0\mathcal{L}_0-formulas iff, for every ψ∈Ψ\psi\in\Psi:

(i) adequacy: Sug⁡L1(ψ)≠∅\operatorname{Sug}_{\mathcal{L}_1}(\psi) \ne\varnothing and Sug⁡L2(ψ)≠∅\operatorname{Sug}_{\mathcal{L}_2}(\psi) \ne\varnothing; and

(ii) non-isomorphism: no formula in Sug⁡L1(ψ)\operatorname{Sug}_{\mathcal{L}_1}(\psi) has a structure-preserving translation to a formula in Sug⁡L2(ψ)\operatorname{Sug}_{\mathcal{L}_2}(\psi).

The two definitions differ only in replacing the realization sets Real⁡Li(η)\operatorname{Real}_{\mathcal{L}_i}(\eta), which contain all formulas equivalent to the intent, with the sugaring sets Sug⁡Li(ψ)\operatorname{Sug}_{\mathcal{L}_i}(\psi), which contain only the formulas that reproduce the syntax of the seed. Unlike realization sets, sugaring sets are finite and computable for a finite alphabet: every construct covers at least one node of ψ\psi, so a sugaring of ψ\psi is never larger than ψ\psi itself. Whether a translation maps one given formula to another is decided by comparing the two trees position by position. Effective contrapuntality is therefore decidable.

Example 4.4. Consider two seeds that differ in a single connective, ψ→=p(v)→q(v)\psi_{\to} = p(v) \to q(v) and ψ∧=p(v)∧q(v)\psi_{\land} = p(v) \land q(v), and let Ψ={ψ→,ψ∧}\Psi= \{\psi_{\to}, \psi_{\land}\}. Consider also two sugared candidate languages for Ψ\Psi: the constructs of L1\mathcal{L}_1 fuse the connective with the antecedent, whereas those of L2\mathcal{L}_2 mirror the base symbols one by one:

L1:Dα→=p(v)→□1,Dα∧=p(v)∧□1,Dαq=q(v);L2:Dβ→=□1→□2,Dβ∧=□1∧□2,Dβp=p(v),Dβq=q(v).\begin{aligned} \mathcal{L}_1:\quad&D_{\alpha\to} = p(v) \to\square_1,\qquad D_{\alpha\land} = p(v) \land\square_1,\qquad D_{\alpha q} = q(v);\\ \mathcal{L}_2:\quad&D_{\beta\to} = \square_1 \to\square_2,\qquad D_{\beta\land} = \square_1 \land\square_2,\qquad D_{\beta p} = p(v),\qquad D_{\beta q} = q(v). \end{aligned}

Each seed has one sugaring per language: ψ→\psi_{\to} has α→(αq)\alpha_{\to}(\alpha_q) and β→(βp,βq)\beta_{\to}(\beta_p,\beta_q), and ψ∧\psi_{\wedge} has α∧(αq)\alpha_{\wedge}(\alpha_q) and β∧(βp,βq)\beta_{\wedge}(\beta_p,\beta_q). The L1\mathcal{L}_1-sugarings have two nodes and the L2\mathcal{L}_2-sugarings three, so no translation relates them, and L1\mathcal{L}_1 and L2\mathcal{L}_2 are effectively contrapuntal for Ψ\Psi.

This balance between L1\mathcal{L}_1 and L2\mathcal{L}_2 is delicate. Extend L2\mathcal{L}_2 to L2′\mathcal{L}'_2 with a construct that fuses the connective with the consequent, Dγ→=□1→q(v)D_{\gamma_{\to}} = \Box_1 \to q(v). Now ψ→\psi_{\to} has a second sugaring, γ→(βp)\gamma_{\to}(\beta_p), and the relabeling α→↦γ→\alpha_{\to} \mapsto\gamma_{\to}, αq↦βp\alpha_q \mapsto\beta_p translates α→(αq)\alpha_{\to}(\alpha_q) into it (Figure 3), so L1\mathcal{L}_1 and L2′\mathcal{L}'_2 are no longer effectively contrapuntal. Note that this translation pairs αq\alpha_q, which stands for q(v)q(v), with βp\beta_p, which stands for p(v)p(v): a translation only relabels the tree, regardless of what the constructs stand for.

The seed $\psi_{\to}$ carved by $\mathcal{L}_1$ and by the extension $\mathcal{L}'_2$

Figure 3. The seed ψ→\psi_{\to} carved by L1\mathcal{L}_1 (left) and by the extension L2′\mathcal{L}'_2 (right). Each colored region is the fragment of the seed covered by one construct. The fragments correspond one to one (same colors), inducing the translation α→↦γ→\alpha_{\to} \mapsto\gamma_{\to}, αq↦βp\alpha_q \mapsto\beta_p.

Synthesis of Contrapuntal Languages

This section solves the synthesis problem: given the seed set Ψ\Psi, find a pair of sugared languages that is effectively contrapuntal for Ψ\Psi. Rather than reasoning about structure-preserving translations between all pairs of sugarings of every seed, our method enforces a simpler and more conservative requirement: that no two sugarings of a seed have the same shape.

Definition 5.1 (Shape). The shape of a formula χ\chi is its set of positions Pos⁡(χ)\operatorname{Pos}(\chi); formulas χ1∈L1\chi_1 \in\mathcal{L}_1 and χ2∈L2\chi_2 \in\mathcal{L}_2 have the same shape iff Pos⁡(χ1)=Pos⁡(χ2)\operatorname{Pos}(\chi_1) = \operatorname{Pos}(\chi_2)—that is, their trees are identical up to labels.

Formulas related by a structure-preserving translation have the same shape, but not conversely: p(u)∧p(v)p(u) \wedge p(v) and p(u)∧q(v)p(u) \wedge q(v) have the same shape, yet no translation relates them, since it would have to map pp to both pp and qq. Forbidding same-shaped sugarings therefore entails clause (ii) of Definition 4.3, and avoids quantifying over symbol maps: whether two sugarings have the same shape depends only on their positions, which § 5.2 encodes as quantifier-free constraints.

Our method searches over cuts of the seed trees. A cut of a formula is a non-root position π\pi; it severs the edge above the subtree at π\pi. A cut set C⊆Pos⁡(ψ)∖{ε}C \subseteq\operatorname{Pos}(\psi) \setminus\{\varepsilon\} partitions the tree into fragments, one rooted at ε\varepsilon and one at each cut, each extending downward until it meets a cut or a leaf. It thereby determines a sugar: each fragment becomes the definition of a construct, with its cuts as holes, and the resulting fragment tree is a sugared formula that desugars to the seed (Figure 4).

Two cut sets over the same seed

Figure 4. Two cut sets over the same seed: C1={11,21,211}C_{1} = \{11, 21, 211\} and C2={21,22,221}C_{2} = \{21, 22, 221\}. Gray labels give positions, triangles stand for subtrees, and double strokes mark cuts; colors mark the root fragment (peach) and the subtrees below it (blue, green). Both fragment trees have the shape {ε,1,2,21}\{\varepsilon, 1, 2, 21\}.

Incremental Synthesis Algorithm

The algorithm grows the two languages by adding constructs. An extension for a seed ψ\psi over a pair (L1,L2)(\mathcal{L}_1,\mathcal{L}_2) is a pair δ=(ΔL1,ΔL2)\delta= (\Delta\mathcal{L}_1,\Delta\mathcal{L}_2) of sets of fresh constructs, obtained from two cut sets of ψ\psi whose fragment trees differ in shape. Each ΔLi\Delta\mathcal{L}_i defines every fragment of the ii-th cut set not already in Li\mathcal{L}_i, so that its fragment tree is an (Li∪ΔLi)(\mathcal{L}_i \cup\Delta\mathcal{L}_i)-formula desugaring to ψ\psi. Extending thus only adds constructs and never changes existing definitions. Algorithm 1 is a backtracking fold over the seeds: each invocation of Synth⁡\operatorname{Synth} integrates the head of the list SS of remaining seeds by one extension and recurses on the tail, keeping its own set BB of extensions it has tried and rejected; PP is the set of integrated seeds, and both languages start empty.

The algorithm uses two subroutines. Cut⁡(ψ,L1,L2,B)\operatorname{Cut}(\psi,\mathcal{L}_1,\mathcal{L}_2,B) returns an extension for ψ\psi over (L1,L2)(\mathcal{L}_1,\mathcal{L}_2) that is not in BB, or none once its search space is exhausted (§ 5.3). FindIso⁡(Ψ′,L1,L2)\operatorname{FindIso}(\Psi',\mathcal{L}_1,\mathcal{L}_2) returns a witness (ψ′,χ1,χ2)(\psi',\chi_1,\chi_2), consisting of a seed ψ′∈Ψ′\psi' \in\Psi' and same-shaped sugarings χ1∈Sug⁡L1(ψ′)\chi_1 \in\operatorname{Sug}_{\mathcal{L}_1}(\psi') and χ2∈Sug⁡L2(ψ′)\chi_2 \in\operatorname{Sug}_{\mathcal{L}_2}(\psi'), or none if there is none (§ 5.3). This check is needed because an extension guarantees different shapes only for the two fragment trees it was built from: constructs may recombine into other sugarings of a seed, as γ→\gamma_{\to} recombines with βp\beta_p in Example 4.4. New constructs can create such recombinations for earlier seeds too, so line 12 rechecks every integrated seed.

An extension is blocked (line 17) either because it violates the shape constraint, when FindIso returns a witness, or because it is a dead end, when the recursive call finds no completion over the remaining seeds; the loop then asks Cut for another extension. Since BB is local to the invocation, it starts empty whenever the languages are extended and is restored on backtracking.

Theorem 5.2 (Correctness). Algorithm 1 terminates, and if it returns a pair of languages, the pair is effectively contrapuntal for Ψ\Psi.

The proof is given in our supplementary materials. The algorithm is incomplete: it may return none even if an effectively contrapuntal pair exists.

Encoding Shape Constraints

Figure 4 shows two cut sets that cut the same seed in unrelated places, yet yield fragment trees of the same shape. What matters is not where the cuts lie but how they nest: the holes of a fragment are its dominating cuts, those below its root with no other cut in between. At the root, C1C_1 has the dominating cuts 11 and 21 (with 211 below 21), and C2C_2 has 21 and 22 (with 221 below 22), so both top constructs have two holes. The constraints below capture this condition node by node.

We encode a pair of cut sets C1,C2C_1,C_2 of a seed ψ\psi symbolically, one for each language. Let i∈{1,2}i \in\{1, 2\}, and let all positions below range over Pos⁡(ψ)\operatorname{Pos}(\psi). For every non-root position π\pi, a Boolean cut variable cπic^i_\pi indicates that π∈Ci\pi\in C_i. For every position π\pi, a symbolic array aπia^i_\pi records where the node at π\pi ends up in the fragment tree of CiC_i: if π\pi roots a construct (π=ε\pi= \varepsilon or π∈Ci\pi\in C_i), aπia^i_\pi holds its position, and otherwise the constant nil; we also write ε\varepsilon for the empty array. A construct’s position gains one element per cut on the path from the root, so aπia^i_\pi has no more elements than π\pi. Figure 5 shows the arrays for C1C_1. The non-nil arrays of a cut thus enumerate the positions of its fragment tree, which is how the encoding compares shapes.

The array assignment for C1

Figure 5. The array assignment for C1C_{1} (Figure 4); gray annotations give aρ1a_{\rho}^{1}.

Three families of constraints determine the arrays from the cuts, a fourth compares the two cuttings, and a fifth handles binders. We write aπi⊑1aρia^i_\pi\sqsubseteq_1 a^i_\rho if neither array is nil and aρia^i_\rho holds a child of the position held by aπia^i_\pi.

The definedness constraints place the root of the seed at position ε\varepsilon of the fragment tree and make the array of any other position non-nil exactly when that position is cut:

Def⁡i≜aεi=ε∧⋀π≠ε(aπi≠nil⁡↔cπi).\operatorname{Def}^i \triangleq a^i_\varepsilon= \varepsilon\land\bigwedge_{\pi\ne\varepsilon} (a^i_\pi\ne\operatorname{nil} \leftrightarrow c^i_\pi).

("")]

// no algorithm transcription? Need include visible algorithm! forgot. Must insert before paragraphs likely right column reading order but algorithm appears alongside first paragraphs; reading order columns: left starts continuation then algorithm right? In single page two columns, algorithm float right starts around same. Reading order likely left column text then right algorithm? Algorithm is at top right and left text continues. But must include. Add after first paragraph perhaps. Need final revise. Also equation exact Def likely \mathrm{Def}^i and a epsilon superscripts. Use \triangleq. Algorithm plain. Ensure ends mid equation? page bottom equation complete visually, paragraph continues next page likely ends_mid 1 because section continuation? Last block equation seems complete, but text likely next page continues, equation not cut. ends_mid should 0 unless last paragraph runs? The page ends at equation, likely next text follows, equation block complete. ends_mid=0. starts mid yes.

Need output complete with algorithm. Use fenced code perhaps exact text. But math in algorithm should be math inline. plain lines. Add heading Algorithm 1? It is printed caption, should transcribe. Use bold lead. Could represent list lines. I'll include as paragraph/code-like fenced? Code listing would not preserve math. Use plain lines with line breaks, acceptable body block. The domination constraints determine the edges of the fragment tree: the construct at ρ\rho is a child of the construct at π\pi exactly when ρ\rho is cut and no cut lies strictly between π\pi and ρ\rho:

Dom⁡i≜⋀π⊏ρ(aπi⊑1aρi↔aπi≠nil⁡∧cρi∧⋀π⊏σ⊏ρ¬cσi)\operatorname{Dom}^{i} \mathrel{\triangleq} \bigwedge_{\pi\sqsubset\rho}\left(a_{\pi}^{i} \sqsubseteq_{1} a_{\rho}^{i} \leftrightarrow a_{\pi}^{i} \ne\operatorname{nil} \land c_{\rho}^{i} \land\bigwedge_{\pi\sqsubset\sigma\sqsubset\rho}\neg c_{\sigma}^{i}\right)

Domination determines which constructs are children of which, but not in what order. The ordering constraints number the children of every construct 1,…,d1,\ldots,d from left to right, following the order of their cuts in the seed. We write ρ≺ρ′\rho\prec\rho' if ρ\rho lies to the left of ρ′\rho' (neither is a prefix of the other, and ρ\rho is smaller at the first index where they differ); sib⁡(aρi,aρ′i)\operatorname{sib}(a_{\rho}^{i},a_{\rho'}^{i}) if both arrays are non-nil and hold positions of equal length that differ at most in the last element; and last⁡(aρi)\operatorname{last}(a_{\rho}^{i}) for the last element, where comparisons on last⁡\operatorname{last} imply that the arrays are non-nil and nonempty:

Ord⁡i≜⋀ρ≺ρ′(sib⁡(aρi,aρ′i)→last⁡(aρi)<last⁡(aρ′i))∧⋀ρ(last⁡(aρi)>1→⋁ρ′≺ρ(sib⁡(aρ′i,aρi)∧last⁡(aρi)=last⁡(aρ′i)+1))\operatorname{Ord}^{i} \mathrel{\triangleq} \bigwedge_{\rho\prec\rho'}\left(\operatorname{sib}(a_{\rho}^{i},a_{\rho'}^{i}) \to\operatorname{last}(a_{\rho}^{i}) < \operatorname{last}(a_{\rho'}^{i})\right) \land\bigwedge_{\rho}\left(\operatorname{last}(a_{\rho}^{i}) > 1 \to\bigvee_{\rho' \prec\rho}\left(\operatorname{sib}(a_{\rho'}^{i},a_{\rho}^{i}) \land\operatorname{last}(a_{\rho}^{i}) = \operatorname{last}(a_{\rho'}^{i}) + 1\right)\right)

The first conjunct orders siblings as their cuts are ordered in the seed and, since sib allows equal last elements, prevents two constructs from sharing a position; the second makes indices contiguous.

The same-shape constraint requires every construct position realized in one fragment tree to be realized in the other:

Shape⁡≜⋀ρ(aρ1≠nil⁡→⋁ρ′aρ′1=aρ2)∧⋀ρ(aρ2≠nil⁡→⋁ρ′aρ′2=aρ1)\operatorname{Shape} \mathrel{\triangleq} \bigwedge_{\rho}\left(a_{\rho}^{1} \ne\operatorname{nil} \to\bigvee_{\rho'}a_{\rho'}^{1} = a_{\rho}^{2}\right) \land\bigwedge_{\rho}\left(a_{\rho}^{2} \ne\operatorname{nil} \to\bigvee_{\rho'}a_{\rho'}^{2} = a_{\rho}^{1}\right)

Since Def⁡i∧Dom⁡i∧Ord⁡i\operatorname{Def}^{i} \land\operatorname{Dom}^{i} \land\operatorname{Ord}^{i} force the arrays to hold the actual positions of the constructs, Shape holds exactly when the two fragment trees have the same shape.

The binding constraints keep every bound variable occurrence in the same fragment as its quantifier, as sugarings require (§ 3); for example, they forbid cutting p(v)p(v) out of ∀v. (p(v)→q(v))\forall v.\ (p(v) \to q(v)). We write π\pi binds ρ\rho if π\pi is labeled ∀x\forall x or ∃x\exists x and ρ\rho is an occurrence of xx bound by it:

Bnd⁡i≜⋀π binds ρ⋀π⊑σ⊑ρ¬cσi\operatorname{Bnd}^{i} \mathrel{\triangleq} \bigwedge_{\pi\ \mathrm{binds}\ \rho}\bigwedge_{\pi\sqsubseteq\sigma\sqsubseteq\rho}\neg c_{\sigma}^{i}

Subroutines Cut and FindIso

Both subroutines search cut sets of a seed with the constraints of § 5.2: Cut for two cut sets whose fragment trees differ in shape, and FindIso for two sugarings of the same shape built from existing constructs. We solve all queries, including a MaxSAT problem, with the Z3 SMT solver [6].

Cut⁡(ψ,L1,L2,B)\operatorname{Cut}(\psi, L_1, L_2, B) works in two steps: a matching step decides which constructs of L1L_1 and L2L_2 are reused in ψ\psi, and a cutting step cuts the rest of ψ\psi.

A match of a construct α∈Λi\alpha\in\Lambda_i at a position π\pi is an occurrence of DαD_\alpha in ψ\psi: its non-hole nodes coincide with the nodes of ψ\psi at and below π\pi, and its holes fall at positions ρ1,…,ρar⁡(α)\rho_1,\ldots,\rho_{\operatorname{ar}(\alpha)}. Adopting the match makes the occurrence one fragment:

match⁡α,πi≜cπi∧⋀jcρji∧⋀σ¬cσi\operatorname{match}^{i}_{\alpha,\pi} \triangleq c^{i}_{\pi} \land\bigwedge_j c^{i}_{\rho_j} \land\bigwedge_{\sigma} \neg c^{i}_{\sigma}

where σ\sigma ranges over the non-hole positions strictly below π\pi covered by DαD_\alpha, and cπic^{i}_{\pi} is dropped when π=ε\pi=\varepsilon. Matches are found by syntactic comparison, at most one per construct and position.

The matching step reuses as many constructs of L1L_1 and L2L_2 as possible. Adopting every match is impossible in general, since two matches may disagree on a cut variable, so we treat the match formulas as soft constraints and use MaxSat to find a largest set of them that hold together with Bnd. The cut variables they determine are then fixed (Figure 6).

Matching constructs and their occurrences in a seed

Figure 6. Matching constructs κ1,κ2∈Λ1\kappa_1, \kappa_2 \in\Lambda_1 (definitions on the left, colored as their occurrences) against a seed (right). Each adopted match cuts at the root and holes of its occurrence but not inside it; the uncovered remainder (α,γ,φ4)(\alpha, \gamma, \varphi_4) is left to the cutting step.

The cutting step then solves

Def⁡∧Dom⁡∧Ord⁡∧¬Shape⁡∧Bnd⁡∧Block⁡\operatorname{Def} \land\operatorname{Dom} \land\operatorname{Ord} \land\neg\operatorname{Shape} \land\operatorname{Bnd} \land\operatorname{Block}

where Def⁡≜Def⁡1∧Def⁡2\operatorname{Def} \triangleq\operatorname{Def}^{1} \land\operatorname{Def}^{2}, and likewise for the other families. The cut variables fixed by matching are frozen, so the solver chooses cuts only in the unmatched remainder of ψ\psi, which keeps the search of Algorithm 1 tractable. Within this space, Def, Dom, Ord, and Bnd describe the two cuttings, ¬\negShape requires their fragment trees to differ in shape, and Block rules out the extensions already tried: since ψ\psi, L1L_1, and L2L_2 are fixed across the calls of one loop, an extension is determined by its pair of cut sets, so, writing (C1δ,C2δ)(C_1^\delta,C_2^\delta) for the cut sets of an extension δ∈B\delta\in B,

Block⁡≜⋀δ∈B¬⋀i∈{1,2}(⋀π∈Ciδcπi∧⋀π∉Ciδ¬cπi)\operatorname{Block} \triangleq\bigwedge_{\delta\in B} \neg\bigwedge_{i \in\{1,2\}} \left(\bigwedge_{\pi\in C_i^\delta} c^i_\pi\land\bigwedge_{\pi\notin C_i^\delta} \neg c^i_\pi\right)

A satisfying assignment of the query yields the extension directly: its cut variables give the two cut sets, fragments that are definitions of existing constructs reuse them, and every other fragment becomes a fresh construct of ΔL1\Delta L_1 or ΔL2\Delta L_2. If the query is unsatisfiable, Cut returns none.

FindIso⁡(Ψ′,L1,L2)\operatorname{FindIso}(\Psi', L_1, L_2) uses the same ingredients in the opposite direction: for each seed ψ′∈Ψ′\psi' \in\Psi', it computes the matches of the constructs of L1L_1 and L2L_2 in ψ′\psi' and asks whether some pair of sugarings has the same shape.

A sugaring of ψ′\psi' in LiL_i is a tiling of ψ′\psi' by occurrences of constructs of LiL_i. We introduce an adoption variable mα,πim^i_{\alpha,\pi} for every match and require the adopted matches to commit their cut variables and, together, to cover ψ′\psi':

Tile⁡i≜⋀α,π(mα,πi→match⁡α,πi)∧⋀σ⋁(α,π)∋σmα,πi\operatorname{Tile}^{i} \triangleq\bigwedge_{\alpha,\pi} \left(m^{i}_{\alpha,\pi} \to\operatorname{match}^{i}_{\alpha,\pi}\right) \land\bigwedge_{\sigma} \bigvee_{(\alpha,\pi)\ni\sigma} m^{i}_{\alpha,\pi}

where (α,π)∋σ(\alpha,\pi)\ni\sigma means that σ\sigma is a non-hole position of the occurrence of DαD_\alpha at π\pi. Coverage ensures that every cut stems from a match: since match formulas keep interiors uncut, a cut position can be covered only as the root of an adopted occurrence.

For each ψ′∈Ψ′\psi' \in\Psi', FindIso then checks

Tile⁡1∧Tile⁡2∧Def⁡∧Dom⁡∧Ord⁡∧Shape⁡∧Bnd⁡,\operatorname{Tile}^{1} \land\operatorname{Tile}^{2} \land\operatorname{Def} \land\operatorname{Dom} \land\operatorname{Ord} \land\operatorname{Shape} \land\operatorname{Bnd},

now asserting Shape positively. The matches adopted in a satisfying assignment form same-shaped sugarings χ1∈Sug⁡L1(ψ′)\chi_1 \in\operatorname{Sug}_{L_1}(\psi') and χ2∈Sug⁡L2(ψ′)\chi_2 \in\operatorname{Sug}_{L_2}(\psi'), giving the witness (ψ′,χ1,χ2)(\psi', \chi_1, \chi_2); if the query is unsatisfiable for every ψ′∈Ψ′\psi' \in\Psi', FindIso returns none.

Evaluation

Our experiments address the following research questions:

RQ1: How effective are contrapuntal languages at validating autoformalized specifications compared with baselines?

RQ2: (Ablation) How does contrapuntality affect the validation performance?

RQ3: Do contrapuntal languages help mitigate correlated errors?

RQ4: What is the token cost of contrapuntal languages in comparison with baselines?

RQ5: What are the causes of failures of contrapuntal languages?

Datasets. We evaluate on two programming benchmarks. The first is HumanEval+ (HEP) [21], whose tasks provide a natural-language description, a Python signature, a reference implementation, and tests. Although LLMs solve most HumanEval+ tasks, prior studies show that generating behaviorally correct specifications for HumanEval remains challenging even when expressed as Python postconditions and contracts [8, 30]. Our results show that this challenge persists when formalizing these tasks in SMT-LIB: even with reasoning enabled, Qwen3.6-Flash achieves an average pass@30 below 50%. For testing, we use HumanEval+-mini [21], which EvalPlus derives from the full suite by a greedy set cover that preserves branch coverage, mutant killing, and the detection of incorrect LLM-generated programs. It is about 47× smaller with similar testing effectiveness, which substantially reduces the cost of SMT queries.

The second is LiveCodeBench (LCB) [12], whose competitive programming problems from AtCoder and LeetCode are substantially harder to formalize. Applying the same test-suite reduction, we construct LiveCodeBench-mini: 727 of the original 7,000 tests across 175 tasks (463 public and 264 private), which still exercise all 6,340 branch arcs covered by the validated reference implementations and detect all 2,587 functionally exposed mutants considered during test selection.

Models. We evaluate using three LLM settings. GPT-5.4 mini is a compact proprietary OpenAI model with strong coding, reasoning, and tool-use capabilities. Qwen3.6-Flash is a fast-serving model in Qwen family, which includes open-weight releases and emphasizes multilingual coding. This model supports both thinking mode enabled and thinking mode disabled. We conducted experiments under these two modes, respectively.

Methods. For each task, we prompt the LLM with the task description, function signature, and types to generate an SMT-LIB v2 specification. It declares constants for the arguments and return values and contains two named assertions: pre_condition, for valid inputs, and post_condition, for the input–output relation. Since we focus on validating autoformalized specifications; deciding which candidates to accept when no external correctness oracle is available, we therefore compare three such strategies using the same sampling budget of 30 LLM-generated responses per task, and include direct generation as a reference to assess the effect of validation.

Direct generation keeps all n=30n = 30 samples that pass basic validity checks, i.e., follow the pre-/postcondition structure and parse in Z3 (We discuss the choice of nn in supplementary materials).

Plurality voting follows the Symbolic Equivalence strategy [19], clusters these specifications by pairwise SMT equivalence and selects the largest class.

Round-trip veri. follows the round-trip verification strategy [1], translating each of n=10n = 10 valid seeds into natural language and back into SMT-LIB. It retains only seeds proven SMT-equivalent to their regenerated counterparts, which serve solely as verification artifacts.

Contrapuntal langs. synthesizes a pair of contrapuntal languages from n=10n = 10 valid seeds and generates m=10m = 10 specifications in each language; a candidate is kept if it passes the validity checks, uses the constructs of its language, and is proven equivalent to a candidate from the other language.

Mutant generation. To assess soundness, we need incorrect programs, called mutants, whose outputs a sound specification must reject. Since HumanEval+ provides no incorrect programs, we prompt GPT-5.5 with the canonical solution to produce distinct single-bug variants, targeting five per task; for LiveCodeBench, we combine real wrong-answer submissions with at least five GPT-5.5 variants of a validated correct submission. We discard candidates that are syntactically invalid, lack the required entry point, or duplicate others, and run the rest on the benchmark tests. A mutant yields a negative example only when it returns a value different from the reference output; exceptions and resource failures yield no input–output pair to check against a specification and are ignored. This gives 779 mutants for HumanEval+ (161 tasks, 4.84 per task) and 2,587 for LiveCodeBench (175 tasks, 14.78 per task: 1,618 real submissions and 969 generated variants).

Evaluation Method. Neither benchmark provides reference formal specifications, so, following prior behavioral evaluations [8, 29, 30], we evaluate specifications on input–output pairs: positive tests from reference executions and negative tests from mutant outputs, all with inputs valid for their tasks. For each pair, Z3 checks whether the specification’s pre- and postconditions, with their variables bound to the pair, are satisfiable, that is, whether the specification admits the pair. A positive test passes if its pair is admitted; rejecting it, including through the precondition, is a completeness failure. A negative test kills its mutant if the pair is rejected while the input satisfies the precondition, so that an overly restrictive precondition does not count as a kill. A mutant is killed if any of its negative tests kills it, and a specification is sound if it kills every mutant.

Since the solver may time out, we use a threshold τ∈[0,1]\tau\in[0, 1]: a specification is τ\tau-complete if no positive test fails, at least a fraction τ\tau pass, and the rest return UNKNOWN. An UNKNOWN result counts as neither a pass nor a kill; errored or unsupported cases are excluded.

RQ1: Effectiveness of Specification Validation

Reporting either completeness or soundness alone for specifications accepted under different methods can be misleading, since a specification may trivially favor completeness by accepting all behaviors, or favor soundness by rejecting all behaviors. We therefore report two joint metrics: MKR|C denotes the percentage of evaluated mutants killed by accepted specifications that are τ\tau-complete; CR denotes the empirical correctness rate: the percentage of accepted specifications that are both τ\tau-complete and sound (able to kill all evaluated mutants). Their task-level macro-averages are denoted by Avg. MKR|C and Avg. CR, respectively. The discussion below focuses on τ=0.8\tau= 0.8 and τ=1.0\tau= 1.0; in our supplementary materials, we present a sensitivity analysis across the full range τ∈[0,1]\tau\in[0, 1].

As shown in Table 1, contrapuntal languages achieve significantly higher Avg. CR than both round-trip verification and plurality voting on average under a paired task-level bootstrap (100,000 resamples). The gains over round-trip verification are 22.13 percentage points at τ=0.8\tau= 0.8 (approximate 95% simultaneous confidence interval: [6.67, 37.60]) and 20.76 points at τ=1.0\tau= 1.0 ([5.27, 36.24]); the corresponding gains over plurality voting are 22.79 points ([7.57, 38.00]) and 22.10 points ([6.87, 37.34]), respectively. The other metrics in Table 1 also show improvements: averaged across the three model configurations, the relative gains over plurality voting in MKR|C, Avg. MKR|C, and CR are 5.8–6.3%, 13.6–14.4%, and 16.2–17.0% on HEP, and 29.5–32.2%, 84.1–92.5%, and 40.1–42.9% on LCB, respectively. Contrapuntal languages also outperform round-trip verification in these metrics across all reported settings except CR (τ=1.0\tau= 1.0) for Qwen3.6-Flash with thinking on HEP.

BMModelMethodMKR|C (%) τ=0.8\tau=0.8MKR|C (%) τ=1.0\tau=1.0CR (%) τ=0.8\tau=0.8CR (%) τ=1.0\tau=1.0Avg. MKR|C (%) τ=0.8\tau=0.8Avg. MKR|C (%) τ=1.0\tau=1.0Avg. CR (%) τ=0.8\tau=0.8Avg. CR (%) τ=1.0\tau=1.0
HEPGPT-5.4 miniDirect generation79.5277.7521.4118.3059.1755.6219.6616.70
HEPGPT-5.4 miniRound-trip Veri.84.3582.6728.3023.7873.8071.2421.6218.72
HEPGPT-5.4 miniPlurality voting92.2691.2541.6935.5981.2280.4423.8121.24
HEPGPT-5.4 miniContrapuntal langs.99.0498.8652.3043.5498.8998.6047.5237.59
HEPQwen3.6-Flash thinking=offDirect generation85.9585.9337.9134.9471.3569.7824.4322.67
HEPQwen3.6-Flash thinking=offRound-trip Veri.88.3989.7259.7853.6384.6485.1843.0639.62
HEPQwen3.6-Flash thinking=offPlurality voting91.5592.5262.7058.8183.1284.6737.3135.07
HEPQwen3.6-Flash thinking=offContrapuntal langs.98.0498.0468.4768.4790.6790.6750.0050.00
HEPQwen3.6-Flash thinking=onDirect generation87.7686.6548.9941.7671.8264.3937.3730.85
HEPQwen3.6-Flash thinking=onRound-trip Veri.94.6494.2776.0370.6284.8683.8759.4854.06
HEPQwen3.6-Flash thinking=onPlurality voting94.9894.5869.8562.6787.3585.4351.1442.94
HEPQwen3.6-Flash thinking=onContrapuntal langs.97.8699.0181.2568.7596.0696.9576.1864.91
LCBGPT-5.4 miniDirect generation43.4942.829.038.5529.9126.727.566.98
LCBGPT-5.4 miniRound-trip Veri.40.0142.3311.1110.8428.5629.229.168.84
LCBGPT-5.4 miniPlurality voting56.8255.5827.6526.3633.8031.3911.029.84
LCBGPT-5.4 miniContrapuntal langs.88.7088.7050.4350.4376.8176.8138.1038.10
LCBQwen3.6-Flash thinking=offDirect generation63.7068.7021.4119.5435.7037.199.928.64
LCBQwen3.6-Flash thinking=offRound-trip Veri.79.1388.1133.3332.5657.1165.4220.3717.99
LCBQwen3.6-Flash thinking=offPlurality voting78.3783.9244.4943.7050.9760.0023.8121.43
LCBQwen3.6-Flash thinking=offContrapuntal langs.100.0100.055.5655.56100.0100.042.8642.86
LCBQwen3.6-Flash thinking=onDirect generation78.5180.9332.0628.1248.5047.9115.0312.47
LCBQwen3.6-Flash thinking=onRound-trip Veri.72.7575.0742.6841.0654.4158.6830.6528.61
LCBQwen3.6-Flash thinking=onPlurality voting88.5991.2360.8357.9164.9270.8833.3329.24
LCBQwen3.6-Flash thinking=onContrapuntal langs.100.0100.068.6763.86100.0100.062.5058.93

Table 1. Validation results for accepted specifications. Higher is better; bold marks the best result for each metric and threshold within each benchmark (BM) and model configuration.

The results above cover only tasks with an accepted specification. We therefore also report task coverage, the fraction of tasks with at least one accepted specification. For reference, we also report seed availability, the fraction of tasks whose initial seed pool contains at least one complete and sound specification. This is an upper bound on the fraction of tasks any method can accept correctly. Seed availability is 39.17% on HEP and 12.97% on LCB. Our method covers 29.81% and 8.76%, round-trip validation 64.60% and 52.00%, and plurality voting 73.27% and 48.77%. Both baselines exceed seed availability by a wide margin, so they must accept incorrect specifications for many tasks. Our coverage is lower than theirs, but it is the closest to seed availability on both benchmarks.

Overall, specifications accepted by contrapuntal languages kill the most mutants and are most often correct. Our method rejects more tasks than the baselines, but its coverage is the closest to the upper bound on correct acceptance. This conservatism matters for verification: an incorrect specification can let a buggy program pass verification, whereas a rejected task is simply flagged as unresolved. Contrapuntal languages thus offer the best balance between reliability and coverage.

RQ2 (Ablation): Impact of Contrapuntality

To assess the contribution of contrapuntality to the effectiveness of our method, we compare our approach with a relaxed version. This variant randomly partitions the sampled seed formalizations into two disjoint subsets of equal size and synthesizes one language independently from each subset, breaking contrapuntality guarantee between two languages. Relative to Algorithm 1, it removes the requirement that both languages express every seed, the different-shape constraint in Cut, and the FindIso check and its associated rejection of candidate extensions. We retain the same subsequent formalization and equivalence checking procedure.

Compared with our full approach, the relaxed version yields average relative decreases of 15% in CR and 34.5% in Avg. CR, which support the contribution of contrapuntality: constructing two different languages alone does not provide the same validation reliability as contrapuntal languages.

RQ3: Mitigating Correlated Errors

Contrapuntal languages are intended to decorrelate errors: two incorrect formalizations in different languages should be less likely to be incorrect in the same way. We test this by comparing single-language pairs (two specifications generated directly in SMT-LIB) with cross-language pairs (one specification from each contrapuntal language). For each pair type, we measure error coincidence (EC): among pairs of incorrect specifications, the fraction that are semantically equivalent.

For each task and model setting, we consider the valid specifications among the 30 direct-generation samples and the valid candidates generated in each contrapuntal language before equivalence-based acceptance. We group candidates into solver-confirmed equivalence classes using the same SMT-based equivalence-checking procedure as in § 6.1. A class is labeled incorrect if a member rejects a reference input–output pair or an evaluated mutant is confirmed to survive its checks. Otherwise, it is labeled correct if a member meets the 0.8-completeness and soundness criteria used in RQ1. Classes without sufficient evidence for either label are excluded.

For the single-language comparison, we form unordered pairs of distinct SMT-LIB candidates; for the cross language comparison, we pair one candidate from each contrapuntal language. Pairs with unresolved equivalence checks are excluded from both the numerator and denominator. For task tt and pair type p∈{single,cross}p \in\{\text{single}, \text{cross}\}, let DtpD_t^p be the number of remaining pairs, WtpW_t^p the number in which both candidates are incorrect, and EtpE_t^p the number in which both belong to the same incorrect equivalence class. T are the tasks with Dtp>0D_t^p > 0 for both pp. We normalize pair counts within each task and then aggregate the resulting proportions across tasks to compute EC:

wtp=WtpDtp,etp=EtpDtp,ECp=∑t∈Tetp∑t∈Twtp.w_t^p = \frac{W_t^p}{D_t^p}, \qquad e_t^p = \frac{E_t^p}{D_t^p}, \qquad\mathrm{EC}^p = \frac{\sum_{t \in T} e_t^p}{\sum_{t \in T} w_t^p}.

Averaging EC equally across the three model settings, the rate decreases from 25.23% for single-language pairs to 21.88% for cross-language pairs on HumanEval+, and from 10.07% to 5.72% on LiveCodeBench. Thus, when both candidates are incorrect, cross-language pairs agree on the same incorrect semantics less frequently on average. These results provide empirical support for using contrapuntal representations to decorrelate model errors for more effective validation of autoformalized specifications, beyond enforcing differences in AST shape.

RQ4: Token Usage

Table 2 reports the mean input, output, and total token usage per task under the same 30-response sampling budget used in RQ1.

ModelMethodHumanEval+ InputHumanEval+ OutputHumanEval+ TotalLiveCodeBench InputLiveCodeBench OutputLiveCodeBench Total
GPT-5.4 miniRound-trip Veri.24,1034,56028,66427,4906,07933,570
GPT-5.4 miniPlurality voting32,1466,50338,64939,8268,83248,659
GPT-5.4 miniContrapuntal langs.45,8404,18050,02076,7586,34583,102
Qwen3.6-Flash thinking=offRound-trip Veri.15,3968,14923,54516,65820,07036,728
Qwen3.6-Flash thinking=offPlurality voting32,14622,26254,40839,82659,95199,777
Qwen3.6-Flash thinking=offContrapuntal langs.53,37512,51465,88966,12432,84898,972
Qwen3.6-Flash thinking=onRound-trip Veri.15,2033,51318,71618,94915,38334,331
Qwen3.6-Flash thinking=onPlurality voting19,9686,05026,01939,82632,45472,280
Qwen3.6-Flash thinking=onContrapuntal langs.46,2114,08050,29175,31922,93198,250

Table 2. Token usage per task on HumanEval+ and LiveCodeBench.

All three methods consume more tokens on LCB than on HEP, consistent with its more complex task descriptions and specifications. Round-trip verification consumes fewer tokens than plurality voting because of shorter prompts and condensed task descriptions. Compared with plurality voting, contrapuntal languages consume more input tokens because their prompts include the synthesized language constructs and instructions for using them, also yielding more compact outputs. Their more compact outputs generally do not offset the larger input completely.

On average, contrapuntal languages consume 1.4×1.4 \times as many tokens as plurality voting and 2.5×2.5 \times as many as round-trip verification, using the additional context to induce structurally different representations. This trade-off yields the higher validation performance demonstrated in § 6.1 by addressing correlated errors that additional sampling alone does not remove.

RQ5: Analysis of Failure

Across the two benchmarks and three model settings, contrapuntal languages’ false-positive failures accounted for 38.9% of all 216 failures. Although we introduce representational diversity between contrapuntal languages, the two languages still share the same seed formalizations and therefore cannot eliminate correlated errors completely. After investigation, most false-positive cases lacked any 0.8-complete and sound specification among seed formalizations, and among tasks with at least two valid seeds, these cases exhibited approximately 15% lower normalized equivalence-class entropy than other tasks that lacked such a seed specification, suggesting a more concentrated distribution of incorrect interpretations that may be more difficult to decorrelate even when formalizations are required to use structurally different representations.

False-negative failures accounted for the remaining 61.1%. These comprised cases with no valid specifications under one or both languages (20.8%), cases with valid specifications but no matching pairs between the two languages (31.5%), and failures to synthesize languages satisfying contrapuntality (8.8%). Invalid specifications primarily resulted from SMT-LIB syntax, type, or symbol errors; failure to use constructs from the synthesized language; and empty outputs or malformed specification structures. The no-matching-pair cases comprised two groups: those containing at least one candidate pair whose equivalence remained unresolved by the solver mostly due to timeout, accounting for 17.6%, and those in which all candidate pairs were proven non-equivalent, accounting for 13.9%.

Case Study: Ambiguous Task Descriptions

While manually examining changes in candidate distributions across representations, we encountered HumanEval/154, where a reference-consistent interpretation frequent in direct formalization lost its dominance under one of the two languages. Both language-conditioned distributions nevertheless remained concentrated. Inspecting their conflicting dominant specifications revealed an unresolved boundary case in the task description. We examine this case to show how cross-language disagreement can make different plausible interpretations apparent even when each language induces strong agreement. The results below use Qwen3.6-Flash in thinking mode.

HumanEval/154 asks whether a word or any of its rotations is a substring of another, without explicitly addressing an empty second word. Of 30 direct formalizations, 22 were valid and formed semantic classes of sizes [13,2,1×7][13, 2, 1 \times7]. As shown in Figure 7, the largest class, s1s_1, required True for a="abc" and b="", matching the benchmark reference. The class of size two, s2s_2, required False. Plurality voting selected specifications representing s1s_1, while the plausible empty-word interpretation appeared in only a small minority of the direct candidates.

Cross-language disagreement diagram for HumanEval/154

Figure 7. Cross-language disagreement exposes different plausible interpretations of HumanEval/154. For an empty second word, s1s_1 requires True and s2s_2 requires False; concentrated distributions under the two languages favor different interpretations.

Under the contrapuntal languages, the class-size distributions were [8, 1, 1] in L1\mathcal{L}_1 and [10] in L2\mathcal{L}_2. The previously minor interpretation s2s_2 now accounted for eight of ten candidates in L1\mathcal{L}_1, whereas all ten candidates in L2\mathcal{L}_2 represented s1s_1. Each distribution was more concentrated around its dominant interpretation, but the two dominant classes were not equivalent. Stronger within-language agreement therefore did not settle the empty-word convention; comparing the languages brought another plausible interpretation into focus. This diagnosis is consistent with the SpecFix analysis [14], in which HumanEval/154 is among the 20 tasks identified as ambiguous by all models in their experiment. The cross-language contrast thus identifies a specific decision for the user.

This case study suggests a complementary role for representational diversity: beyond supporting specification validation, it may help expose ambiguity by making different plausible interpretations explicit. Future work could investigate when such disagreement is indicative of ambiguity and how distinguishing behaviors can be used to formulate targeted clarification questions for users.

Threats to Validity

Behavioral evaluation. Our completeness and soundness judgments are relative to the tested behaviors, not exhaustive semantic correctness. In particular, killing a mutant establishes only that at least one observed incorrect output is rejected. We apply the same tests and criteria to all methods, providing a consistent basis for comparison within the intended input domain.

Test-suite and mutant selection. Test reduction may omit inputs that distinguish specifications. Our reduction criteria preserve complementary indicators of test effectiveness, including branch coverage and mutant detection, but these concern the programs used in reduction rather than exhaustive coverage of specification errors. Mutant selection also limits the faults represented; combining real wrong-answer submissions with LLM-generated variants on LiveCodeBench broadens these sources beyond generated mutations alone.

Generalizability and interpretation of intent. Our evaluation covers two benchmarks of different complexity and three configurations spanning two model families and both thinking and non-thinking modes. Generalization to other settings and specification formalisms requires further evaluation. Reference outputs provide one interpretation of benchmark intent, but ambiguous descriptions may admit others. Our case study shows that cross-language disagreement can surface plausible alternatives, not determine which matches the user’s intent. Resolving such ambiguity requires confirmation from the requirement author or user, particularly for real-world requirements that may exhibit more substantial and diverse ambiguities.

Related Work

LLM-based autoformalization and specification generation. LLM-based autoformalization has been studied for mathematical statements and software specifications across theorem-prover languages, regular expressions, first-order and temporal logic [9, 34]. In software engineering, recent work generates postconditions and richer contracts, often using program analysis or verification feedback [8, 22, 30, 32]. These works generate specifications in a given target formalism. However, generated specifications are themselves untrusted, and validating whether they capture the intended behavior without an external oracle remains challenging [17]. We study oracle-free validation of autoformalized specifications, using two task-specific formal representations as validation views.

Consistency-based validation and candidate selection. Li et al. [19] propose Symbolic Equivalence (SymEq), which scores candidates by equivalence-class size, and Semantic Consistency (SemCo), which scores back-translations by embedding similarity. We adapt SymEq into our plurality voting baseline by accepting specifications in the largest SMT-checked equivalence class. This provides a direct class-based acceptance rule, whereas using SemCo for acceptance would require an additional policy beyond its candidate-ranking scores. Amrollahi et al. [1] validate formalizations by checking equivalence after back-translation and re-formalization, and use verification failures to guide subsequent repair. We adopt their complete round-trip verification procedure as our baseline. Liu et al. [20] query users to disambiguate candidate assertions when needed, while Mendoza et al. [26] use user judgments on distinguishing traces; these oracle-assisted workflows fall outside our oracle-free comparison. Semantic triangulation mitigates correlated errors through consistency across original and transformed programming problems [5], but targets code selection; adapting it would require specification-level transformations and consistency relations. We instead preserve task intent while varying its formal representation, validating agreement across two synthesized, structurally distinct languages.

Decomposition, reuse, and intermediate representations. Several systems improve specification synthesis through decomposition or fragment reuse. Clause2Inv reuses clauses from candidate invariants [3], while nl2spec and SynthTL expose structured sub-translations for correction or localized validation [4, 25]. Req2TL introduces a hierarchical intermediate representation [23], and KELPS studies aligned formalization across theorem-prover languages [36]. We likewise exploit intermediate structure, but synthesize two deliberately different decompositions of the same seeds, combining common seed coverage with structural difference to obtain validation evidence. We do not use these systems as baselines because they address generation, repair, or logic-specific translation rather than the validation setting studied here.

Evaluation of generated specifications. When a reference formalization is available, candidates can be evaluated against it; for example, BEq+ establishes bidirectional implication using deterministic Lean proofs [28]. Without references, prior work relies on behavioral evidence: Endres et al. [8] evaluate postconditions using trusted tests and buggy mutants, while Lahiri [16] uses symbolic testing with mutated outputs. FormalBench combines deductive verification with mutation analysis [18], while Coins evaluates Rocq specifications on positive and mutation-derived negative cases through concrete proof obligations [35]. Without reference formal specifications, we follow this test-based evaluation approach, using positive tests, negative tests, and mutant killing as behavioral approximations of specification quality.

SMT-based synthesis and repair. Constraint solving has long been used to synthesize programs and repairs. Oracle-guided component-based synthesis encodes the composition of program components as SMT constraints [13], while DirectFix builds on component-based synthesis and MaxSAT to search for simple program repairs [24]. Our setting changes the object being synthesized: we use SMT to construct formal languages rather than programs or patches. The encoding searches over cuts of seed formulas and constrains the resulting fragment-tree shapes to obtain an effectively contrapuntal language pair.

Conclusion

We presented an oracle-free approach to validating autoformalized specifications through contrapuntal languages, pairs of task-specific formal languages, each designed to express the intended specification, yet admitting no structure-preserving translation between them. By guiding LLM to formalize the same intent along different representational paths, our approach uses solver-checked agreement as evidence of correctness. Experiments on HumanEval+ and LiveCodeBench show that our approach improves the proportion of accepted specifications that are complete and sound over the strongest baseline on average, supporting deliberately structured representational diversity as a means of making agreement more informative for specification validation.

Acknowledgments

This work was supported by the National Natural Science Foundation of China under Grant No. W2632069. We thank Haotian Xu, Sijie Liang, and Dimitrios Stamatios Bouras for their feedback.

Example of Syntactic Sugar

This appendix illustrates the notions of § 3 on Formula I of Figure 1. Writing dd and ℓ\ell for descend_at and largest, the formula is

ψI=r÷−1∨(d(r,a)∧ℓ(r,a)).\psi_{\mathrm{I}} = r \div-1 \lor\left(d(r,a) \land\ell(r,a)\right).

Trees and positions. ψI\psi_{\mathrm{I}} is a tree with eleven nodes, shown with its positions in Figure 8 (middle right). For example, ψI(ε)=∨\psi_{\mathrm{I}(\varepsilon)} = \lor is the label of the root, ψI∣2=d(r,a)∧ℓ(r,a)\psi_{\mathrm{I}}|_{2} = d(r,a) \land\ell(r,a) is the subtree at position 2, and ψI(21)=d\psi_{\mathrm{I}}(21) = d; moreover, 2⊏212 \mathbin{\sqsubset} 21, since position 21 lies in the subtree at position 2.

Syntactic sugar on Formula I of Figure 1

Figure 8. Syntactic sugar on Formula I of Figure 1, with dd and ℓ\ell abbreviating descend_at and largest. Top: the definitions of the five constructs of L\mathcal{L}, with their non-hole parts colored. Middle and bottom: the two sugarings χ1\chi_{1} and χ2\chi_{2} of ψI\psi_{\mathrm{I}} (left) and their common desugaring ψI\psi_{\mathrm{I}} (right), carved into the fragments covered by their constructs (same colors); double strokes mark the cuts between fragments, and gray labels give positions.

A sugared language. Let L\mathcal{L} be the sugared language with the five constructs whose definitions are shown at the top of Figure 8:

Dκ∨=r÷−1∨□1,Dκd∧=d(r,a)∧□1,Dκ∧=□1∧□2,Dκd=d(r,a),Dκℓ=ℓ(r,a).D_{\kappa_{\lor}} = r \div-1 \lor\square_{1}, \qquad D_{\kappa_{d\land}} = d(r,a) \land\square_{1}, \qquad D_{\kappa_{\land}} = \square_{1} \land\square_{2}, \qquad D_{\kappa_{d}} = d(r,a), \qquad D_{\kappa_{\ell}} = \ell(r,a).

The arity of a construct is its number of holes: κ∧\kappa_{\land} is binary, κ∨\kappa_{\lor} and κd∧\kappa_{d\land} are unary, and κd\kappa_{d} and κℓ\kappa_{\ell} are constants. As Definition 3.2 requires, every definition uses each of its holes and contains at least one other node.

Desugaring. The L\mathcal{L}-formula χ1=κ∨(κd∧(κℓ))\chi_1 = \kappa_{\lor}(\kappa_{d\land}(\kappa_{\ell})) desugars by replacing each construct with its definition, from the leaves up:

D(χ1)=Dκ∨[Dκd∧[Dκℓ]]]=Dκ∨[Dκd∧[ℓ(r,a)]]=Dκ∨[d(r,a)∧ℓ(r,a)]=ψI.D(\chi_1) = D_{\kappa_{\lor}}[D_{\kappa_{d\land}}[D_{\kappa_{\ell}]]] = D_{\kappa_{\lor}}[D_{\kappa_{d\land}}[\ell(r,a)]] = D_{\kappa_{\lor}}[d(r,a) \land\ell(r,a)] = \psi_I.}

Hence χ1\chi_1 desugars to ψI\psi_I, and χ1≡ψI\chi_1 \equiv\psi_I. Likewise, χ2=κ∨(κ∧(κd,κℓ))\chi_2 = \kappa_{\lor}(\kappa_{\land}(\kappa_d,\kappa_{\ell})) desugars to ψI\psi_I.

Sugaring. In fact, Sug⁡L(ψI)={χ1,χ2}\operatorname{Sug}_{\mathcal{L}}(\psi_I) = \{\chi_1,\chi_2\}. The root of a sugaring must be a construct whose definition matches ψI\psi_I at its root, and only κ∨\kappa_{\lor} does; its hole then receives ψI∣2\psi_I|_2, which is covered either by κd∧\kappa_{d\land}, leaving ℓ(r,a)\ell(r,a) for κℓ\kappa_{\ell}, or by κ∧\kappa_{\land}, leaving d(r,a)d(r,a) and ℓ(r,a)\ell(r,a) for κd\kappa_d and κℓ\kappa_{\ell}. As Figure 8 shows, each sugaring carves ψI\psi_I into fragments: every construct of the sugaring covers one fragment, and every edge of the sugaring corresponds to a cut. The two sugarings have different shapes—three nodes versus four—which is what the non-isomorphism requirement of § 4 is about: a second language whose only sugaring of ψI\psi_I has four nodes cannot be related to χ1\chi_1 by a structure-preserving translation, but may be related to χ2\chi_2.

Proof of Theorem 5.2

Termination. A seed has finitely many positions, hence finitely many cut sets, so there are finitely many extensions for a seed ψ\psi over any given pair of languages. Within one invocation of Synth, the seed ψ\psi and the languages L1,L2\mathcal{L}_1,\mathcal{L}_2 are fixed, and every iteration of the loop either returns or adds to BB the extension δ\delta that Cut has just returned. By the contract of Cut, δ∉B\delta\notin B before this step, so BB grows strictly, and after finitely many iterations Cut returns none and the loop exits—provided that every recursive call terminates. Each recursive call receives the tail of SS, so the recursion depth is at most nn, and termination follows by induction on the length of SS.

Adequacy. Suppose that Synth returns a pair (L1∗,L2∗)(\mathcal{L}_1^*,\mathcal{L}_2^*). It is returned by the base case, reached through a chain of nn invocations, the kk-th of which integrates ψk\psi_k by an extension (ΔL1k,ΔL2k)(\Delta\mathcal{L}_1^k,\Delta\mathcal{L}_2^k) over (L1k−1,L2k−1)(\mathcal{L}_1^{k-1},\mathcal{L}_2^{k-1}) and passes Lik=Lik−1∪ΔLik\mathcal{L}_i^k = \mathcal{L}_i^{k-1} \cup\Delta\mathcal{L}_i^k to the next, with Li0=∅\mathcal{L}_i^0 = \varnothing and Lin=Li∗\mathcal{L}_i^n = \mathcal{L}_i^*. By the definition of an extension, the fragment tree of the ii-th cut set of ψk\psi_k is an Lik\mathcal{L}_i^k-formula χik\chi_i^k with D(χik)=ψkD(\chi_i^k) = \psi_k; since the cut set satisfies Bnd⁡i\operatorname{Bnd}_i, no cut separates a bound variable occurrence from its quantifier, so χik\chi_i^k desugars to ψk\psi_k. Since the added constructs are fresh, Lik⊆Li∗\mathcal{L}_i^k \subseteq\mathcal{L}_i^* and every construct of Lik\mathcal{L}_i^k has the same definition in Li∗\mathcal{L}_i^*; hence χik\chi_i^k is also an Li∗\mathcal{L}_i^*-formula that desugars to ψk\psi_k, and χik∈Sug⁡Li∗(ψk)\chi_i^k \in\operatorname{Sug}_{\mathcal{L}_i^*}(\psi_k). Clause (i) of Definition 4.3 thus holds for every seed.

Non-isomorphism. The nn-th invocation makes its recursive call only after FindIso(P,{ψn},L1∗,L2∗)(P,\{\psi_n\},\mathcal{L}_1^*,\mathcal{L}_2^*) has returned none, where P∪{ψn}=ΨP \cup\{\psi_n\} = \Psi. By the contract of FindIso, there is thus no seed ψ∈Ψ\psi\in\Psi with sugarings χ1∈Sug⁡L1∗(ψ)\chi_1 \in\operatorname{Sug}_{\mathcal{L}_1^*}(\psi) and χ2∈Sug⁡L2∗(ψ)\chi_2 \in\operatorname{Sug}_{\mathcal{L}_2^*}(\psi) of the same shape. A structure-preserving translation from χ1\chi_1 to χ2\chi_2 requires Pos⁡(χ1)=Pos⁡(χ2)\operatorname{Pos}(\chi_1) = \operatorname{Pos}(\chi_2), that is, the same shape; hence none exists, and clause (ii) of Definition 4.3 holds. □\square

Sample Size Setting

To choose a practical sampling budget, we examine how the empirical distribution over specification equivalence classes varies with sample size. For each task xx, we measure this distribution using semantic entropy:

HN(x)=−∑i=1KN(x)pilog⁡2pi,pi=∣Ci∣nok(x,N),(1)H_N(x) = -\sum_{i=1}^{K_N(x)} p_i \log_2 p_i,\qquad p_i = \frac{|C_i|}{n_{\mathrm{ok}}(x,N)}, \tag*{(1)}

where KN(x)K_N(x) denotes the number of specification equivalence classes formed by the successfully generated specifications among the first NN sampling attempts, CiC_i denotes the ii-th equivalence class, and nok(x,N)n_{\mathrm{ok}}(x,N) is the number of these successful generations. Failed generations are excluded without replacement. We vary NN from 5 to 50 in increments of 5, using prefixes of the same 50-sample sequence for each task, and report the arithmetic mean of task-level entropies across the 161 HumanEval+ tasks.

As shown in Figure 9, the mean entropy increases from 1.436 bits at N=5N = 5 to 2.839 bits at N=30N = 30, with progressively smaller gains as the sampling budget grows. Increasing NN further from 30 to 50 raises the mean entropy to 3.168 bits—an additional 0.329 bits, or 11.6%, despite a 66.7% increase in sampling budget. Although the entropy continues to increase, these diminishing returns suggest that larger sample sizes provide comparatively modest gains in measured semantic diversity. We therefore select N=30N = 30 as a practical trade-off between representing specification diversity and limiting sampling and equivalence-analysis costs.

Mean semantic entropy of specification equivalence-class distributions across 161 HumanEval+ tasks

Figure 9. Mean semantic entropy of specification equivalence-class distributions across 161 HumanEval+ tasks as a function of specification sample size. Each point averages task-level entropies in bits, computed from successful generations among the first NN sampling attempts.

Full threshold Results for RQ1

This section supplements RQ1 (§ 6.1) by examining whether the comparative advantage of contrapuntal languages depends on the completeness threshold. Figure 10 and Figure 11 extend the two joint metrics in Table 1 to the full range τ∈[0,1]\tau\in[0,1]. The step curves include every empirical threshold at which the set of τ\tau-complete specifications changes, with the same sample-selection/acceptance and averaging rules as in Table 1. Rows correspond to the three model settings. The first two columns report MKR|C and Avg. MKR|C, respectively; the last two report CR and Avg. CR.

Threshold sensitivity on HumanEval+

Figure 10. Threshold sensitivity on HumanEval+. Rows denote models; columns denote metrics. Markers show τ=0\tau= 0, 0.8, and 1; the vertical line marks 0.8.

Threshold sensitivity plots for six model–benchmark settings

Figure 11. Threshold sensitivity on LiveCodeBench, using the same layout and markers as Figure 10.

Contrapuntal languages achieve the highest task-level macro-averages, Avg.  MKR∣C\,\mathrm{MKR}\mathbin{|}\mathrm{C} and Avg. CR\mathrm{CR}, throughout τ∈[0,1]\tau\in[0,1] in all six model–benchmark settings. For each sample-level metric, they also lead throughout this range in five of the six settings. There are two exceptions on HumanEval+: with GPT-5.4 mini, plurality voting has a higher MKR∣C\mathrm{MKR}\mathbin{|}\mathrm{C} at some low thresholds below 0.2; with Qwen3.6-Flash in thinking mode, round-trip verification has a higher CR\mathrm{CR} at some high thresholds, including τ=1\tau= 1. These results support the overall performance advantage observed in RQ1 across a broad range of thresholds, particularly under task-level macro-averaging.

References

  1. [1]Daneshvar Amrollahi, Jerry Lopez, and Clark Barrett. 2026. Faithful Autoformalization via Roundtrip Verification and Repair. arXiv:2604.25031 [cs.CL] https://arxiv.org/abs/2604.25031
  2. [2]Clark Barrett, Aaron Stump, Cesare Tinelli, et al. 2010. The smt-lib standard: Version 2.0. In Proceedings of the 8th international workshop on satisfiability modulo theories (Edinburgh, UK), Vol. 13. 14.
  3. [3]Weining Cao, Guanyang Wu, Tangzhi Xu, Yuan Yao, Hengfeng Wei, Taolue Chen, and Xiaoxing Ma. 2025. Clause2Inv: A Generate-Combine-Check Framework for Loop Invariant Inference. Proceedings of the ACM on Software Engineering 2, ISSTA (2025), 1009–1030.DOI
  4. [4]Matthias Costler, Christopher Hahn, Daniel Mendoza, Frederik Schmitt, and Caroline Trippel. 2023. nl2spec: Interactively Translating Unstructured Natural Language to Temporal Logics with Large Language Models. In Computer Aided Verification: 35th International Conference, CAV 2023, Paris, France, July 17–22, 2023, Proceedings, Part II (Paris, France). Springer-Verlag, Berlin, Heidelberg, 383–396. doi:10.1007/978-3-031-87703-7_18
  5. [5]Yihan Dai, Sijie Liang, Haotian Xu, Peichu Xie, and Sergey Mechtav. 2026. Reducing Hallucinations in LLM-Generated Code via Semantic Triangulation. arXiv:2511.12288 [cs.SE] https://arxiv.org/abs/2511.12288
  6. [6]Leonardo de Moura and Nikolaj Bjørner. 2008. Z3: An Efficient SMT Solver. In Tools and Algorithms for the Construction and Analysis of Systems (TACAS) (Lecture Notes in Computer Science, Vol. 4963). Springer, 337–340. doi:10.1007/978-3-540-78800-3_24DOI
  7. [7]Kacper Duma, Patryk Wróblewski, Jagoda Bobińska, Julia Winiarska, and Piotr Pryzmus. 2026. These Aren’t the Reviews You’re Looking For: How Humans Review AI-Generated Pull Requests. In Proceedings of the International Conference on Evaluation and Assessment in Software Engineering (EASE 2026). arXiv:2605.02273
  8. [8]Madeline Endres, Sarah Fakhoury, Saikat Chakraborty, and Shuvendu K. Lahiri. 2024. Can Large Language Models Transform Natural Language Intent into Formal Method Postconditions? arXiv:2310.01831 [cs.SE] https://arxiv.org/abs/2310.01831
  9. [9]Christopher Hahn, Frederik Schmitt, Julia J. Tillman, Niklas Metzger, Julian Siber, and Bernd Finkbeiner. 2022. Formal Specifications from Natural Language. arXiv:2206.01962 [cs.SE] https://arxiv.org/abs/2206.01962
  10. [10]Lars Kai Hansen and Peter Salamon. 1990. Neural network ensembles. IEEE Transactions on Pattern Analysis and Machine Intelligence 12, 10 (1990), 993–1001. doi:10.1109/34.58871DOI
  11. [11]Qinheping Hu, Jason Breck, John Cyphert, Loris D’Antoni, and Thomas Reps. 2019. Proving unrealizability for syntax-guided synthesis. In International Conference on Computer Aided Verification. Springer, 335–352.arxiv.org/abs/1905.05800
  12. [12]Naman Jain, Alex Gu, Wen-ding Li, Fanjia Yan, Tianjun Zhang, Sida Wang, Armando Solar-Lezama, Koushik Sen, and Ion Stoica. 2025. Livecodebench: Holistic and contamination free evaluation of large language models for code. In International Conference on Learning Representations, Vol. 2025. 58791–58831.arxiv.org/abs/2403.07974
  13. [13]Sumit Jha, Sumit Gulwani, Sanjit A. Seshia, and Ashish Tiwari. 2010. Oracle-guided component-based program synthesis. In Proceedings of the 32nd ACM/IEEE International Conference on Software Engineering - Volume 1 (Cape Town, South Africa) (ICSE ’10). Association for Computing Machinery, New York, NY, USA, 215–224. doi:10.1145/1806799.1806833DOI
  14. [14]Haoxiang Jang, Robbie Morris, He Ye, Federica Sarro, and Sergey Mechtaev. 2025. Automated Repair of Ambiguous Problem Descriptions for LLM-Based Code Generation. In 2025 40th IEEE/ACM International Conference on Automated Software Engineering (ASE). 367–379. doi:10.1109/ASE63991.2025.0020038
  15. [15]Elliot Kim, Avi Garg, Kenny Peng, and Nikhil Garg. 2025. Correlated errors in large language models. arXiv preprint arXiv:2506.07962 (2025).arxiv.org/abs/2506.07962
  16. [16]Shuvendu K. Lahiri. 2024. Evaluating LLM-driven User-Intent Formalization for Verification-Aware Languages. In 2024 Formal Methods in Computer-Aided Design (FMCAD). 142–147. doi:10.3427/2024/isbn.978-3-85448-065-5_19DOI
  17. [17]Shuvendu K Lahiri. 2026. Intent formalization: A grand challenge for reliable coding in the age of AI agents. arXiv preprint arXiv:2603.17150 (2026).arxiv.org/abs/2603.17150
  18. [18]Thanh Le-Cong, Bach Le, and Toby Murray. 2025. Can LLMs Reason About Program Semantics? A Comprehensive Evaluation of LLMs on Formal Specification Inference. In Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), Wanxiang Che, Joyce Nabende, Ekaterina Shutova, and Mohammad Taher Pilehvar (Eds.). Association for Computational Linguistics, Vienna, Austria, 21991–22014. doi:10.18653/v1/2025.acl-long.1068
  19. [19]Zenan Liu, Yi Fan Wu, Zhaoyu Li, Xinming Wei, Fan Yang, Xian Zhang, and Xiaoxing Ma. 2024. Autoformalize Mathematical Statements by Symbolic Equivalence and Semantic Consistency. In Advances in Neural Information Processing Systems, A. G. Globerson, L. Mackey, D. Belgrave, A. Fan, U. Paquet, J. Tomczak, and C. Zhang (Eds.), Vol. 37. Curran Associates, Inc., 53598–53625. doi:10.2202/07917-1697
  20. [20]Hongyi Liu, Madhusudan Parthasarathy, and Adithya Murali. 2026. Faithful Autoformalization of Natural Language Assertions. arXiv:2607.13303 [cs.SE] https://arxiv.org/abs/2607.13303
  21. [21]Jiawei Liu, Chunqiu Steven Xia, Yuyao Wang, and Jingming Zhang. 2023. Is your code generated by chatgpt really correct? rigorous evaluation of large language models for code generation. Advances in neural information processing systems 36 (2023), 21558–21572.arxiv.org/abs/2305.01210
  22. [22]Lezhi Ma, Shangqing Xie, Yi Li, Xiaofei Xie, and Lei Bu. 2025. SpecGen: Automated Generation of Formal Program Specifications via Large Language Models. In 2025 IEEE/ACM 47th International Conference on Software Engineering (ICSE). 16–28. doi:10.1109/ICSE55347.2025.00129DOI
  23. [23]Zhi Ma, Cheng Wen, Zhexin Su, Xiao Liang, Cong Tian, Shengchao Qin, and Mengfei Yang. 2025. Bridging Natural Language and Formal Specification—Automated Translation of Software Requirements to LTL via Hierarchical Semantics Decomposition Using LLMs. In 2025 40th IEEE/ACM International Conference on Automated Software Engineering (ASE) (Seoul, Korea, Republic of). IEEE Press, 1208–1220. doi:10.1109/ASE63991.2025.00104DOI
  24. [24]Sergey Mechtaev, Jooyong Yi, and Abhik Roychoudhury. 2015. DirectFix: looking for simple program repairs. In Proceedings of the 37th International Conference on Software Engineering - Volume 1 (Florence, Italy) (ICSE ’15). IEEE Press, 448–458.
  25. [25]Daniel Mendoza, Christopher Hahn, and Caroline Trippel. 2024. Translating Natural Language to Temporal Logics with Large Language Models and Model Checkers. In 2024 Formal Methods in Computer-Aided Design (FMCAD). 1–11. doi:10.3427/2024/isbn.978-3-85448-065-5_17doi.org/10.34727/2024/isbn.978-3-85448-065-5_17</div
  26. [26]Daniel Mendoza, Anastasia Mavridou, Andreas Katis, and Caroline Trippel. 2026. Automating requirements formalization: using LLMs and low-complexity distinguishing traces for semantic validation. In Proceedings of the 2026 IEEE/ACM 48th International Conference on Software Engineering. 1314–1326.DOI
  27. [27]Hussein Mozannar, Gagan Bansal, Adam Fourney, and Eric Horvitz. 2024. Reading Between the Lines: Modeling User Behavior and Costs in AI-Assisted Programming. In Proceedings of the CHI Conference on Human Factors in Computing Systems (CHI ’24). ACM, 1–16. arXiv:2210.14306 doi:10.1145/3613904.3641936DOI
  28. [28]Auguste Poiroux, Gail Weiss, Viktor Kunčak, and Antoine Bosselut. 2025. Reliable Evaluation and Benchmarks for Statement Autoformalization. In Proceedings of the 2025 Conference on Empirical Methods in Natural Language Processing, Christos Christodoulopoulos, Tanmoy Chakraborty, Carolyn Rose, and Violet Peng (Eds.). Association for Computational Linguistics, Suzhou, China, 17947–17969. doi:10.18653/v1/2025.emnlp-main.907DOI
  29. [29]ISWB Prasetya, Fritsumeit Kefew, and Davide Prandi. 2026. Talk is Cheap, Logic is Hard: Benchmarking LLMs on Post-Condition Formalization. arXiv preprint arXiv:2603.17193 (2026).arxiv.org/abs/2603.17193
  30. [30]Cedric Richter and Heike Wehrheim. 2025. Beyond Postconditions: Can Large Language Models infer Formal Contracts for Automatic Software Verification? arXiv:2510.12702 [cs.SE] https://arxiv.org/abs/2510.12702
  31. [31]Kagan Tumer and Joydeep Ghosh. 1996. Error correlation and error reduction in ensemble classifiers. Connection science 8, 3-4 (1996), 385–404. doi:10.1080/095400996116839DOI
  32. [32]Cheng Wen, Jiulian Cao, Jie Su, Zhiwu Xu, Shengchao Qin, Mengda He, Haokun Li, Shing-Chi Cheung, and Cong Tian. 2024. Enhancing Program Specification Synthesis by Large Language Models Using Static Analysis and Program Verification. In Computer Aided Verification: 36th International Conference, CAV 2024, Montreal, QC, Canada, July 24–27, 2024, Proceedings, Part II (Montreal, QC, Canada). Springer-Verlag, Berlin, Heidelberg, 302–328. doi:10.1007/978-3-031-65630-9_16
  33. [33]Benjamin Lee Whorf. 1956. Language, Thought, and Reality: Selected Writings of Benjamin Lee Whorf. MIT Press, Cambridge, MA.
  34. [34]Yuhui Wu, Albert Qiaochu Jiang, Wenda Li, Markus Rabe, Charles Staats, Mateja Jamnik, and Christian Szegedy. 2022. Autoformalization with Large Language Models. In Advances in Neural Information Processing Systems, S. Koyejо, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh (Eds.), Vol. 35. Curran Associates, Inc., 32353–32368. doi:10.52202/064831-2344arxiv.org/abs/2205.12615
  35. [35]Fanpeng Yang, Xing Li, Shuling Wang, Jie An, Zeyu Sun, Shenghua Feng, Wenhan Wang, Weiyi Wang, Naijun Zhan, and Fanjiang Xu. 2026. How Powerful are LLMs in Generating Formal Program Specifications? arXiv:2608.13077 [cs.SE] https://arxiv.org/abs/2608.13077
  36. [36]Jiyao Zhang, Chengli Zhong, Hui Xu, Qige Li, and Yi Zhou. 2025. KELPS: A Framework for Verified Multi-Language Autoformalization via Semantic-Syntactic Alignment. arXiv:2507.08665 [cs.CL] https://arxiv.org/abs/2507.08665

Paper details

vlnc:W_a2m9q6nz
v1 · latestHistory (1)

published · Fresh — added to the Hub within the last 30 days

added ·

Usage

views · 0

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

CC BY 4.0

Original source

  • Computer Science

Not recorded for this paper · View statement →

Looking for related papers…
Contents