Manuscript Offprint
arXiv:2610.38130Template-Free Dynamic Invariant Detection
ERFAN ARVAN, NJIT, USA
MICHAEL D. ERNST, UW CSE, USA
MARTIN KELLOGG, NJIT, USA
A dynamic invariant detector proposes invariants, such as method pre- and postconditions, and rules out those that do not hold at run time. Traditional detectors propose invariants from a fixed library of templates, which limits their expressiveness. A large language model (LLM) can propose invariants instead of, or in addition to, template-derived ones. With the right prompt and context choices, we found that this idea can both improve the invariants' expressiveness and reduce the cost of inferring the invariants.
Greater expressiveness brings complications: an LLM-proposed invariant can execute arbitrary code during invariant evaluation, causing side effects or infinite loops. Our novel instrumentation strategies mitigate these problems. We wrap each candidate and evaluate only one invariant per thread at a time, so nested invariant evaluations cannot trigger one another indefinitely. To recover from non-nested hangs, we monitor each run for stalls and retry it under a growing time budget. Because we cannot prove a candidate side-effect-free in advance, we use delta debugging over the invariants evaluated during a failing test to isolate and disable a side-effecting candidate without discarding the rest of the run.
We compared our implementation, Oca, to the popular template-based Daikon invariant detector on real open-source Java projects. Oca produces more expressive invariants: on average, 28% of its held invariants call a project-specific method, which Daikon's templates cannot express. Its invariants are more often valid, with a false-positive rate of 18% in a manual inspection, vs. 76% for Daikon, and more useful: as properties for property-based testing, they exposed 9 of 25 real bugs, compared with 4 for Daikon. Oca also costs less, using 566 minutes and 27 GB of disk, compared with 2,817 minutes and 827 GB for Daikon.
1 Introduction
Invariants capture essential semantic properties of programs, such as preconditions, postconditions, and design intent. They support program understanding and serve as a foundation for testing, verification, and debugging [15]. A dynamic invariant detection tool infers invariants from executions. Traditionally, the tool proposes invariants from a fixed template library. This can express only properties that match one of its predefined syntactic forms: it cannot represent invariants that depend on project-specific logic or domain abstractions, and it restricts relations to a small, fixed number of variables. These limits are not implementation details of any one tool; they are structural consequences of deriving candidates from a fixed grammar, whatever that grammar is. Daikon [15] (fig. 2, right) is the most widely used tool of this design, in both research and practice [1, 26, 29, 48].
Recent advances in large language models (LLMs) provide an opportunity to move beyond fixed invariant templates. When supplied with source code as context, an LLM can propose candidate invariants that reflect program-specific constraints.
This paper introduces Oca¹, a dynamic invariant detector realizing this idea. Like Daikon, Oca validates candidates against program executions; unlike Daikon, it obtains them from an LLM rather than a template grammar. For each method entry and exit, Oca asks an LLM for candidate invariants, filters them, injects the survivors into the program source as instrumentation probes, and runs the existing test suite (fig. 2, left). A candidate that executes at least once and is never falsified is reported as held. Daikon by default checks invariants offline, against an execution trace written by its Java frontend, Chicory. That is infeasible for arbitrary expressions, which may depend
¹Oca is a South American root vegetable, chosen as a nod to Daikon, which was named after another root vegetable.
Authors' Contact Information: Erfan Arvan, ea442@njit.edu, NJIT, Newark, NJ, USA; Michael D. Ernst, UW CSE, Seattle, WA, USA, mernst@cs.washington.edu; Martin Kellogg, NJIT, Newark, NJ, USA, martin.kellogg@njit.edu.
on any part of the program state; checking candidates in place is also simpler and faster. Further speedups come from evaluating only a comparatively small set of LLM-proposed candidates.
Oca also dispenses with the complex machinery Daikon uses to avoid computing and reporting uninformative invariants. For example, an invariant over unrelated quantities, such as myBoolean <= myPointer, should not be reported, so Daikon computes abstract types [6, 17] to determine which variables may meaningfully be compared. Daikon also groups variables whose values are always equal, so that each template is instantiated once per group rather than once per variable; streamlines the common case of quickly falsified invariants; and applies statistical tests to suppress invariants that hold only by coincidence. An advantage of checking a small, targeted set of potential invariants is that Oca needs none of these complexities.
Using an LLM to propose invariants raises two challenges. The first (C1) is obtaining useful, well-formed candidates from the LLM: without careful prompt design and context, models produce ill-formed, vacuous, or irrelevant candidates, and even under a good prompt, some candidates are syntactically invalid or fail to compile. The second (C2) is ensuring that invariants evaluated at run time do not corrupt the inference process itself: they may have side effects that perturb program state (C2.1), pass otherwise-unseen values to the program's own routines – causing a called method's own injected invariants to be evaluated against inputs that arise only from invariant evaluation (C2.2) – or fail to terminate (C2.3).
We address these challenges as follows. For C1, we empirically evaluated multiple prompt strategies and context configurations, deriving the configurations from a literature review of the context that LLM-based software engineering techniques supply to the model (section 3). Oca also filters ill-formed expressions before instrumentation, using both syntactic checks and compilation (section 4.1). For side effects (C2.1), Oca relies on the project's test suite, using delta debugging to isolate and disable the specific candidate invariant responsible for an observed test failure (section 4.2.2). For C2.2, Oca suppresses nested invariant evaluation when another check is already active on the same thread (section 4.2.3). For nontermination (C2.3), the same re-entrancy check rules out the nontermination that mutually triggering probes would cause, and a background monitor detects and disables suspected nonterminating candidates at the per-invariant level, without discarding results for other invariants (section 4.2.4).
We evaluated Oca against Daikon on real open-source Java projects along four complementary dimensions, and found that Oca produces more expressive, more valid, and more useful invariants at lower cost. First, we compared the expressiveness of the inferred invariants (section 5.2): on average, 28% of Oca's held invariants call a project-specific method and 5% relate more than three variables; Daikon's templates can express neither. Second, we manually checked both tools' output for false positives, invariants that hold for the given executions but not in general (section 5.3): 18% of sampled Oca invariants were false positives, compared with 76% for Daikon. Third, we compared the invariants as properties for property-based testing (section 5.4): Oca exposed 9 of 25 real bugs, compared with 4 for Daikon. Fourth, we compared the tools' cost (section 5.5): Oca used 566 minutes and 27 GB of disk in total, compared with 2,817 minutes and 827 GB for Daikon. We deliberately adopt conservative evaluation choices throughout to avoid overstating the benefits of LLM-generated invariants. In summary, this paper makes the following contributions:
- A characterization of the research challenges in using large language models for dynamic invariant detection.
- A language-agnostic design for template-free dynamic invariant detection: LLM-proposed candidates are checked in place by probes, with test-driven isolation of side effects, suppression of nested evaluation, and recovery from hangs.
@Override
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
if (sourceType.isAssignableTo(targetType)) {
return source;
}
Collection<?> sourceCollection = (Collection<?>) source;
if (sourceCollection.isEmpty()) {
return null;
}
Object firstElement = sourceCollection.iterator().next();
return this.conversionService.convert(firstElement, sourceType.elementTypeDescriptor(firstElement), targetType);
}
Fig. 1: CollectionToObjectConverter.convert from Spring's [42] type-conversion infrastructure.
- A literature review of the program context that LLM-based software engineering techniques supply to the model: a taxonomy derived by coding 181 papers from the latest editions of FSE, ICSE, ASE, and ISSTA, with the prevalence of each context type.
- An empirical study of prompt and context strategies for LLM-based invariant generation.
- Oca, an implementation of our template-free invariant detector design for Java that supports both cloud-hosted and locally hosted LLMs.
- An empirical evaluation comparing Oca and Daikon for expressiveness, validity, downstream usefulness, and inference cost.
2.1 Terminology
In this paper, a program point is a method entry or exit; together they capture a method's preconditions and postconditions. A candidate invariant is an arbitrary Boolean expression proposed for a program point; it may reference formal parameters, result (at non-void method exits), and fields, and it may invoke methods. Oca injects each candidate and executes the project's test suite; each evaluation of a candidate at its program point is a check. A candidate is reported as held if it compiles, is evaluated at least once, and is never observed to be false; it is falsified if any evaluation returns false or throws an exception; otherwise, it is never executed. We call the wrapper injected at the corresponding program point to evaluate the candidate and record the outcome an instrumentation probe, or simply a probe (section 4.2.1 details its structure). Oca disables a candidate, leaving its probes in place but no longer checking it, once it is falsified, causes a test failure, or hangs.
2.2 Running Example
The convert method of fig. 1 takes a source collection source of type sourceType and produces a value of targetType. If sourceType is already assignable to targetType, the method returns source unchanged. Oca reports this property at convert's exit:
!sourceType.isAssignableTo(targetType) || result == source

Fig. 2: The pipelines of Oca (left) and Daikon (right).
By contrast, Daikon reports only that this conversionService is not side-effected. Daikon's output says nothing about the method's semantics. Inferring the key invariant, and doing so safely, requires Oca to address two challenges: proposing invariants (C1) and evaluating candidates safely (C2).
2.3 Proposing Invariants (C1)
In initial experiments, a naively prompted LLM often proposed low-quality invariants: tautologies such as sourceType.isAssignableTo(targetType) || !sourceType.isAssignableTo(targetType); trivial invariants such as source == null || source instanceof Object, which merely reflects the declared type of source; and false candidates such as result == source, which does not always hold.
LLMs are also sensitive to the source-level context supplied in the prompt: too little context can lead to generic, irrelevant, code-inconsistent, or false candidates, while excessive or extraneous context can distract the model, increase cost, and reduce the quality of its proposals. Prompt strategy and context configuration together determine the quality of the candidates the LLM proposes.
We address both facets of the proposal problem empirically rather than by fixing design choices in advance: in section 3, we evaluate a set of prompt strategies drawn from prior work and select the best-performing one, then evaluate and select a context configuration under that strategy. All other evaluations use the selected combination, Few-Shot with Class-Aware context.
2.3.1 Filtering and Compiling Candidates. Even with a well-designed prompt, a candidate is not guaranteed to be high-quality, syntactically valid, or compilable: it may be a tautology, reference an identifier that is unavailable at the program point (e.g., firstElement != null at method entry, since firstElement is a local variable defined only partway through the method body), violate a typing constraint (e.g., source.size() > 0, since source is statically typed as Object), or be malformed (e.g., sourceType.isAssignableTo(targetType) && (result == source, which is missing a closing parenthesis) (C1). Oca first applies cheap static filters (section 4.1.1), which catch many problematic ones. For the rest, the Java compiler provides a stronger check (section 4.1.2).
2.4 Evaluating Candidates Safely (C2)
2.4.1 Side Effects (C2.1). Evaluating a candidate can cause side effects that corrupt program state. A side effect can make a valid invariant appear falsified or a falsified invariant appear to hold.
Oca does not attempt to prove a candidate side-effect-free before running it. Precisely determining side-effect freedom is undecidable in general, and the purity-analysis tools available in practice rely on conservative approximations that classify many side-effect-free methods as potentially side-effecting [19]. Filtering candidates on the results of such an analysis would wrongly reject many useful candidates that invoke side-effect-free methods.
Oca derives a more practical but weaker guarantee from the project's test suite. The intuition is that if a side effect occurs, it is likely to change the tests' behavior. If a test fails, Oca uses delta debugging to find the invariants that caused that failure and disables them in the next run. Oca thus guarantees that reported invariants are side-effect-free modulo the test assertions, but a side effect that no test exposes can still go undetected.
2.4.2 Nested Invariant Invocation (C2.2). Even a side-effect-free candidate can distort the invariants Oca reports, because evaluating it passes the program's own routines values they would not otherwise see. Consider this conversionService.convert(source, sourceType, targetType) != null, proposed at convert's exit: evaluating it invokes the conversion service again, which may dispatch to a different, instrumented converter and evaluate that converter's own invariants against an execution that exists solely because this (possibly incorrect!) candidate was being checked.
Oca guarantees that only one invariant evaluates at a time on a given thread: nested evaluation is suppressed, so one invariant's evaluation cannot trigger another's.
2.4.3 Nontermination (C2.3). Evaluating a candidate can also fail to terminate. It may call a method with an argument value that arises only because of the evaluation itself – such as a much larger bound than the method was designed for – and run too long.
Oca monitors each run for signs that it has stalled. On detection, it kills the run, permanently disables the candidate whose probe was executing at that point, if any, and retries with a larger time budget, repeating until a run finishes cleanly.
3 Selecting a Prompt Strategy and Context (C1)
We empirically evaluated prompt strategies and context configurations. We organized this configuration-selection process around two research questions:
-
RQ1 (Prompt Strategy): Which prompt strategy is most effective for generating invariants that hold during invariant evaluation?
-
RQ2 (Context Configuration): Which program-context configuration is most effective for generating invariants that hold under the selected prompt strategy?
We answer the two questions in sequence: RQ1 compares prompt strategies under a fixed context configuration, and RQ2 compares context configurations under the prompt strategy selected in RQ1. Testing every pair of strategy and configuration would have multiplied the experimental cost, so this design assumes the two factors are independent (a threat to validity discussed in section 6).
For both RQs, we operationalized effectiveness as the number of held invariants produced by Oca under the given configuration. This is an objective and scalable metric: it can be measured without human judgment. It does not measure invariant quality, however: a trivially true invariant counts the same as a semantically meaningful one. Analogously to statement coverage in testing, a configuration that yields few held invariants is unlikely to be useful, but a high count alone does not ensure useful invariants. We assess quality separately, through expressiveness (section 5.2), false positives (section 5.3), and usefulness in property-based testing (section 5.4).
Table 1: Prompt strategies we evaluated. Each strategy other than Zero-Shot is the Zero-Shot template plus only the additions in its own row. Exact prompts are available in our replication package [2].
| Strategy & Prompting Technique | Our Template |
|---|---|
| Zero-Shot promptingZero-shot | The system message gives the task description and global rules (output schema, allowed names, side-effect freedom, no tautologies). The user message gives the program point, in-scope names, and program context, and requests up to K invariants as JSON. |
| Few-Shot promptingIn-context learning | Zero-Shot template + 1–2 worked examples (program point → expected JSON) before the target instance. |
| Chain-of-ThoughtThought generation | Zero-Shot template + an instruction to reason internally about types, evaluability, and implied constraints before answering. |
| StepwiseDecomposition | Zero-Shot template + explicit sub-steps (unary, then relational, then method-call invariants), combined into one JSON output. |
| Self-RefinementSelf-criticism | Zero-Shot template + an instruction to draft candidates, check each against the rules, and return only the corrected set. |
| Multi-SampleEnsembling | Zero-Shot template + an instruction to produce three internal drafts with different focuses and keep only invariants that appear in at least two. |
3.1 Benchmark Projects
We searched open-source projects hosted on GitHub using SEART's repository search infrastructure [11], applying the following criteria: (1) the project is written in Java, (2) it has at least 1,000 commits, (3) it has at least 1,000 pull requests, (4) it has at least 1,000 GitHub stars, and (5) it has at least one commit in the three weeks before we downloaded it. Oca targets Java programs, requiring criterion 1. Criteria 2–5 favor mature, active, and widely used projects. These criteria yielded 16 candidate projects. We then excluded 3 repositories whose available Javadocs were not predominantly written in English (e.g., alibaba/druid). Some context configurations in our study provided Javadocs to the LLM, so the language of those Javadocs could itself affect the generated invariants. Including such projects would therefore make it difficult to determine whether differences between configurations were caused by the provided context or by its language. Next, we excluded 7 projects for which the flaky-test detector iDFlakies [23] could not be run successfully. Our experiments use iDFlakies to identify and remove potentially flaky tests, which is important because Oca uses test failures to detect side effects. After these filtering steps, six projects remained: Apollo [5], Dubbo [3], Hudi [4], libGDX [25], Netty [44], and Spring [42]. When a project contained multiple Java modules or subprojects, we manually identified the primary module containing the project's core functionality and used that module in our evaluations.
3.2 RQ1: Prompt Strategy
A single, unstructured instruction to propose an invariant tends to lead to vague or trivially true output, since the model has no signal about what kind of property is useful beyond “something that holds”. Table 1 shows the text-based prompting strategies that we evaluated instead, which we derived from the survey by Schulhoff et al. [40]. (Other surveys of prompt engineering [20, 39] are similar.) We treated zero-shot prompting as the baseline strategy; every other strategy extends it.
We instantiated each strategy with meta-prompting [40]: we provided GPT-5 with a meta-prompt that combined a description of the strategy with a task specification shared by all strategies and written by the authors, and GPT-5 returned the strategy's prompt template. The specification has three parts, which GPT-5 was instructed to copy verbatim into the template. Rules, such as “Each invariant must be a valid Java boolean expression”, govern output format and well-formedness
Table 2: Held invariants by prompt strategy, per project, using the Local context configuration. Every strategy was run on all six benchmark projects, so the final column sums over all six and is directly comparable across rows. Bold marks the best value in each column.
| Strategy | Apollo | Dubbo | Hudi | libGDX | Netty | Spring | Total |
|---|---|---|---|---|---|---|---|
| Zero-Shot (baseline) | 1,515 | 8,119 | 316 | 711 | 1,045 | 5,937 | 17,643 |
| Few-Shot | 1,396 | 9,017 | 257 | 1,673 | 909 | 6,021 | 19,273 |
| Chain-of-Thought | 1,404 | 8,256 | 561 | 635 | 837 | 5,219 | 16,912 |
| Stepwise | 1,378 | 8,328 | 580 | 672 | 453 | 4,973 | 16,384 |
| Self-Refinement | 1,169 | 7,584 | 549 | 1,624 | 1,095 | 4,670 | 16,691 |
| Multi-Sample | 638 | 3,972 | 271 | 978 | 440 | 2,355 | 8,654 |
and go in the system message. Constraints, such as “Do not invent methods or fields that are not available at this program point”, govern candidate content and go in the user message, with the program point and context. The third part, also in the user message, defines result, a symbolic name for the method’s return value along all paths. Giving the specification to GPT-5, rather than appending it afterward, lets each template build on it; e.g., Self-Refinement checks drafts against the rules.
The complete rules, constraints, and generated prompt templates are available in our replication package [2].
3.2.1 Experimental Results. We ran Oca on each benchmark project (section 3.1), varying only the prompt strategy while keeping all other factors fixed, using the Local context configuration (section 3.3’s baseline). As the LLM, we used gpt-4.1-mini via the OpenAI API, with K (the maximum number of invariants requested per query, table 1) of 5. Table 2 shows the number of held invariants that Oca produces for each combination of benchmark and prompt strategy.
Few-Shot produced the most held invariants overall (19,273); most of the other strategies clustered around 17,000; and Multi-Sample trailed the rest by a wide margin (8,654). This ranking is not an artifact of aggregation: Few-Shot was also the best strategy on three of the six benchmark projects – Dubbo (9,017), libGDX (1,673), and Spring (6,021) – more projects than any other strategy. So, we selected Few-Shot as the prompt strategy for the rest of the paper.
3.3 RQ2: Context Configuration
Independently of prompt strategy, the amount of source-level context supplied affects what the model can reference when proposing an invariant. Unlike for prompt strategies, we could not find a survey of context configurations. So, to select contexts, we conducted a literature review of the latest editions of four top-tier software engineering conferences (FSE, ICSE, ASE, and ISSTA).
3.3.1 Literature Review Procedure. We first searched for papers mentioning “LLM” or “large language model” in their title or abstract, yielding 332 papers. We manually examined these papers to identify those in which an LLM performed a task on source code (e.g., program repair, refactoring, code generation, or reasoning about program behavior), resulting in 184 candidate papers. We open-coded a random sample of these papers, starting with 20 (about 10%) and adding five randomly selected papers at a time until a batch of five produced no new category, which happened at 40 papers. We examined the context supplied to the LLM in each sampled paper and inductively grouped the observed types into the categorization in fig. 3. We then applied these codes to the remaining 144 papers, examining their methods and prompts where available. One author performed the initial coding, and the other authors reviewed the resulting codes; we resolved disagreements through live discussion among the authors. The original categories covered the code-related context in every paper but one: a frontend-repair study [49] supplied properties of the rendered interface. We
Table 3: Context configurations considered in our study.
| Configuration | Composition |
| Local | Method body + in-scope variables (baseline). |
| Documented | Local + the method's own Javadoc. |
| Class-Aware | Local + enclosing class Javadoc, field names/types, and method signatures (and Javadoc). |
| Type-Aware | Local + Class-Aware for all types referenced in the method's signature. |
| Usage-Aware | Local + call sites of the method with each caller's Javadoc and implementation. |
| Example-Driven | Local + argument/return-value pairs observed from a test run. |
added the TEST-RENDER subcategory of TEST-EXEC for this execution-derived context after the initial coding. We could not assign a single study-level LLM-context code to three of the remaining papers, because they compare several systems, describe no implemented system, or give no input to an LLM, leaving 181 coded papers. Our search results, screening decisions, per-paper codes, and the justifications for them are in our replication package [2].
3.3.2 Context Configurations Evaluated. We derived the context configurations from the six top-level categories in fig. 3. We excluded Historical/Temporal Context (HIST) because Oca only takes source code as input, not version control history. We also excluded Semantic Context (SEM) because the reviewed papers derive it from hand-constructed abstractions (e.g., manually written specifications) rather than mechanically extracted context; Oca is fully automated. For each of the four remaining categories, we selected one or more representative context components that are (a) mechanically extractable from the project and (b) plausibly informative for proposing an invariant at a given program point. Below, we describe each by category, tagged with its taxonomy code(s).
We drew two components from the Local Code Context (LC) category as the baseline: (1) the method body (LC-FUNC): the source code of the method itself; and (2) the scope (LC-SUBSRC): a list of the in-scope variables and their types at the program point. Together, these give the model a concrete starting point, which helps prevent hallucinations.
We drew three components from the Structural Expansion Context (SE) category — class documentation, type documentation, and call-site context — all instantiated SE-ANALYSIS: structural information about the program obtained by statically resolving declarations and usages, rather than reasoning about the method body in isolation. The class documentation (SE-ANALYSIS + DOC-NL, applied to the enclosing class) consists of structured information about the class enclosing the method: its Javadoc, the names and types of its fields, and the signatures and Javadocs of its other methods. We treat this as an SE rather than DOC-NL component because, although it does include some natural-language documentation, it is assembled using an analysis. The type documentation (SE-ANALYSIS + DOC-NL, applied recursively to referenced types) contains the same structured information — Javadoc, fields,

Fig. 3: Taxonomy of context types provided to LLMs, derived via open coding of prior work. Bracketed numbers count the 181 coded papers that use each type or any of its subtypes; a paper can use several types, so parent counts are unions rather than sums.
Table 4: Held invariants by context configuration, per project, under the selected Few-Shot prompt strategy. Local reuses the Few-Shot row from table 2, since it is the same underlying configuration. Bold marks the best value in each column.
| Configuration | Apollo | Dubbo | Hudi | libGDX | Netty | Spring | Total |
|---|---|---|---|---|---|---|---|
| Local (baseline) | 1,396 | 9,017 | 257 | 1,673 | 909 | 6,021 | 19,273 |
| Usage-Aware | 1,554 | 9,414 | 255 | 941 | 824 | 6,173 | 19,161 |
| Class-Aware | 1,543 | 9,384 | 332 | 1,819 | 1,021 | 6,419 | 20,518 |
| Documented | 1,401 | 9,045 | 262 | 577 | 880 | 6,230 | 18,395 |
| Type-Aware | 1,396 | 9,067 | 257 | 751 | 908 | 6,038 | 18,417 |
| Example-Driven | 1,548 | 8,868 | 333 | 1,046 | 872 | 6,137 | 18,804 |
method signatures — but gathered recursively for the types referenced in the method's signature (i.e., its parameter and return types). This documentation enables the model to include an operation defined on a parameter's type that is not visible from the method body or the enclosing class alone. Finally, the call-site context (SE-ANALYSIS, applied to call sites) consists of call sites of the method elsewhere in the project, each paired with the caller's own Javadoc and implementation. This shows the model how the method is used in practice, which could suggest a constraint on its inputs or outputs that is satisfied by every caller but not stated in the method's own documentation.
We drew one component directly from the Documentation & Retrieval Context (DOC/RET) category — the method Javadoc (DOC-NL). DOC-NL also appears combined with SE-ANALYSIS in two of the SE components above, but this component is scoped to the method itself rather than requiring resolution of other declarations.
Lastly, we drew one component from the Testing & Execution Context (TEST) category — I/O examples (TEST-IO) observed from a test run. These argument and return-value pairs were drawn from an index pre-built with Daikon's Chicory [15]. This gives the model concrete evidence of what the method's inputs and outputs look like, which a static reading of the source may not provide.
We combined these components into named context configurations, which each supply a different mix of context to the prompt. Every configuration includes the method body and scope (LC) as a baseline, which we call Local. Each remaining configuration adds exactly one non-LC component to Local: Documented adds the method Javadoc, Class-Aware adds class documentation, Type-Aware adds type documentation, Usage-Aware adds call-site context, and Example-Driven adds I/O examples. Table 3 summarizes the resulting configurations.
3.3.3 Experimental Results. All configurations were evaluated with the Few-Shot prompt strategy selected in section 3.2. Table 4 shows the results. Class-Aware produced the most held invariants overall (20,518). Based on these results, Oca uses the Few-Shot prompt strategy with the Class-Aware context configuration in all subsequent experiments in this paper.
To understand why Class-Aware produced more held invariants, we manually inspected nine randomly sampled methods for which every configuration other than Local produced at least one held invariant, plus CollectionToObjectConverter.convert from our running example (section 2.2). In most of these methods, Class-Aware's invariants were more semantically meaningful, captured richer relationships among program values or object state, or avoided trivial and observation-specific properties that other configurations produced. For example, Class-Aware was the only configuration to recover the key relationship in convert: when the source type is assignable to the target type, the result is the source object itself. A plausible explanation is that class-level context describes the surrounding abstraction, letting the model connect the method to relationships not explicit in its body. The other configurations showed characteristic biases: Example-Driven sometimes anchored on salient values in the supplied executions, such as nullness, numeric ranges, or particular run-time states, and Usage-Aware sometimes emphasized relationships specific to how the observed callers use the method. Our inspection thus complements the quantitative result: class-level context tends to yield more informative candidates, not only more of them.
4 Filtering and Evaluating Candidates
This section describes how Oca statically filters and compiles candidate invariants proposed by the LLM to discard malformed ones (C1), then evaluates them safely during test execution (C2).
4.1 Filtering and Compiling Candidates (C1)
4.1.1 Static Filtering. Before injecting a candidate, Oca checks it against a set of rejection criteria. A candidate is rejected if it exceeds a length bound intended to catch degenerate or runaway generations; if it is a syntactic tautology, such as a disjunction of an expression and its negation; if it uses a construct that may introduce further side effects or nontermination on its own (lambda, streams, object construction, throw, System.exit); if it mentions no variable in scope at that program point; if it performs a null check against a variable of primitive type; if it references an identifier that is not in scope; or if it does not parse as a valid Java expression.
4.1.2 Compilation and Error Attribution. After injecting candidate invariants into the program, Oca runs the compiler and parses any resulting compiler errors. Oca wraps each injected probe in begin/end marker comments, so each delimited region contains the probe's code, including the candidate's identifier (section 4.2.1). When the compiler reports an error inside such a region, Oca removes the region, records the candidate as failing to compile, and retries. If errors remain after a configurable number of retries, Oca restores each file that still fails to compile to its uninstrumented state, guaranteeing that this process terminates with a successful compilation.
4.2 Evaluating Candidates Safely (C2.1–C2.3)
Section 2.4 introduced challenges C2.1–C2.3, which arise from evaluating candidates.
4.2.1 Probe Structure. Each candidate is injected as one or more probes; fig. 4 shows a probe's structure in the abstract. Oca represents each candidate with a unique identifier shared by its probes. Once a candidate is falsified, its probes stop evaluating it for the rest of the process. Oca also records falsified candidates, and those that hang (section 4.2.4) or cause a test failure (section 4.2.2), so that later processes skip them. Within one run, whenever execution reaches a candidate's program point, its expression is evaluated unless the candidate has been disabled or another invariant is already evaluating on the same thread. A method-entry probe is placed at the start of the method body; a method-exit probe is placed immediately before each return statement, or at the point of fall-through for a void method.
4.2.2 Side Effects. Oca uses newly failing tests as a proxy for side effects from candidate invariants (C2.1). We would prefer that Oca statically prove that candidates are side-effect free, but the available tools are so conservative that they reject most candidates in practice, leading Oca to discard too many useful candidates [19]. Oca's approach underapproximates
disabled: global map, id to boolean,
initially false
evaluating: thread-local flag,
initially false
probe(id, invariant):
if disabled[id] or evaluating:
return
evaluating := true
try:
ok := invariant
catch any exception:
ok := false
finally:
evaluating := false
if not ok:
record id as falsified
disabled[id] := true
Fig. 4: The bottom part is the structure of the probe injected for a candidate invariant with identifier id. For clarity, the figure omits bookkeeping for hang detection (section 4.2.4) and for carrying outcomes across processes.
side effects, since one that no test exercises goes undetected. In exchange, it catches side effects that disrupt the behavior developers actively validate.
When a test fails on an instrumented run, Oca applies the ddmin delta-debugging algorithm [50] to the set of candidates executed during that run, reducing it to a 1-minimal set of culprits. Oca orders the candidates so that those executed closest to the failure come first, on the premise that they are more likely responsible; this biases the search toward finding the culprits early. Once a culprit set is isolated, Oca disables it and reruns the test suite to confirm that the failure no longer reproduces, which guards against coincidental reductions.
4.2.3 Nested Evaluation. Evaluating a candidate can call a method that has its own injected probe, so the outer evaluation triggers the inner probe's evaluation against inputs that exist only because the outer candidate is being checked. This nesting leads to two challenges: the inner invariant may be falsified incorrectly (C2.2), and if the method containing the inner probe transitively calls back into the method containing the outer probe, the two probes can trigger each other indefinitely, hanging the run (C2.3). The evaluating check in fig. 4 closes off both nested cases: this thread-local flag is set while a probe evaluates its invariant, so a probe reached during another invariant's evaluation returns without evaluating its own.
4.2.4 Detecting and Recovering from Hangs. Non-termination is still possible without nesting: a candidate can call a method that blocks indefinitely without involving any other probe. Oca kills a run if it produces no output on standard output or standard error for longer than a silence timeout, or if it exceeds its time budget. If a candidate was being evaluated at that moment, Oca disables it. Then, Oca reruns the program from the start with a longer time budget, doubled from the previous attempt up to a fixed cap, so that a few retries suffice for a slow but legitimate run. If a run at the cap is killed while no candidate is being evaluated, Oca by default disables the most recently evaluated candidate and reruns. Alternatively, Oca can be configured to disable every candidate evaluated before the stall, which prevents the same stall from recurring if the uninstrumented tests finish within the cap, at the cost of not checking those candidates again. It can also be configured to stop and report the invariants held so far, leaving the user to diagnose the stall.
5 Evaluation
Our evaluation compares Oca to Daikon in four ways:
- RQ3 (Expressiveness). Does Oca infer invariants that Daikon structurally cannot?
- RQ4 (False-Positive Analysis). Compared to Daikon, how many "invariants" reported by Oca do not actually hold on all possible executions?
- RQ5 (Usefulness). How do the invariants inferred by Oca compare to those inferred by Daikon when used for a downstream task, property-based testing?
- RQ6 (Performance). How does the cost of generating invariants with Oca compare to the cost of generating invariants with Daikon?
Unless otherwise noted, Oca uses the prompt strategy and context configuration selected in section 3 (Few-Shot prompting with Class-Aware context) and Daikon uses its default settings throughout. All experiments in this evaluation, for both Daikon and Oca, were run on a high-performance computing (HPC) cluster, on nodes with AMD EPYC 7753 CPUs and 128 GB of RAM. Oca uses gpt-4.1-mini via the OpenAI API, with , as in section 3.
5.1 Subjects and Datasets
We drew on two sets of subject programs in this evaluation. The first is the set of six benchmark projects from section 3.1 (Apollo, Dubbo, Hudi, libGDX, Netty, and Spring). Since this benchmark was also used to select Oca's prompt strategy and context configuration, there is a risk of overfitting, which motivates the inclusion of a second dataset. The second dataset is Defects4J [21], a widely used benchmark suite of real-world Java programs with curated buggy and fixed versions and high-quality test suites. For each subject program, Defects4J provides paired buggy and fixed revisions, enabling controlled comparisons across program versions.
Defects4J contains 17 projects. We excluded Chart because checking it out requires Subversion, which was unavailable on our cluster. We then piloted the usefulness experiment in section 5.4 on the latest bugs of the remaining 16 projects. A project was included only if every step completed successfully for both tools within the cluster's 72-hour walltime limit. Daikon's Chicory frontend exceeded this limit while collecting traces on 10 projects, and crashed on another (Jsoup). We therefore experimented with only five projects: Cli, Codec, Collections, Gson, and Math.
5.2 RQ3: Expressiveness
The subject projects in this experiment are the six benchmarks from section 3 and the five Defects4J projects; we analyze and report the two sets separately. For every subject project, we ran both Daikon and Oca using the same project version and test suite, inferring invariants at all method entry and exit program points. The same executions were used for both tools wherever possible, so that differences in the resulting invariant sets reflect differences between the invariant-detection approaches rather than differences in exercised program behavior.
The independent variable is the invariant-inference tool—Daikon or Oca. The dependent variable is invariant expressiveness:
Definition 5.1 (Expressiveness). We define an inferred invariant as expressive if it (1) involves project-specific operations or (2) relates more than three variables.
This definition intentionally underestimates Oca's full expressive capability, since it excludes other forms of semantic richness that may also lie outside Daikon's fixed template library. We adopt this restricted definition to make the comparison with Daikon objective and unambiguous. Both criteria correspond to expressiveness boundaries that Daikon cannot cross by design: Daikon's invariant grammar does not support project-specific method calls and limits relations to a small, fixed number of variables. By focusing on these dimensions, we avoid subjective judgments about invariant quality and ensure that any measured expressiveness advantage reflects capabilities fundamentally unavailable to Daikon.
For each project, we recorded four quantities: , the total number of held invariants reported by Daikon; , the total number of held invariants reported by Oca; , the number of held Oca invariants that relate more than three variables; and PSPM, the number of held Oca invariants that contain at least one project-specific method call, which we used to operationalize the project-specific-operation criterion above. From these, we computed two expressiveness metrics for Oca: the percentage, , and the PSPM percentage, . We report and alongside these percentages for context, not as a measure of relative quality, because the two counts are not comparable. Oca's count scales with , the maximum number of invariants requested per query, which we set to 5 (section 3); raising yields more held invariants. Daikon's count reflects its large template grammar, which instantiated many low-information invariants, such as the only invariant it reports for our running example: that this conversionService is not side-effected (section 2).
For three of the configuration-selection benchmark projects, Daikon could not produce invariants from a full trace. For Dubbo and libGDX, tracing with Chicory did not finish within the 72-hour maximum walltime of our institution's HPC cluster; for Netty, Daikon terminated with an exception while processing the full trace. For these projects, we reran Chicory with -sample-start=5, which records every execution of a program point until it has executed five times and samples later executions, and ran Daikon on the resulting trace. Their values therefore come from sampled traces, which can change the set of invariants Daikon reports in both directions: an invariant that a skipped execution would falsify can survive, and an invariant can go unreported because too few observations remain for Daikon to justify it statistically.
5.2.1 RQ3 Results. Table 5 gives the results. Overall, the results support an expressiveness advantage for Oca. By design, none of Daikon's invariants relate more than three variables or call a project-specific method; Oca has no such limitations. In fact, Oca produced such invariants on every project: on the benchmark projects, a macro-average of 4% of its held invariants related more than three variables and 23% called a project-specific method; on Defects4J, the corresponding figures were 6% and 33% (5% and 28% across all 11 projects). These percentages underestimate Oca's expressiveness, since the definition deliberately counts only these two forms. Oca's advantage is the kinds of properties it can express, not the number of invariants, which is not directly comparable between the tools.
5.3 RQ4: False-Positive Analysis
Both Daikon and Oca are dynamic invariant detectors: an invariant that they report "holds" was true on the observed executions, but it is not necessarily a semantic property of the program. An incorrect candidate may therefore be reported as held
simply because the available test executions do not exercise an input that falsifies it. Since Daikon and Oca propose invariants in different ways, one tool could introduce more "false-positive" invariants that are not true on all possible program executions.
To test whether one tool does, we manually analyzed a stratified sample of 100 held invariants, 50 from each tool, drawn from the outputs of Daikon and Oca on the benchmark projects described in section 3.1. The 100 invariants come from 19 distinct methods across all the benchmark projects. We stratified the sample across projects and methods, including methods exercised with different numbers of inputs, to avoid concentrating the analysis on a small number of projects, methods, or highly exercised program points.
To reduce bias, one author prepared the sampled invariants for blinded review by removing all information identifying which tool produced each. Because Daikon reports invariants in its own textual notation, this author rewrote the sampled Daikon invariants as semantically equivalent Java expressions so that their representation was indistinguishable from that of the Oca invariants. The resulting blinded sample was independently inspected by two other authors. For each invariant, the reviewers examined the corresponding program point and source code and determined whether
Table 5: Expressiveness results for the benchmark projects used in the prompt and context studies and for the fixed Defects4J projects. Each and PSPM entry gives the count of held Oca invariants of that kind and, in parentheses, its share of ; percentages in the Total rows are macro-averages.
| Project | ND | NO | V>3 | PSPM |
|---|---|---|---|---|
| Benchmark projects (prompt/context study) | ||||
| Apollo | 59,316 | 1,543 | 53 (3%) | 237 (15%) |
| Dubbo† | 19,730 | 9,384 | 378 (4%) | 4,091 (44%) |
| Netty† | 75,756 | 1,021 | 48 (5%) | 215 (21%) |
| Hudi | 312,607 | 332 | 2 (1%) | 6 (2%) |
| libGDX† | 21,101 | 1,819 | 101 (6%) | 329 (18%) |
| Spring | 9,590 | 6,419 | 194 (3%) | 2,569 (40%) |
| Total | 498,100 | 20,518 | 776 (4%) | 7,447 (23%) |
| Defects4J projects (fixed versions) | ||||
| Cli | 6,389 | 1,929 | 87 (5%) | 513 (27%) |
| Codec | 45,147 | 4,049 | 257 (6%) | 1,231 (30%) |
| Collections | 122,046 | 18,549 | 1,071 (6%) | 7,975 (43%) |
| Gson | 418,757 | 3,426 | 231 (7%) | 1,021 (30%) |
| Math | 18,789 | 5,522 | 337 (6%) | 1,990 (36%) |
| Total | 611,128 | 33,475 | 1,983 (6%) | 12,730 (33%) |
†Daikon ran on a sampled trace (-sample-start=5) because tracing did not finish within the 72-hour walltime limit (Dubbo, libGDX) or failed with an exception (Netty).
the invariant was semantically valid: that is, whether it followed from the program's semantics and the expressed programmer intent at that program point rather than merely holding for the executions observed by the dynamic analysis. An invariant was classified as a false positive when it was reported as held by the tool but was not semantically valid and had survived only because the available executions did not expose a counterexample. Disagreements between the two reviewers were resolved by the judgment of a third author.
We report, for each tool, the number and percentage of sampled invariants classified as false positives. We additionally report the number and percentage of classifications on which the two reviewers agreed, and their inter-rater agreement according to Cohen's , both computed on the reviewers' independent classifications, before disagreements were resolved.
Table 6: False-positive analysis of the manually inspected sample (RQ4).
| Tool | False pos. | Valid | Total | Rate |
|---|---|---|---|---|
| Oca | 9 | 41 | 50 | 18% |
| Daikon | 38 | 12 | 50 | 76% |
5.3.1 RQ4 Results. Table 6 shows the results. Of the 50 sampled Daikon invariants, 38 (76%) were classified as false positives, compared with 9 of 50 (18%) for Oca. The reviewers agreed on 89 of the 100 classifications (89% agreement) and disagreed on 11 (11%), which the third author resolved. Their inter-rater agreement was substantial, with a Cohen's of 0.780. Overall, Oca had the lower observed false-positive rate in this manually inspected sample.
5.4 RQ5: Usefulness via Simulated Property-Based Testing
We evaluated invariant usefulness by simulating a realistic debugging workflow in which invariants are inferred before a bug-revealing input is known and are then evaluated once such an input becomes available. The goal is to infer an invariant that the original programmers intended to always be true but that only the bug-revealing input falsifies (because of the bug). For this experiment, we used buggy versions of the Defects4J benchmarks. While working on this experiment, we resolved five issues that caused Daikon to fail, but additional randomly selected pilot bugs revealed further issues that required manual intervention. Daikon also required up to 1 TB of traces per bug, which limited how many bugs could run concurrently. Given these execution and storage limitations and the manual effort needed to resolve failures, we limited our evaluation to the latest five bugs of each included project, 25 bugs in total. For each bug, we applied the same procedure to Daikon and Oca:
(1) Infer candidate invariants. Run the buggy version's test suite without the bug-revealing tests and retain the held candidate invariants. (2) Check whether the bug-revealing tests falsify any invariants. Run the bug-revealing tests and identify the candidates falsified by them. (3) Check the fixed version. Check that those candidates are not falsified anywhere in the fixed version's full test suite.
A bug is exposed if at least one candidate satisfies all of these requirements. We attribute each invariant check to the test that triggered it, and neither tool infers new candidates after the first step. Excluding the bug-revealing tests in the first step models a developer who has not yet identified a failing test, and it prevents bug-triggering inputs from leaking into inference.
This evaluation design intentionally factors input generation out of the experiment. Although property-based testing typically relies on automated input generation (e.g., random or coverage-guided fuzzing), Defects4J already provides inputs that are known to expose each bug. By reusing these inputs, we isolated and compared the usefulness of the inferred invariants themselves, independent of the effectiveness of any particular input-generation technique. Both Daikon and Oca were evaluated on identical bug-revealing inputs, ensuring a fair and controlled comparison.
We report the number of bugs each tool exposes per project, and its Bug Exposure Rate (exposed bugs divided by evaluated bugs) in aggregate.
5.4.1 RQ5 Results. Table 7 reports the bugs each tool exposed. Oca exposed 9 of the 25 bugs (36%), and Daikon exposed 4 (16%). Overall, the results support a substantial usefulness advantage for Oca: it exposed more than twice as many bugs as Daikon (9 versus 4), and it exposed at least as many bugs as Daikon on every project except Math. Because the comparison covers 25 bugs from five projects, the size of the advantage should be interpreted with care (section 6).
Table 7: Bugs exposed per project (RQ5).
| Project | Bugs | Oca | Daikon |
|---|---|---|---|
| Cli | 5 | 0 | 0 |
| Codec | 5 | 2 | 1 |
| Collections | 5 | 5 | 1 |
| Gson | 5 | 1 | 0 |
| Math | 5 | 1 | 2 |
| Total | 25 | 9 (36%) | 4 (16%) |
Illustrative example: Math-105. Math-105 illustrates a bug exposed by both tools. The affected method, SimpleRegression.getSumSquaredErrors, returns the sum of squared errors (SSE) of a regression model. Its documentation specifies that negative results caused by rounding are returned as zero, and that NaN is returned when insufficient observations have been added to estimate the model. With the bug-revealing tests excluded, both tools inferred result >= 0.0 at the method's exit. Oca also inferred the following entry property:
Double.isNaN(getSumSquaredErrors()) || getSumSquaredErrors() >= 0
This entry property calls getSumSquaredErrors itself; because the method is side-effect-free, this constrains the value it is about to return. Oca's suppression of nested invariant evaluation (section 4.2.3) prevents these calls from recursively evaluating the same invariant.
The buggy implementation computes sumYY - sumXY * sumXY / sumXX. Although an SSE is non-negative in exact arithmetic, floating-point cancellation produces approximately for the bug-revealing input, contradicting the method's documentation and falsifying all three candidates. The fix wraps the expression in Math.max(0d, ...), returning zero for the same input. All three candidates satisfied the fixed-version check of our procedure, so both tools expose the bug. Oca additionally inferred a property that explicitly permits the documented NaN outcome: under Java's expression semantics, the two exit properties reject NaN, whereas the entry property accepts it. This property combines a project-specific method call with a disjunction, which template-free inference makes possible, and so accounts for both a nonnegative SSE and the documented outcome when the model cannot yet be estimated.
5.5 RQ6: Performance
Unlike Daikon, Oca uses a new and relatively expensive component: the LLM that proposes candidate invariants. But it evaluates far fewer candidate invariants and records no execution traces to disk. So, it is not obvious which of the two systems is more expensive.
We reused the Daikon and Oca runs performed for RQ3 (section 5.2) rather than making dedicated runs, so that the cost comparison reflects the exact executions whose expressiveness results are reported there. For each project and each tool, we recorded the wall-clock time and disk usage of the invariant-inference run, computed differently for each tool to match what each actually produces. For Daikon, time is the sum of the wall-clock time spent running Chicory, Daikon's instrumentation and trace-collection tool, and the wall-clock time spent running Daikon itself to infer invariants from Chicory's traces. Disk usage is the total size of Chicory's dtrace files, together with the log files in which Daikon reports inferred invariants. For Oca, time is the total wall-clock time for a single end-to-end run of the tool on a project, including the LLM querying phase (remote calls to the OpenAI API), filtering, compilation, and test-suite execution. Disk usage is the size of the copied, instrumented version of the project plus the output and the log files Oca produces.
5.5.1 RQ6 Results. Table 8 shows the results. The full-trace attempts of the three † projects cost far more before failing: Netty's took 59.8 hours to collect and occupied 2.3 TB before Daikon failed on it after 10.5 hours; libGDX's Chicory run was stopped at the 72-hour walltime limit with 1.9 TB of partial trace, on which Daikon failed after 23.9 hours; and Dubbo's Chicory run likewise did not complete, leaving a 280 GB partial trace on which Daikon failed after 69.1 hours. Oca also incurs a cost that Daikon does not: LLM token usage, since it sends a prompt for each program point. Across all 11 projects, it used about 107 million tokens, costing about $55.
Overall, the results support a performance advantage for Oca. It was faster than Daikon on both subject sets (389.4 versus 1,961.6 minutes on our benchmarks and 176.2 versus 855.0 on Defects4J) and used less disk (26.32 versus 780.49 GB and 0.30 versus 46.60 GB), with one exception (Spring). Time was mixed per project: Daikon was faster on Apollo, Dubbo, Spring, and Math, while Oca was much faster where Daikon's runs were long, such as Netty, libGDX, and Codec. Oca's run time is also more predictable: it scales roughly linearly with the number of program points (r = 0.90), whereas Daikon's run time is uncorrelated with program-point count (r = -0.01).
Table 8: Time and disk usage per project, on the same runs used to answer RQ3.
| Project | Time [min] | Disk [GB] | ||
|---|---|---|---|---|
| Daikon | Oca | Daikon | Oca | |
| Benchmark projects (prompt/context study) | ||||
| Apollo | 8.1 | 14.4 | 2.56 | 0.38 |
| Dubbo† | 23.9 | 129.9 | 1.34 | 0.78 |
| full (failed) | - | - | 280.00* | - |
| Netty† | 1,549.7 | 60.0 | 0.76 | 0.73 |
| full (failed) | - | - | 2,300.00 | - |
| Hudi | 27.1 | 11.3 | 683.30 | 19.00 |
| libGDX† | 350.6 | 83.0 | 90.32 | 2.81 |
| full (failed) | - | - | 1,900.00* | - |
| Spring | 2.2 | 90.8 | 2.21 | 2.62 |
| Total | 1,961.6 | 389.4 | 780.49 | 26.32 |
| Defects4J projects (fixed versions) | ||||
| Cli | 10.0 | 9.1 | 0.60 | 0.02 |
| Codec | 570.0 | 14.5 | 14.20 | 0.03 |
| Collections | 240.0 | 101.1 | 26.30 | 0.13 |
| Gson | 20.0 | 10.3 | 3.10 | 0.03 |
| Math | 15.0 | 41.2 | 2.40 | 0.09 |
| Total | 855.0 | 176.2 | 46.60 | 0.30 |
†Daikon ran on a sampled trace; the full (failed) row gives the size of the full-trace attempt, excluded from the totals.
*Partial trace at the 72-hour limit.
6 Limitations and Threats to Validity
Internal Validity. Oca only guarantees that a held invariant is side-effect-free modulo the project's test suite (section 4.2.2). Similarly, our flaky-test filtering (section 3.1) may miss some flaky tests, so a few test failures we attribute to an injected candidate could instead reflect residual flakiness. Our prompt-strategy and context-configuration selection (section 3) used a single LLM (gpt-4.1-mini); results could differ for other models. This selection also assumed that the two factors are independent; an untested combination could outperform the one we selected.
External Validity. We evaluated only Java programs, so our findings may not generalize to other languages. Our selection criteria favored mature, popular, and active GitHub repositories (section 3.1), so the six benchmark projects may not represent smaller or less active projects. We selected the prompt strategy and context configuration on these same six projects (section 3), so results on them do not independently confirm that this configuration is optimal; hence we also evaluate on Defects4J (section 5.1). Our literature review (section 3.3) covered one edition of each of four venues and searched titles and abstracts, so it may miss papers that use an LLM without saying so there, and its prevalence counts reflect recent work at these venues, not the whole field.
Construct Validity. For three benchmark projects, Daikon's invariant counts come from traces sampled with Chicory's -sample-start option, because full runs exceeded our cluster's 72-hour walltime limit on two projects and crashed Daikon on the third (section 5.2). Sampling can change which invariants Daikon reports, so these counts are not directly comparable to those from full traces. Our expressiveness metric (section 5.2) counts an invariant as expressive only if it relates more than three variables or invokes a project-specific method; by design, this underestimates Oca's expressiveness, since it ignores other forms of semantic richness. Our false-positive analysis (section 5.3) relies on manual, blinded judgments of semantic validity by two reviewers; although we report Cohen's , such judgments remain subjective. One author coded the context taxonomy (fig. 3); the others reviewed the codes and resolved disagreements by discussion, but we did not measure inter-rater agreement, so the codes may reflect one coder's interpretation.
7 Related Work
Oca is a neuro-symbolic invariant detector, so we discuss prior symbolic and neural approaches.
Augmenting Dynamic Invariant Detection. We compare Oca to Daikon [15], the seminal dynamic invariant detector, which falsifies template invariants on test-suite traces. Daikon is the usual baseline for follow-up work [10, 26, 29, 30, 35]. Oca makes the invariants a Daikon-like system can detect more expressive. Prior work toward this goal mainly designed new templates [14, 22, 28] or sped up Daikon to evaluate more complex invariants [13, 17, 36]. Other approaches increase expressiveness differently. DIG [33] infers polynomial invariants by treating traces as high-dimensional numerical vectors; follow-ups check candidates with symbolic execution [31, 32] but are still limited to numerical invariants. Like Oca, DIDUCE [18] checks invariants as the program runs, but its invariants are more restrictive than Daikon's: bitmasks recording which bits of one tracked expression stayed constant, and their values.
Neuro-symbolic Dynamic Invariant Detection. ClassInvGen [43] uses LLMs to propose class-level invariants for C++ data structures, not method pre- and postconditions like Oca. It co-generates invariants and test inputs, discarding candidates that fail those tests; Oca instead uses the project's existing test suite. ClassInvGen prompts the LLM for side-effect-free checks but describes no mechanism for handling side effects, nontermination, or nested evaluation during checking, which Oca handles.
Balestra et al. [7] use LLM-generated tests to falsify SpecFuzzer's dynamically inferred assertions, discarding up to 12% of the invalid ones and improving precision by up to 7% without affecting recall. This orthogonal work improves the test inputs that dynamic inference relies on, not the candidate invariants, and could be combined with Oca to further reduce false positives.
Pei et al. [35] fine-tuned a model on Daikon-generated invariants to predict invariants from source code, without running the program. Against Daikon's output on 200 executions per program, it reaches 86% precision and recall but outperforms Daikon only when Daikon observes five or fewer executions. Because it imitates Daikon, its invariants stay within Daikon's templates; Oca instead prompts an off-the-shelf LLM for arbitrary invariants, including calls to project-specific methods. Their model is not public, so we could not compare against it.
Neural Invariant Detection. Pre-LLM neural approaches learned loop invariants directly. For example, Code2Inv [41] trains a graph neural network over a program graph by reinforcement learning, with a verifier supplying the reward. Others [16, 34, 38] differ in details, but all target inductive loop invariants over small numeric benchmarks with a sound verifier as an oracle. Oca instead infers method pre- and postconditions for real-world programs, validated against real executions.
In prior work, LLMs infer specifications and loop invariants for program verifiers. Clause2Inv [8] infers loop invariants with a generate-combine-check framework, and SpecGen [26] generates formal specifications, mutating candidates that fail to verify; many others pair an LLM with a verifier [9, 24, 27, 37, 45–47]. Like the neural approaches above, these tools accept a candidate only if it passes a static check, whereas Oca accepts it if no test-suite execution falsifies it.
Another study [12] used LLMs to turn method documentation into postconditions that would detect 64 of 525 Defects4J bugs, but did not build an invariant detector like Oca.
8 Conclusion
This paper presented Oca, a dynamic invariant detector that obtains candidate invariants from an LLM instead of a fixed template grammar. Because each candidate is an arbitrary Java expression, Oca can infer invariants that relate many variables and call project-specific methods, which Daikon cannot express by design. Compared with Daikon, Oca's invariants are more expressive, more often valid, more useful, and cheaper to obtain. These results suggest that LLM-proposed candidates can overcome the expressiveness limits of template-based invariant detection.
Data Availability
Our replication package [2] contains Oca's implementation, complete prompts, and the data and scripts to reproduce all experiments. Upon acceptance, we will archive it on Zenodo with a DOI.
References
[1] Juan C Alonso, Sergio Segura, and Antonio Ruiz-Cortés. 2023. AGORA: automated generation of test oracles for REST apis. In International Symposium on Software Testing and Analysis (ISSTA). 1018–1030.
[2] Anonymous. 2026. Replication Package for "Template-Free Dynamic Invariant Detection". https://anonymous.4open.science/r/template-free-invariant-detection-replication-F43D/.
[3] Apache Dubbo. 2026. Apache Dubbo. https://github.com/apache/dubbo. Accessed: 2026-09-10.
[4] Apache Hudi. 2026. Apache Hudi. https://github.com/apache/hudi. Accessed: 2026-09-10.
[5] Apollo Config. 2026. Apollo. https://github.com/apolloconfig/apollo. Accessed: 2026-09-10.
[6] Henry Baker. 1990. Unify and Conquer (Garbage, Updating, Aliasing, ...). In LFP '90: Proceedings of the 1990 ACM Conference on LISP and Functional Programming. Nice, France, 218–226.
[7] Agustín Balestra, Agustín Nolasco, Facundo Molina, Diego Garbervetsky, Renzo Degiovanni, and Nazareno Aguirre. 2026. Improving Dynamic Specification Inference with LLM-Generated Counterexamples. In Proceedings of the IEEE International Conference on Software Testing, Verification and Validation (ICST).
[8] Weining Cao, Guangyuan 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.
[9] Saikat Chakraborty, Shuvendu K. Lahiri, Sarah Fakhoury, Madanlal Musuvathi, Akash Lal, Aseem Rastogi, Aditya Senthilnathan, Rahul Sharma, and Nikhil Swamy. 2023. Ranking LLM-Generated Loop Invariants for Program Verification. In Findings of the Association for Computational Linguistics: EMNLP 2023.
[10] Christoph Csallner, Nikolai Tillmann, and Yannis Smaragdakis. 2008. DySy: Dynamic symbolic execution for invariant inference. In ICSE 2008, Proceedings of the 30th International Conference on Software Engineering. Leipzig, Germany, 281–290. doi:10.1145/1368088.1368127
[11] Ozren Dabic, Emad Aghajani, and Gabriele Bavota. 2021. Sampling projects in GitHub for MSR studies. In MSR. 560–564.
[12] Madeline Endres, Sarah Fakhoury, Saikat Chakraborty, and Shuvendu K. Lahiri. 2024. Can large language models transform natural language intent into formal method postconditions? Proceedings of the ACM on Software Engineering 1, FSE (2024), 1889–1912.
[13] Michael D. Ernst, Adam Czeisler, William G. Griswold, and David Notkin. 2000. Quickly detecting relevant program invariants. In ICSE 2000, Proceedings of the 22nd International Conference on Software Engineering. Limerick, Ireland, 449–458. doi:10.1109/icse.2000.870435
[14] Michael D. Ernst, William G. Griswold, Yoshio Kataoka, and David Notkin. 1999. Dynamically discovering pointer-based program invariants. Technical Report UW-CSE-99-11-02. U. Wash. Dept. of Comp. Sci. & Eng., Seattle, WA. Revised Mar. 17, 2000. [15] Michael D. Ernst, Jeff H. Perkins, Philip J. Guo, Stephen McCamant, Carlos Pacheco, Matthew S. Tschantz, and Chen Xiao. 2007. The Daikon system for dynamic detection of likely invariants. Science of Computer Programming 69, 1-3 (Dec. 2007). 35-45. doi:10.1016/j.scico.2007.01.015 [16] Grigory Fedyukovich, Samuel J. Kaufman, and Rastislav Bodik. 2017. Sampling invariants from frequency distributions. In Formal Methods in Computer-Aided Design (FMCAD). IEEE, 100-107. [17] Philip J. Guo, Jeff H. Perkins, Stephen McCamant, and Michael D. Ernst. 2006. Dynamic inference of abstract types. In ISSTA 2006, Proceedings of the 2006 International Symposium on Software Testing and Analysis. Portland, ME, USA, 255-265. doi:10.1145/1146238.1146268 [18] Sudheendra Hangal and Monica S. Lam. 2002. Tracking down software bugs using automatic anomaly detection. In ICSE 2002, Proceedings of the 24th International Conference on Software Engineering. Orlando, Florida, 291-301. doi:10.1109/icse.2002.1007976 [19] Dominik Helm, Florian Kübler, Michael Eichberg, Michael Reif, and Mira Mezini. 2018. A unified lattice model and framework for purity analyses. In Proceedings of the 33rd ACM/IEEE International Conference on Automated Software Engineering (ASE). 340-350. doi:10.1145/3238147.3238226 [20] Kaicheng Huang, Fanyu Wang, Yutan Huang, and Chetan Arora. 2025. Prompt engineering for requirements engineering: A literature review and roadmap. In 2025 IEEE 33rd International Requirements Engineering Conference Workshops (REW). IEEE, 548-557. [21] René Just, Darioush Jalali, and Michael D. Ernst. 2014. Defects4J: A database of existing faults to enable controlled testing studies for Java programs. In ISSTA 2014, Proceedings of the 2014 International Symposium on Software Testing and Analysis. San Jose, CA, USA, 437-440. doi:10.1145/2610384.2628055 Tool demo. [22] Nadya Kuzmina, John Paul, Ruben Gamboa, and James Caldwell. 2008. Extending dynamic constraint detection with disjunctive constraints. In WODA 2008: Workshop on Dynamic Analysis. Seattle, WA, USA, 57-63. doi:10.1145/1401827.1401839 [23] Wing Lam, Reed Oei, August Shi, Darko Marinov, and Tao Xie. 2019. iDFlakies: A framework for detecting and partially classifying flaky tests. In 2019 12th ieee conference on software testing, validation and verification (icst). IEEE, 312-322. [24] Tianchi Li, Zhenyu Yan, Junhao Liu, Peng Di, and Xin Zhang. 2026. Guiding LLM-based Loop Invariant Synthesis via Feedback on Local Reasoning Errors. ACM Transactions on Programming Languages and Systems (2026). doi:10.1145/3806652 [25] libGDX. 2026. libGDX. https://github.com/libgdx/libgdx. Accessed: 2026-09-10. [26] Lezhi Ma, Shangqing Liu, 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). IEEE Computer Society, 666-666. [27] Md Rakib Hossain Misu, Cristina V. Lopes, Iris Ma, and James Noble. 2024. Towards AI-assisted synthesis of verified Dafny methods. Proceedings of the ACM on Software Engineering 1, FSE (2024). [28] Facundo Molina, Marcelo d'Amorim, and Nazareno Aguirre. 2022. Fuzzing Class Specifications. In International Conference on Software Engineering (ICSE). [29] Facundo Molina, Renzo Degiovanni, Pablo Ponzio, Germán Regis, Nazareno Aguirre, and Marcelo Frias. 2019. Training binary classifiers as data structure invariants. In International Conference on Software Engineering (ICSE). IEEE, 759-770. [30] Facundo Molina, Pablo Ponzio, Nazareno Aguirre, and Marcelo Frias. 2021. EvoSpex: An Evolutionary Algorithm for Learning Postconditions. In International Conference on Software Engineering (ICSE). doi:10.1109/ICSE43902.2021.00112 [31] ThanhVu Nguyen, Timos Antonopoulos, Andrew Ruef, and Michael Hicks. 2017. Counterexample-Guided Approach to Finding Numerical Invariants. In Joint Meeting on Foundations of Software Engineering (ESEC/FSE). [32] ThanhVu Nguyen, Matthew B. Dwyer, and Willem Visser. 2017. SymInfer: Inferring Program Invariants Using Symbolic States. In International Conference on Automated Software Engineering (ASE). [33] ThanhVu Nguyen, Deepak Kapur, Westley Weimer, and Stephanie Forrest. 2014. DIG: A dynamic invariant generator for polynomial and array invariants. ACM Transactions on Software Engineering and Methodology (TOSEM) 23, 4 (2014), 1-30. [34] Saswat Padhi, Rahul Sharma, and Todd Millstein. 2017. LoopInvGen: A loop invariant generator based on precondition inference. arXiv preprint arXiv:1707.02029 (2017). [35] Kexin Pei, David Bieber, Kensen Shi, Charles Sutton, and Pengcheng Yin. 2023. Can large language models reason about program invariants?. In International Conference on Machine Learning. PMLR, 27496-27520. [36] Jeff H. Perkins and Michael D. Ernst. 2004. Efficient incremental algorithms for dynamic detection of likely invariants. In FSE 2004: Proceedings of the ACM SIGSOFT 12th Symposium on the Foundations of Software Engineering. Newport
Beach, CA, USA, 23–32. doi:10.1145/1029894.1029901
[37] Muhammad A. A. Pirzada, Giles Reger, Ahmed Bhayat, and Lucas C. Cordeiro. 2024. LLM-Generated Invariants for Bounded Model Checking Without Loop Unrolling. In Proceedings of the 39th IEEE/ACM International Conference on Automated Software Engineering (ASE).
[38] Gabriel Ryan, Justin Wong, Jianan Yao, Ronghui Gu, and Suman Jana. 2020. CLN2INV: Learning loop invariants with continuous logic networks. In International Conference on Learning Representations (ICLR).
[39] Pranab Sahoo, Ayush Kumar Singh, Sriparna Saha, Vinija Jain, Samrat Mondal, and Aman Chadha. 2024. A systematic survey of prompt engineering in large language models: Techniques and applications. arXiv preprint arXiv:2402.07927 (2024).
[40] S Schulhoff, M Ilie, N Balepur, K Kahadze, A Liu, C Si, Y Li, A Gupta, H Han, S Schulhoff, et al. 2025. The prompt report: A systematic survey of prompt engineering techniques (arXiv: 2406.06608). arXiv.
[41] Xujie Si, Hanjun Dai, Mukund Raghothaman, Mayur Naik, and Le Song. 2018. Learning loop invariants for program verification. In Advances in Neural Information Processing Systems (NeurIPS).
[42] Spring. 2026. Spring Framework. https://github.com/spring-projects/spring-framework. Accessed: 2026-09-10.
[43] Chuyue Sun, Viraj Agashe, Saikat Chakraborty, Jubi Taneja, Clark Barrett, David Dill, Xiaokang Qiu, and Shuvendu K Lahiri. 2025. ClassInvGen: Class invariant synthesis using large language models. In International Symposium on AI Verification. Springer, 64–96.
[44] The Netty Project. 2026. Netty. https://github.com/netty/netty. Accessed: 2026-08-28.
[45] Shubham Ugare, Tarun Suresh, Sasa Misailovic, and Julien Vanegue. 2026. Fun2spec: Code Contract Synthesis At Scale. In Companion Proceedings of the ACM International Conference on the Foundations of Software Engineering (FSE), Industry Papers.
[46] Anjiang Wei, Tarun Suresh, Tianran Sun, Haoze Wu, Ke Wang, and Alex Aiken. 2025. InvBench: Can LLMs Accelerate Program Verification with Invariant Synthesis? arXiv:2509.21629.
[47] Guangyuan Wu, Weining Cao, Yuan Yao, Hengfeng Wei, Taolue Chen, and Xiaoxing Ma. 2024. LLM Meets Bounded Model Checking: Neuro-symbolic Loop Invariant Inference. In Proceedings of the 39th IEEE/ACM International Conference on Automated Software Engineering (ASE).
[48] Yuan Xia, Deepayan Sur, Aabha Shailesh Pingle, Jyotirmoy V Deshmukh, Mukund Raghothaman, and Srivatsan Ravi. 2025. Discovering Likely Invariants for Distributed Systems Through Runtime Monitoring and Learning. In International Conference on Verification, Model Checking, and Abstract Interpretation. Springer, 3–25.
[49] Mingyue Yuan, Jieshan Chen, Zhenchang Xing, Aaron Quigley, Yuyu Luo, Tianqi Luo, Gelareh Mohammadi, Qinghua Lu, and Liming Zhu. 2025. DesignRepair: Dual-stream design guideline-aware frontend repair with large language models. In 2025 IEEE/ACM 47th International Conference on Software Engineering (ICSE). IEEE, 2483–2494.
[50] Andreas Zeller and Ralf Hildebrandt. 2002. Simplifying and Isolating Failure-Inducing Input. IEEE Transactions on Software Engineering 28 (2002), 183–200. doi:10.1109/32.988498