Skip to main content

Runtime Code Contracts Cut Agent Thinking by 14.4% at 32/32 Parity (N=3)

Updated 6 min readMarkdown

💡 AI Labo Benchmark Series — Experiment E54 (Design-by-Contract Runtime Sensor)

Part of our controlled benchmark series testing AI coding agent harnesses inside network-isolated Proxmox VMs (N=3 counterbalanced AB/BA/AB trials, temperature=0.7, 3-UID grading, 90% prefix-cache cost accounting).

Representative unit tests (ex_01..ex_08) check specific happy-path examples, while formal verification tools like Lean demand heavy upfront proof engineering. Anthony Rimet (Marmelab, 2026) proposed Code Contracts—runtime Requires, Ensures(old, new), and Invariant assertions—as the practical halfway house.

We benchmarked Design-by-Contract Runtime Sensors (18 probes) against Example Unit Testing (8 probes) on a 4-module enterprise expense-splitting ledger (models/gemini-4-carbon, thinkingLevel="MEDIUM", N=3). Under explicit specs, both modes hit 32/32—yet runtime contracts yielded a subtle cognitive payoff.


TL;DR — Key Empirical Findings

  • 1. Explicit-Spec Ceiling Parity (32.00 ± 0.00 / 32 in Both Modes): Across 32 unseen grading tests (12 example + 20 contract/invariant), both Baseline (Example Unit Testing) and Candidate (DbC Runtime Sensor) passed 32.00 ± 0.00 / 32 (100.0%) in all 3 trials (example_green_with_silent_bugs = 0). When TICKET.md spells out Requires/Ensures/Invariants, gemini-4-carbon (MEDIUM) satisfies them on its initial edit.
  • 2. -14.37% Internal Thinking Tokens via Immediate Contract Proof: Receiving structured 18/18 contract verification inside edit_and_verify eliminated pre-submit self-doubt. Average thinking tokens fell -14.37% (19,791.3 ➔ 16,947.0; Trial 3's final submit turn alone dropped from 6,396 to 1,726 thinking tokens, -73%).
  • 3. -3.37% Effective Cached Cost & -44.3% Lower Cost Variance: Higher implicit cache hits (+48.3%, 24,682.3 ➔ 36,594.7) plus lower thinking spend edged effective cached cost down from `$0.4218 ± $0.0795` to `$0.4076 ± $0.0443` (-3.37%, SD -44.3%), with a +29.78% mean latency trade-off (388.52s ➔ 504.21s) driven by API round-trip variance.
Metric (N=3 Trials, Mean ± SD) Baseline: Example Unit Testing (8) Candidate: DbC Runtime Sensor (18) Delta / Effect
Hidden Grading Suite (32 Cases) 32.00 ± 0.00 (100.0%) 32.00 ± 0.00 (100.0%) 100% tie (12 example + 20 contract)
Silent Bugs Passing Examples 0.00 ± 0.00 0.00 ± 0.00 Zero silent invariant leaks
LLM Calls (model_calls) 3.33 ± 0.58 ([3–4]) 3.67 ± 0.58 ([3–4]) +0.33 calls (+10.0%)
Thinking Tokens (thoughts) 19,791.3 ± 3,522.9 16,947.0 ± 1,622.6 -14.37% (-2,844.3 tokens)
Cached Input Tokens (cached) 24,682.3 36,594.7 +48.26% higher cache reuse
Total Tokens (total_tokens) 94,883.7 ± 29,119.9 105,071.3 ± 26,550.8 +10.74% (+10,187.7 tokens)
Elapsed Time (elapsed_seconds) 388.52s ± 133.76s 504.21s ± 183.08s +29.78% (local DbC check < 1s)
Effective Cached Cost (90% OFF) `$0.4218 ± $0.0795` `$0.4076 ± $0.0443` -$0.0142 (-3.37%, SD -44.3%)
List-Price Upper Bound (No Cache) `$0.4663 ± $0.0990` `$0.4735 ± $0.0828` +1.54% (`+$0.0072`)
Output Cap Hits (capped_termination) 0 / 3 0 / 3 Zero truncation

1. Experiment Design & Architecture

+-----------------------------------------------------------------------+
| Proxmox VM258 (0 NICs, gemini-4-carbon MEDIUM, temp=0.7, N=3 AB/BA)   |
| Task: 4-Module Expense-Splitting Ledger (12 Example + 20 DbC Tests)   |
|                                                                       |
| Shared Start: Identical TICKET.md (Requires/Ensures/Invariants)       |
|   |-- Baseline (Example Unit Testing): runs ex_01..ex_08 (8 checks)   |
|   |     -> Returns "8/8 PASSED" -> agent spends extra thinking        |
|   |        double-checking unprobed invariants -> $0.4218 eff.        |
|   |-- Candidate (Design-by-Contract Sensor):                          |
|         runs 8 (old, new) immutability wrappers + 10 invariant probes |
|         -> Emits [REQUIRES/ENSURES/INVARIANT_VIOLATED] or "18/18 PASS"|
|         -> Immediate epistemic proof (-14.4% thoughts) -> $0.4076 eff.|
+-----------------------------------------------------------------------+

Notice the anti-strawman symmetry: both modes received the exact same TICKET.md specification and read-only contracts, and a silent oracle (check_silent_dbc_oracle) ran behind the scenes on both arms without leaking signals to Baseline.


2. Drop-In Implementation Recipe: @code_contract Sensor

Wrap state-mutating operations with deep-copied old snapshots and structured [REQUIRES/ENSURES/INVARIANT_VIOLATED] diagnostics inside your local test runner:

import copy
from functools import wraps
from typing import Callable


def code_contract(
    requires: Callable[..., bool],
    ensures: Callable[[object, object, object], bool],
    invariant: Callable[[object], bool],
):
    """Enforces Requires, Ensures(old, new, result), and Group Invariants."""

    def decorator(fn):
        @wraps(fn)
        def wrapper(state, *args, **kwargs):
            if not requires(state, *args, **kwargs):
                raise AssertionError(f"[REQUIRES_VIOLATED] {fn.__name__} precondition failed")
            old_snapshot = copy.deepcopy(state)
            result = fn(state, *args, **kwargs)
            if not ensures(old_snapshot, state, result):
                raise AssertionError(f"[ENSURES_VIOLATED] {fn.__name__} postcondition failed")
            if not invariant(state):
                raise AssertionError(f"[INVARIANT_VIOLATED] {fn.__name__} broke group invariant")
            return result

        return wrapper

    return decorator
  • Why this works: Capturing old_snapshot verifies non-mutation and conservation laws (sum(net_balances) == 0, Hamilton remainder debt caps, atomic rollback on failure) automatically—and gives the LLM crisp proof to stop overthinking before final submission.

3. Threats to Validity & When NOT to Use This

  1. Explicit-Spec Ceiling Effect (32/32 Tie): Because TICKET.md documented every invariant explicitly, gemini-4-carbon (MEDIUM) satisfied them on Turn 2 in both modes (example_green_with_silent_bugs = 0). On underspecified legacy repos or smaller Flash models, Baseline's 8-example suite is far more likely to pass silently broken invariants (verified deterministically in tests/verify_e54_local.py).
  2. Closed 4-Module Scope & Latency Jitter (N=3): Tested on self-contained Python finance modules; distributed DB invariants are out of scope. Also, local DbC execution took < 1s, so the +115.70s elapsed difference reflects upstream API SSE latency variance across N=3 trials.
  3. When Baseline Is Enough: On single-turn frontier-model batches with crystal-clear specs, run all 18 compact contract probes inside one single-shot verify sensor rather than adding extra verification round-trips.
📋 Experiment Metadata & Reproducibility
  • Experiment ID: E54 (C050 / Marmelab Code Contracts / Benchmark v2.1)
  • Run ID: e54-20261119-vm258-01 (N=3 trials: AB ➔ BA ➔ AB, temperature=0.7)
  • Sandbox Environment: Proxmox Isolated VM VM258 (0 NICs, PrivateNetwork=yes, 3-UID isolation: labexp54 / labrunner54 / labjudge54)
  • Model & Thinking Level: models/gemini-4-carbon (thinkingLevel="MEDIUM")
  • Cost Accounting: Google 90% implicit prefix-cache discount (effective_cached_micro_usd) as primary metric; list-price upper bound reported alongside.

Discussion: Do your test sensors check Ensures(old, new) state-transition invariants (like conservation of balance and rollback atomicity), or only final return values?

🔗 Continue Reading the Series

No comments yet. Be the first to comment.