Skip to content

False error: a counter updated in a loop is only known by the loop condition (for (int i = 0; i < 10; i++) does not prove i >= 0) #537

Closed

Description

@CatarinaGamboa

Summary

A local variable that a loop body updates is known inside the body only through the loop condition. Everything else that holds for it (its initial value, and that the update keeps it in range) is forgotten, so an ordinary counter such as for (int i = 0; i < 10; i++) is not known to be >= 0 inside the loop.

Minimal reproducer

import liquidjava.specification.Refinement;

public class G {
    static int use(@Refinement("_ >= 0") int x) { return x; }

    static void fill() {
        for (int i = 0; i < 10; i++) {
            use(i);   // Refinement Error
        }
    }
}

Output on 0.0.38:

Refinement Error: found `i < 10` but expected `i >= 0`
5 |     static void fill() {
6 |         for (int i = 0; i < 10; i++) {
7 |             use(i);
  |             ^^^^^^^
8 |         }
9 |     }
 --> Counterexample: `i == -1`

Expected: Correct! Passed Verification. The counterexample i == -1 cannot happen: i starts at 0 and only grows.

The same happens with a while loop and an accumulator:

int total = 0;
while (total < 1024) {
    use(total);          // found `total < 1024` but expected `total >= 0`
    total = total + 1;
}

Workaround

Annotating the variable gives the verifier the invariant, and the loop is then accepted:

@Refinement("_ >= 0") int total = 0;

The message does not suggest this, and for a for loop counter it is unusual to write.

Why it matters

This is the standard way to fill a buffer from a stream:

int total = 0;
while (total < limit) {
    int n = in.read(buf, total, limit - total);   // off is refined with _ >= 0
    if (n < 0) break;
    total += n;
}

With a spec that refines read(byte[] b, int off, int len) with off >= 0, this loop is rejected. In a small experiment where coding agents implemented a method against such a spec, 23 of 30 implementations that behaved correctly were rejected for this loop alone, and with the verifier available every agent needed one or more extra rounds to rewrite correct code.

Possible directions: keep i >= c (or <= c) for a variable that starts at a constant and is only incremented (decremented) in the body; or, when the error is on a variable assigned in an enclosing loop, say in the message that the loop forgets what was known about it and that a @Refinement on the variable's declaration states the invariant.

Related: #479 (the list's ghost is also forgotten at the loop head; it notes the missing i >= 0 in passing), #306 (loop condition assumed in the body, fixed).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions