Hmbown/CodeWhale · error · RuntimeContractError

metric ` ` must be a non-negative integer

Error message

{kind} metric `{dotted}` must be a non-negative integer

What it means

metric_value reads a dotted metric path (e.g. `system_prompt.modes.plan.system_prompt_bytes`) from a receipt or budget document and enforces that every tracked metric is a non-negative integer. It rejects missing values (via required_value), booleans (a bool is an int in Python but not a valid metric), non-int types, and negative numbers. This guards the budget comparison math from floats, strings, and signed garbage.

Solutions

  1. Locate the offending dotted path printed in the message and set it to a non-negative integer in the receipt/budget JSON.
  2. Re-run `python3 scripts/measure-runtime-contract.py` to regenerate the receipt instead of hand-editing values.
  3. Check that the value is not a float/string in the emitting tool (e.g. cast int(...) in the measurement script).
  4. If the metric schema changed, update METRICS in the checker and regenerate both receipt and budget together.

Example fix

// before (receipt JSON)
"system_prompt_bytes": 12804.0
// after
"system_prompt_bytes": 12804
Defensive patterns

Strategy: validation

Validate before calling

def check_metrics(doc: dict, paths) -> None:
    for path in paths:
        node = doc
        for key in path:
            node = node[key]
        if isinstance(node, bool) or not isinstance(node, int) or node < 0:
            raise ValueError(f"{'.'.join(path)} must be a non-negative int, got {node!r}")

Type guard

def is_metric(value: object) -> bool:
    return isinstance(value, int) and not isinstance(value, bool) and value >= 0

Try / catch

try:
    receipt = json.loads(proc.stdout)
    check_metrics(receipt, metric_paths)
except (json.JSONDecodeError, KeyError, ValueError) as e:
    print(f"invalid receipt: {e}", file=sys.stderr)

Prevention

When it happens

Trigger: Calling metric_value via validate_identity_structure, compare, or budget_from_receipt on a document where a metric at a METRICS path is a bool, float, string, negative int, or missing; e.g. a receipt produced by a broken or hand-edited measurement.

Common situations: A measurement script emitted a float (e.g. 1234.0) or null for a metric; someone hand-edited the budget JSON with a string value; a schema change renamed a key so required_value surfaces through the same check; JSON produced by a non-Python tool used `true` for a counter.

Understand the failure class

Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.

Related errors


AI-assisted analysis of Hmbown/CodeWhale@433685b202 (2026-09-15). Data as JSON: /api/errors/8ac95eb70e134b6e. Report an issue: GitHub.

Appendix: source

Thrown at scripts/check-runtime-contract-budget.py:306

    representative = budget.get("representative_context")
    fixture_id = (
        representative.get("fixture_id")
        if isinstance(representative, dict)
        else None
    )
    if fixture_id != REPRESENTATIVE_FIXTURE_ID:
        raise RuntimeContractError(
            "budget metric `representative_context.fixture_id` must be "
            f"`{REPRESENTATIVE_FIXTURE_ID}`, got {fixture_id!r}"
        )
    validate_identity_structure(budget, "budget")


def metric_value(document: dict[str, Any], path: MetricPath, kind: str) -> int:
    value = required_value(document, path, kind)
    dotted = ".".join(path)
    if isinstance(value, bool) or not isinstance(value, int) or value < 0:
        raise RuntimeContractError(
            f"{kind} metric `{dotted}` must be a non-negative integer"
        )
    return value


def compare(
    receipt: dict[str, Any], budget: dict[str, Any]
) -> tuple[list[MetricResult], list[MetricResult]]:
    """Return (increases, decreases) as path/label/current/ceiling tuples."""
    validate_receipt(receipt)
    validate_budget(budget)
    for path, label in IDENTITIES:
        receipt_value = required_value(receipt, path, "receipt")
        budget_value = required_value(budget, path, "budget")
        if receipt_value != budget_value:
            detail = ""
            if isinstance(receipt_value, list) and isinstance(budget_value, list):
                added = [str(item) for item in receipt_value if item not in budget_value]

View on GitHub (pinned to 433685b202)