gdp-wired

Languages · gdp-wired 0.43

Prove the rules already in your code.

One comment over your code. One command.

The rules already in your code are read with nothing to write: the language, the class or functions, and what other code is answered or left out are inferred. The command prints the rule in your code’s names, checks it against your code by running both, proves the laws you state as comments, proposes laws nobody wrote, and prints the run that breaks a law, as calls of your code.

One command

Point the CLI at a file, a Go package, a Rust crate or a Swift package. Nothing to install first: npx fetches gdp-wired-cli, which brings gdp-wired and the TypeScript compiler. The language is the file’s; the reader it needs is your language’s own toolchain, already on your machine if you build that code.

$ npx gdp-wired-cli check src/limiter.py

Or a .rb .ex .java .kt .go .rs .swift .c .cpp .ts file, a Go package, a Rust crate, a Swift package, a directory of files, or several at once.

  • What it prints. The rule in your code’s names, how it was checked against your code, every statement it inferred about other code, each law you stated (proven, broken with the run, unknown, or not read with why), and laws nobody wrote, each with the comment that states it (--no-propose turns those off).
  • Exit codes. 0 when no stated law is broken, 1 when one is, 2 when one couldn’t be checked (the rule refused, or the law not read). So it gates a merge: uses: monotykamary/gdp-wired@main with paths: runs it in CI.
  • Flags. --entry X, --methods a,b, --failures kept, --on-error discard, --from any, --clock s|ms, --ms 10000 (the prover’s time per law), --cert <dir> (each proven law’s certificate), --json. Each one but the last three can live in gdp.toml instead.

Writing a law

A law is one comment over the code’s names: gdp: law <name>: <expression>. On the line above a method it is a law of that method’s step; above a class, an Effect service’s make effect or an XState machine, of every step. Where the language has annotations, the law can be one.

LanguageAs a commentAs an annotation
Python# gdp: law …@gdp_law("…"), a decorator of that name in your code
Ruby, Elixir# gdp: law …Elixir: @gdp_law "…", a module attribute
Java, Kotlin// gdp: law …@GdpLaw("…"), the annotation declared in your code
Rust// gdp: law … or /// gdp: law …#[doc = "gdp: law …"]
Go, Swift, C, C++, TypeScript, Effect, XState// gdp: law …none

The expression: comparisons, + - * by a constant, and or not implies; the state after the step by its fields (self., this., @, l-> or bare; after.x), old(x) or before.x before it; the request’s arguments by name; result and failed; a call of other code answered by the request as f(...); x is None; maps as the code reads them (counts[user], user in counts, sum(balances)); forall k in m: ...; a choice by its value (mode == "closed"). Anything else is refused with why, never dropped, and no stated law goes unaccounted: one no rule takes is reported, exit 2.

Beyond one step: eventually laws; laws about two runs (<secret> never reaches <fields>, isolated by <argument>, agrees with <Class>); a duration over the request’s time (now - received < 30 days); and gdp: cite <law name>: <clause>, which ties a law to the clause it answers, kept in the certificate’s meta and never in what is checked.

What each language reads

Each language is read by its own parser, lowered into one shared form, run symbolically into a rule, and checked against your code by a harness in your language that runs both on thousands of requests. Nothing is approximated: what the reader can’t say exactly is refused at its line, with why.

LanguageReader, and what runs the checkInferred, with nothing writtenNeeds a tagInjected stores
Python.pyPython’s ast; python3the class whose public methods write its state; calls of other code left out, or answered over their annotations (read through your modules)a call whose result declares no typeyes
TypeScript.ts, .jsthe TypeScript compilerthe exported class or function that reads as a rule; an injected function answered over the checker’s typenothing: a compound answer is refusedno
Go.go, a packageGo’s own parser; gothe struct its exported methods write; answers over their declared typesnothing: the types are declaredno
Rust.rs, a cratesyn; cargothe struct its public methods write; calls left outeach answered call (// gdp: answer u32)no
Java.javajavac’s tree API; a JDK 17+ ($JAVA_HOME)the class; answers over declared types; a field’s @Autowireda generic resultyes: a proxy of the interface
Kotlin.ktKotlin’s PSI; kotlinc 2.4 ($KOTLIN_HOME)as Javaa generic resultyes: a proxy of the interface
Swift.swift, a packageswift-syntax; Swift 5.9+ ($GDP_SWIFT)the class; answers over declared types; init parameters typed by a protocola value with no declared typeyes: a conforming class per protocol
Ruby.rbPrism; rubythe class; field and argument types from how the code uses themeach answered call (# gdp: answer int)yes
Elixir.exCode.string_to_quoted; elixirthe module, its GenServer or Agenteach answered callno: the state is a value
C.c, .hclangthe struct the file’s functions write; answers over declared typesnothing: the types are declaredno
C++.cppclang++each class of the file tried, its constructor the startnothing: the types are declaredno
Effecta service, a Schedule in .tsthe TypeScript compiler; your project’s effect (3.x or 4.x)a make effect: its Refs the state, its methods the requests, a yielded error the step’s refusal, a transaction one atomic step and a wait a guard; a retry or repeat policy one state machinenothingthe state is its Refs
XStatea machine in .tsthe TypeScript compiler; your project’s xstate (5.x)the file’s one machine: its context, value and eventnothingthe state is its context

An injected store: a dependency your class is given (a cache client, a repository) and calls by a key, held as a map of the rule’s state; the check gives your code a store that keeps what is set. From research/langs/DESIGN.md.

Language by language

The same limiter in each language where it fits: a law that holds, then a one-line bug that breaks it, then the edge of what is read, with the refusal the CLI prints and, where one exists, the line or gdp.toml entry that settles it. Effect gets a retry policy and a transaction. Every output below is what gdp-wired-cli@0.43.0 printed for the file shown.

Reads .py with Python’s own ast; runs your code with python3.

A law that holds

Two laws over hit, one as a comment and one as a decorator (any decorator named gdp_law that returns the function). old(used) is the value before the step, result what it returned.

limiter.py

def gdp_law(text):
    return lambda f: f


class Limiter:
    def __init__(self, limit: int):
        self.limit, self.used = limit, 0

    # gdp: law a counted hit stays within the limit: result implies used <= limit
    @gdp_law("a counted hit adds its cost: result implies used == old(used) + cost")
    def hit(self, cost: int) -> bool:
        if cost <= 0 or self.used + cost > self.limit:
            return False
        self.used += cost
        return True
$ npx gdp-wired-cli check limiter.py
limiter.py: Limiter (Python)
  checked against the code: 2154 requests from the start, 400 from drawn states, 2 from the prover's witnesses, 3 of 3 branch arms
  the entry inferred: Limiter, the class whose public methods write its state (hit; the others read it)
  names (the code's, then the rule's):
    limit         state     limit_
    used          state     used
    limit         made with limit
    hit(cost)     request   cost
    hit() result  result    hit_result
  laws stated in the code:
    proven   a counted hit stays within the limit  (limiter.py:9)
    proven   a counted hit adds its cost  (limiter.py:10)
  laws proposed (nothing written; state one with the comment under it):
    proven   limit never changes
             # gdp: law limit never changes: limit == old(limit)
    proven   used is never negative
             # gdp: law used is never negative: used >= 0
    proven   used never goes down
             # gdp: law used never goes down: used >= old(used)
    (5 more proposed and broken by a run: not shown)

2 of 2 stated laws proven, 0 broken, 0 unknown, 0 not read

exit 0

A one-line bug

The guard checks the spend before the hit instead of after it. “A counted hit stays within the limit” breaks, with the run that breaks it, as calls of your code.

limiter.py

     def hit(self, cost: int) -> bool:
-        if cost <= 0 or self.used + cost > self.limit:
+        if cost <= 0 or self.used > self.limit:
             return False
$ npx gdp-wired-cli check limiter.py
limiter.py: Limiter (Python)
  checked against the code: 2351 requests from the start, 400 from drawn states, 2 from the prover's witnesses, 3 of 3 branch arms
  the entry inferred: Limiter, the class whose public methods write its state (hit; the others read it)
  names (the code's, then the rule's):
    limit         state     limit_
    used          state     used
    limit         made with limit
    hit(cost)     request   cost
    hit() result  result    hit_result
  laws stated in the code:
    broken   a counted hit stays within the limit  (limiter.py:9)
             result implies used <= limit
             run: made with limit = 1
                  hit(cost=-1)
                  hit(cost=0)
                  hit(cost=3)
    proven   a counted hit adds its cost  (limiter.py:10)
  laws proposed (nothing written; state one with the comment under it):
    proven   limit never changes
             # gdp: law limit never changes: limit == old(limit)
    proven   used is never negative
             # gdp: law used is never negative: used >= 0
    proven   used never goes down
             # gdp: law used never goes down: used >= old(used)
    (5 more proposed and broken by a run: not shown)

1 of 2 stated laws proven, 1 broken, 0 unknown, 0 not read

exit 1

The boundary

A call into your own modules is read through them: its value becomes an input of the request, over the callee’s annotation. Here cost_of has none, so the rule is refused at the line that reads it, and the refusal says how to state it.

limiter.py

from pricing import cost_of


class Limiter:
    def __init__(self, limit: int):
        self.limit, self.used = limit, 0

    # gdp: law a counted hit stays within the limit: result implies used <= limit
    def hit(self, model: str) -> bool:
        cost = cost_of(model)
        if cost <= 0 or self.used + cost > self.limit:
            return False
        self.used += cost
        return True

pricing.py

PRICES = {"small": 1, "large": 5}


def cost_of(model):
    return PRICES.get(model, 10)
$ npx gdp-wired-cli check limiter.py --no-propose
limiter.py: Limiter (Python)
  refused at limiter.py:11:12: cost <= 0: the truth of cost_of(model): the value of cost_of, other code left out; cost_of(model): pricing.cost_of, other code (limiter.py:10:16), whose value is read, and it declares no type: state what it returns (answers: {"cost_of": 'int'}, or a `gdp: answer int` comment on its line)
  laws stated in the code:
    not read a counted hit stays within the limit  (limiter.py:8)
             result implies used <= limit
             the rule was refused

0 of 1 stated laws proven, 0 broken, 0 unknown, 1 not read

exit 2

One line of gdp.toml states what it returns. The output now says the answer is stated, not inferred:

gdp.toml

[rules.Limiter]
answers = {cost_of = "int"}
$ npx gdp-wired-cli check limiter.py --no-propose
limiter.py: Limiter (Python)
  checked against the code: 2154 requests from the start, 400 from drawn states, 2 from the prover's witnesses, 3 of 3 branch arms
  cost_of (limiter.py:10:16): answered by the request (stated), its arguments not read
  names (the code's, then the rule's):
    limit         state     limit_
    used          state     used
    limit         made with limit
    hit(model)    request   model
    cost_of(...)  answered  cost_of
    hit() result  result    hit_result
  laws stated in the code:
    proven   a counted hit stays within the limit  (limiter.py:8)

1 of 1 stated laws proven, 0 broken, 0 unknown, 0 not read

exit 0

Or annotate the callee, and nothing needs stating: the answer is inferred from -> int, and the output says what it assumes.

pricing.py

 
-def cost_of(model):
+def cost_of(model: str) -> int:
     return PRICES.get(model, 10)
$ npx gdp-wired-cli check limiter.py --no-propose
limiter.py: Limiter (Python)
  checked against the code: 2154 requests from the start, 400 from drawn states, 2 from the prover's witnesses, 3 of 3 branch arms
  the entry inferred: Limiter, the class whose public methods write its state (hit; the others read it)
  cost_of (limiter.py:10:16): answered by the request (inferred: its value is read; assumes cost_of may return any int), its arguments not read
  names (the code's, then the rule's):
    limit         state     limit_
    used          state     used
    limit         made with limit
    hit(model)    request   model
    cost_of(...)  answered  cost_of
    hit() result  result    hit_result
  laws stated in the code:
    proven   a counted hit stays within the limit  (limiter.py:8)

1 of 1 stated laws proven, 0 broken, 0 unknown, 0 not read

exit 0

gdp.toml

The few modelling choices a rule needs are written once, beside the code: the nearest gdp.toml from the file up (or [tool.gdp] in pyproject.toml, "gdp" in package.json). Top-level keys hold for every rule; [rules.<name>] for one. A flag on the command line wins over both. TOML has no null: "None" (or "null", "nil") is one.

KeyWhat it states
entry, methodsThe class or functions to read, and which methods are the requests (by default the public ones). Read with none named: the one class whose public methods write its state.
answersWhat a call of other code returns where the code declares no type: answers = {cost = "int"}, {get_allowed_fails_from_policy = "int | None"}. The same as a gdp: answer int comment on the call’s line.
skipCalls stated to change nothing the rule keeps, left out (the same as gdp: skip on the line).
stores.<field>An injected store’s methods (get, set, delete, skip), its value type, the values per key form, and attrs: its attributes held at a value ({"dual_cache.redis_cache" = "None"}: Redis off).
failures"refuse" (the default): an exception or a panic is the step’s refusal. "kept": the step is taken, the state as it was, failed true, for laws about when the code refuses.
onErrorGo and C: "discard" when the caller discards what a failed call wrote (else a write before the failure is refused).
from"any": prove every law from every state the laws allow, for code that steps the rule from states it is handed (loaded from a database, say); the largest inductive set of the stated laws is found.
stricttrue: nothing inferred; the boundary only as stated (answers, skip, stores), any other call of other code refused.
clock"s" or "ms": the unit of the language’s clock, for durations in a law, where the language doesn’t say.
defaults, fields, shareConstructor arguments taken at their defaults; fields held at a value after construction (the claim is for objects so configured); a method’s scalar arguments one input per type and place across methods, so a law over a map they key reads fewer keys.
root, pythonPython: the import root your modules are read from, and the interpreter.

gdp.toml

# every rule: laws about when the code raises
failures = "kept"

[rules.SessionLimiter]
methods = ["hit"]
stores.cache.attrs = {"redis" = "None"}
answers = {lookup_plan = "int | None"}

From a program

The same reading as a library: one import, the file (a path or a URL; a Go package or a Rust crate by any file of it), a law over the rule’s names. The entry is inferred ({entry} names one), and Effect and XState run on the packages your project has. Here, the Python limiter of the Python tab, read from TypeScript:

prove.ts

import {extractPython, proveRule} from 'gdp-wired/extract-py'
const x = extractPython('./limiter.py')
console.log(proveRule(x.rule!, [x.rule!.law('used is never negative', ({used}) => used.atLeast(0))]))
$ bun prove.ts
{
  proven: true,
  checked: true,
}
LanguageFunctionModule
PythonextractPythongdp-wired/extract-py
TypeScriptextractgdp-wired/extract
GoextractGogdp-wired/extract-go
RustextractRustgdp-wired/extract-rs
JavaextractJavagdp-wired/extract-java
KotlinextractKotlingdp-wired/extract-kotlin
SwiftextractSwiftgdp-wired/extract-swift
RubyextractRubygdp-wired/extract-rb
ElixirextractElixirgdp-wired/extract-ex
CextractCgdp-wired/extract-c
C++extractCppgdp-wired/extract-cpp
EffectextractEffectgdp-wired/effect
XStateextractXStategdp-wired/extract

Each module also exports proveRule and proveSteps. The output above is what prove.ts printed with gdp-wired@0.43.0 from npm, on boat. In TypeScript the rule can also be written directly, its laws as code: the guide starts there.

What the boundary claims

A proof holds of your code with every answered call free to return anything its declared type allows, so it holds whatever the callee does. A refutation may rest on a value the callee never returns, so it names what it assumes (assumes … may return -1 (inferred: any int)). Read it, and decide.

Every inferred statement is printed (left out, answered, an injected store, your own code taken as other code), and the check runs both sides on it: a skipped call is run as it is, an answered one is stubbed. A skipped call that raises, writes the state or changes the result is a disagreement, and the rule is refused.

Anything handed the rule’s state is refused: other code, or an injected dependency’s method, given self or this, a nested object, a map, a list, a store the rule holds, or an alias of one, unless you mark the call gdp: skip, stating that it changes nothing the rule keeps. An independent adversarial review found three false proofs there before 0.32, an injected listener or a store’s get handed this; all are refused now and kept as tests, with the other 22 cases (research/langs/adversarial).

Tags go on a call’s line, or on a function’s line or the line above it for every call of it: gdp: skip, gdp: answer [type], and gdp: strict to turn the inference off and keep the boundary only as stated.